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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.737   ! raeburn     4: # $Id: grades.pm,v 1.736 2015/06/09 21:22:48 damieng 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.736     damieng   860:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   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.736     damieng   864:     &js_escape(\%js_lt);
1.597     wenzelju  865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        866:     function checkSelect(checkBox) {
                    867: 	var ctr=0;
                    868: 	var sense="";
                    869: 	if (checkBox.length > 1) {
                    870: 	    for (var i=0; i<checkBox.length; i++) {
                    871: 		if (checkBox[i].checked) {
                    872: 		    ctr++;
                    873: 		}
                    874: 	    }
1.736     damieng   875: 	    sense = '$js_lt{'multiple'}';
1.110     ng        876: 	} else {
                    877: 	    if (checkBox.checked) {
                    878: 		ctr = 1;
                    879: 	    }
1.736     damieng   880: 	    sense = '$js_lt{'single'}';
1.110     ng        881: 	}
                    882: 	if (ctr == 0) {
1.485     albertel  883: 	    alert(sense);
1.110     ng        884: 	    return false;
                    885: 	}
                    886: 	document.gradesub.submit();
                    887:     }
                    888: 
                    889:     function reLoadList(formname) {
1.112     ng        890: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        891: 	formname.command.value = 'submission';
                    892: 	formname.submit();
                    893:     }
1.45      ng        894: LISTJAVASCRIPT
                    895: 
1.118     ng        896:     &commonJSfunctions($request);
1.41      ng        897:     $request->print($result);
1.39      ng        898: 
1.154     albertel  899:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       900: 	"\n";
1.485     albertel  901: 	
1.561     bisitz    902:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    904:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    905:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    906:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    907:                   .&Apache::lonhtmlcommon::row_closure();
                    908:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    909:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    910:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    911:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    912:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  913: 
                    914:     my $submission_options;
1.442     banghart  915:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    916:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  917:     $env{'form.Status'} = $saveStatus;
1.485     albertel  918:     $submission_options.=
1.592     bisitz    919:         '<span class="LC_nobreak">'.
1.624     www       920:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     921:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    922:         '<span class="LC_nobreak">'.
                    923:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     924:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    925:         '<span class="LC_nobreak">'.
1.628     www       926:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     927:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    928:         '<span class="LC_nobreak">'.
                    929:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     930:         &mt('all submissions with details').'</label></span>';
                    931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    932:                   .$submission_options
                    933:                   .&Apache::lonhtmlcommon::row_closure();
                    934: 
                    935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    936:                   .'<select name="increment">'
                    937:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    938:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    939:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    940:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    941:                   .'</select>'
                    942:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  943: 
                    944:     $gradeTable .= 
1.432     banghart  945:         &build_section_inputs().
1.45      ng        946: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  947: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        948: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    949: 
1.618     www       950:     if (exists($env{'form.Status'})) {
1.561     bisitz    951: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        952:     } else {
1.561     bisitz    953:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    954:                       .&Apache::lonhtmlcommon::StatusOptions(
                    955:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    956:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        957:     }
1.112     ng        958: 
1.561     bisitz    959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    960:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    961:                   .&Apache::lonhtmlcommon::row_closure(1)
                    962:                   .&Apache::lonhtmlcommon::end_pick_box();
                    963: 
                    964:     $gradeTable .= '<p>'
1.618     www       965:                   .&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    966:                   .'<input type="hidden" name="command" value="processGroup" />'
                    967:                   .'</p>';
1.249     albertel  968: 
                    969: # checkall buttons
                    970:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        971:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    972:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    973:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  974:     $gradeTable.=&check_buttons();
1.450     banghart  975:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  976:     $gradeTable.= &Apache::loncommon::start_data_table().
                    977: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        978:     my $loop = 0;
                    979:     while ($loop < 2) {
1.485     albertel  980: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    981: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       982: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  983: 	    foreach my $part (sort(@$partlist)) {
                    984: 		my $display_part=
                    985: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    986: 		$gradeTable.=
                    987: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        988: 	    }
1.301     albertel  989: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  990: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        991: 	}
                    992: 	$loop++;
1.126     ng        993: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        994:     }
1.474     albertel  995:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        996: 
1.45      ng        997:     my $ctr = 0;
1.294     albertel  998:     foreach my $student (sort 
                    999: 			 {
                   1000: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1001: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1002: 			     }
                   1003: 			     return $a cmp $b;
                   1004: 			 }
                   1005: 			 (keys(%$fullname))) {
1.41      ng       1006: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1007: 
1.110     ng       1008: 	my %status = ();
1.301     albertel 1009: 
                   1010: 	if ($submitonly eq 'queued') {
                   1011: 	    my %queue_status = 
                   1012: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1013: 							$udom,$uname);
                   1014: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1015: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1016: 	}
                   1017: 
1.618     www      1018: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1019: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1020: 	    my $submitted = 0;
1.164     albertel 1021: 	    my $graded = 0;
1.248     albertel 1022: 	    my $incorrect = 0;
1.110     ng       1023: 	    foreach (keys(%status)) {
1.145     albertel 1024: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1025: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1026: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1027: 		
1.110     ng       1028: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1029: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1030: 		    $submitted = 0;
1.150     albertel 1031: 		    my ($part)=split(/\./,$partid);
1.110     ng       1032: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1033: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1034: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1035: 		}
1.41      ng       1036: 	    }
1.248     albertel 1037: 	    
1.156     albertel 1038: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1039: 				     $submitonly eq 'incorrect' ||
                   1040: 				     $submitonly eq 'graded'));
1.248     albertel 1041: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1042: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1043: 	}
1.34      ng       1044: 
1.45      ng       1045: 	$ctr++;
1.249     albertel 1046: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1047:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1048: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1049: 	    if ($ctr%2 ==1) {
                   1050: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1051: 	    }
1.126     ng       1052: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1053:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1054:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1055: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1056: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1057: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1058: 
1.618     www      1059: 	    if ($submitonly ne 'all') {
1.524     raeburn  1060: 		foreach (sort(keys(%status))) {
1.485     albertel 1061: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1062: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1063: 		}
1.41      ng       1064: 	    }
1.126     ng       1065: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1066: 	    if ($ctr%2 ==0) {
                   1067: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1068: 	    }
1.41      ng       1069: 	}
                   1070:     }
1.110     ng       1071:     if ($ctr%2 ==1) {
1.126     ng       1072: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1073: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1074: 		foreach (@$partlist) {
                   1075: 		    $gradeTable.='<td>&nbsp;</td>';
                   1076: 		}
1.301     albertel 1077: 	    } elsif ($submitonly eq 'queued') {
                   1078: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1079: 	    }
1.474     albertel 1080: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1081:     }
                   1082: 
1.474     albertel 1083:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1084:         '<input type="button" '.
                   1085:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1086:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1087:     if ($ctr == 0) {
1.96      albertel 1088: 	my $num_students=(scalar(keys(%$fullname)));
                   1089: 	if ($num_students eq 0) {
1.485     albertel 1090: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1091: 	} else {
1.171     albertel 1092: 	    my $submissions='submissions';
                   1093: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1094: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1095: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1096: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1097: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1098: 		    $num_students).
                   1099: 		'</span><br />';
1.96      albertel 1100: 	}
1.46      ng       1101:     } elsif ($ctr == 1) {
1.474     albertel 1102: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1103:     }
                   1104:     $request->print($gradeTable);
1.44      ng       1105:     return '';
1.10      ng       1106: }
                   1107: 
1.44      ng       1108: #---- Called from the listStudents routine
1.249     albertel 1109: 
                   1110: sub check_script {
                   1111:     my ($form, $type)=@_;
1.597     wenzelju 1112:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1113:     function checkall() {
                   1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1115:             ele = document.forms.'.$form.'.elements[i];
                   1116:             if (ele.name == "'.$type.'") {
                   1117:             document.forms.'.$form.'.elements[i].checked=true;
                   1118:                                        }
                   1119:         }
                   1120:     }
                   1121: 
                   1122:     function checksec() {
                   1123:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1124:             ele = document.forms.'.$form.'.elements[i];
                   1125:            string = document.forms.'.$form.'.chksec.value;
                   1126:            if
                   1127:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1128:               document.forms.'.$form.'.elements[i].checked=true;
                   1129:             }
                   1130:         }
                   1131:     }
                   1132: 
                   1133: 
                   1134:     function uncheckall() {
                   1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1136:             ele = document.forms.'.$form.'.elements[i];
                   1137:             if (ele.name == "'.$type.'") {
                   1138:             document.forms.'.$form.'.elements[i].checked=false;
                   1139:                                        }
                   1140:         }
                   1141:     }
                   1142: 
1.597     wenzelju 1143: '."\n");
1.249     albertel 1144:     return $chkallscript;
                   1145: }
                   1146: 
                   1147: sub check_buttons {
1.485     albertel 1148:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1149:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1150:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1151:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1152:     return $buttons;
                   1153: }
                   1154: 
1.44      ng       1155: #     Displays the submissions for one student or a group of students
1.34      ng       1156: sub processGroup {
1.619     www      1157:     my ($request,$symb)  = @_;
1.41      ng       1158:     my $ctr        = 0;
1.155     albertel 1159:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1160:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1161: 
1.396     banghart 1162:     foreach my $student (@stuchecked) {
                   1163: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1164: 	$env{'form.student'}        = $uname;
                   1165: 	$env{'form.userdom'}        = $udom;
                   1166: 	$env{'form.fullname'}       = $fullname;
1.619     www      1167: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1168: 	$ctr++;
                   1169:     }
                   1170:     return '';
1.35      ng       1171: }
1.34      ng       1172: 
1.44      ng       1173: #------------------------------------------------------------------------------------
                   1174: #
                   1175: #-------------------------- Next few routines handles grading by student, essentially
                   1176: #                           handles essay response type problem/part
                   1177: #
                   1178: #--- Javascript to handle the submission page functionality ---
                   1179: sub sub_page_js {
                   1180:     my $request = shift;
1.736     damieng  1181:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1182:     &js_escape(\$alertmsg);
1.597     wenzelju 1183:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1184:     function updateRadio(formname,id,weight) {
1.125     ng       1185: 	var gradeBox = formname["GD_BOX"+id];
                   1186: 	var radioButton = formname["RADVAL"+id];
                   1187: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1188: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1189: 	gradeBox.value = pts;
                   1190: 	var resetbox = false;
                   1191: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1192: 	    alert("$alertmsg"+pts);
1.71      ng       1193: 	    for (var i=0; i<radioButton.length; i++) {
                   1194: 		if (radioButton[i].checked) {
                   1195: 		    gradeBox.value = i;
                   1196: 		    resetbox = true;
                   1197: 		}
                   1198: 	    }
                   1199: 	    if (!resetbox) {
                   1200: 		formtextbox.value = "";
                   1201: 	    }
                   1202: 	    return;
1.44      ng       1203: 	}
1.71      ng       1204: 
                   1205: 	if (pts > weight) {
                   1206: 	    var resp = confirm("You entered a value ("+pts+
                   1207: 			       ") greater than the weight for the part. Accept?");
                   1208: 	    if (resp == false) {
1.125     ng       1209: 		gradeBox.value = oldpts;
1.71      ng       1210: 		return;
                   1211: 	    }
1.44      ng       1212: 	}
1.13      albertel 1213: 
1.71      ng       1214: 	for (var i=0; i<radioButton.length; i++) {
                   1215: 	    radioButton[i].checked=false;
                   1216: 	    if (pts == i && pts != "") {
                   1217: 		radioButton[i].checked=true;
                   1218: 	    }
                   1219: 	}
                   1220: 	updateSelect(formname,id);
1.125     ng       1221: 	formname["stores"+id].value = "0";
1.41      ng       1222:     }
1.5       albertel 1223: 
1.72      ng       1224:     function writeBox(formname,id,pts) {
1.125     ng       1225: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1226: 	if (checkSolved(formname,id) == 'update') {
                   1227: 	    gradeBox.value = pts;
                   1228: 	} else {
1.125     ng       1229: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1230: 	    gradeBox.value = oldpts;
1.125     ng       1231: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1232: 	    for (var i=0; i<radioButton.length; i++) {
                   1233: 		radioButton[i].checked=false;
1.72      ng       1234: 		if (i == oldpts) {
1.71      ng       1235: 		    radioButton[i].checked=true;
                   1236: 		}
                   1237: 	    }
1.41      ng       1238: 	}
1.125     ng       1239: 	formname["stores"+id].value = "0";
1.71      ng       1240: 	updateSelect(formname,id);
                   1241: 	return;
1.41      ng       1242:     }
1.44      ng       1243: 
1.71      ng       1244:     function clearRadBox(formname,id) {
                   1245: 	if (checkSolved(formname,id) == 'noupdate') {
                   1246: 	    updateSelect(formname,id);
                   1247: 	    return;
                   1248: 	}
1.125     ng       1249: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1250: 	for (var i=0; i<gradeSelect.length; i++) {
                   1251: 	    if (gradeSelect[i].selected) {
                   1252: 		var selectx=i;
                   1253: 	    }
                   1254: 	}
1.125     ng       1255: 	var stores = formname["stores"+id];
1.71      ng       1256: 	if (selectx == stores.value) { return };
1.125     ng       1257: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1258: 	gradeBox.value = "";
1.125     ng       1259: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1260: 	for (var i=0; i<radioButton.length; i++) {
                   1261: 	    radioButton[i].checked=false;
                   1262: 	}
                   1263: 	stores.value = selectx;
                   1264:     }
1.5       albertel 1265: 
1.71      ng       1266:     function checkSolved(formname,id) {
1.125     ng       1267: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1268: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1269: 	    if (!reply) {return "noupdate";}
1.120     ng       1270: 	    formname.overRideScore.value = 'yes';
1.41      ng       1271: 	}
1.71      ng       1272: 	return "update";
1.13      albertel 1273:     }
1.71      ng       1274: 
                   1275:     function updateSelect(formname,id) {
1.125     ng       1276: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1277: 	return;
1.41      ng       1278:     }
1.33      ng       1279: 
1.121     ng       1280: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1281:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1282: 	formname.gradeOpt.value = val;
1.71      ng       1283: 	if (val == "Save & Next") {
                   1284: 	    for (i=0;i<=total;i++) {
                   1285: 		for (j=0;j<parttot;j++) {
1.125     ng       1286: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1287: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1288: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1289: 			if (points == "") {
1.125     ng       1290: 			    var name = formname["name"+i].value;
1.129     ng       1291: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1292: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1293: 					       ", part "+partid+". Continue?");
1.71      ng       1294: 			    if (resp == false) {
1.125     ng       1295: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1296: 				return false;
                   1297: 			    }
                   1298: 			}
                   1299: 		    }
                   1300: 		}
                   1301: 	    }
                   1302: 	}
1.120     ng       1303: 	formname.submit();
                   1304:     }
                   1305: 
1.71      ng       1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1307:     function checkSubmitPage(formname,total) {
                   1308: 	noscore = new Array(100);
                   1309: 	var ptr = 0;
                   1310: 	for (i=1;i<total;i++) {
1.125     ng       1311: 	    var partid = formname["q_"+i].value;
1.127     ng       1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1314: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1315: 		if (points == "" && status != "correct_by_student") {
                   1316: 		    noscore[ptr] = i;
                   1317: 		    ptr++;
                   1318: 		}
                   1319: 	    }
                   1320: 	}
                   1321: 	if (ptr != 0) {
                   1322: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1323: 	    var prolist = "";
                   1324: 	    if (ptr == 1) {
                   1325: 		prolist = noscore[0];
                   1326: 	    } else {
                   1327: 		var i = 0;
                   1328: 		while (i < ptr-1) {
                   1329: 		    prolist += noscore[i]+", ";
                   1330: 		    i++;
                   1331: 		}
                   1332: 		prolist += "and "+noscore[i];
                   1333: 	    }
                   1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1335: 	    if (resp == false) {
                   1336: 		return false;
                   1337: 	    }
                   1338: 	}
1.45      ng       1339: 
1.71      ng       1340: 	formname.submit();
                   1341:     }
                   1342: SUBJAVASCRIPT
                   1343: }
1.45      ng       1344: 
1.71      ng       1345: #--- javascript for essay type problem --
                   1346: sub sub_page_kw_js {
                   1347:     my $request = shift;
1.80      ng       1348:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1349:     &commonJSfunctions($request);
1.350     albertel 1350: 
1.629     www      1351:     my $inner_js_msg_central= (<<INNERJS);
                   1352: <script type="text/javascript">
1.350     albertel 1353:     function checkInput() {
                   1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1356:       var usrctr = document.msgcenter.usrctr.value;
                   1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1359: 
                   1360:       var msgchk = "";
                   1361:       if (document.msgcenter.subchk.checked) {
                   1362:          msgchk = "msgsub,";
                   1363:       }
                   1364:       var includemsg = 0;
                   1365:       for (var i=1; i<=nmsg; i++) {
                   1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1367:           var frmmsg = document.msgcenter["msg"+i];
                   1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1369:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1370:           showflg.value = "1";
                   1371:           var chkbox = document.msgcenter["msgn"+i];
                   1372:           if (chkbox.checked) {
                   1373:              msgchk += "savemsg"+i+",";
                   1374:              includemsg = 1;
                   1375:           }
                   1376:       }
                   1377:       if (document.msgcenter.newmsgchk.checked) {
                   1378:          msgchk += "newmsg"+usrctr;
                   1379:          includemsg = 1;
                   1380:       }
                   1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1384:       includemsg.value = msgchk;
                   1385: 
                   1386:       self.close()
                   1387: 
                   1388:     }
1.629     www      1389: </script>
1.350     albertel 1390: INNERJS
                   1391: 
1.629     www      1392:     my $inner_js_highlight_central= (<<INNERJS);
                   1393: <script type="text/javascript">
1.351     albertel 1394:     function updateChoice(flag) {
                   1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1398:       opener.document.SCORE.refresh.value = "on";
                   1399:       if (opener.document.SCORE.keywords.value!=""){
                   1400:          opener.document.SCORE.submit();
                   1401:       }
                   1402:       self.close()
                   1403:     }
1.629     www      1404: </script>
1.351     albertel 1405: INNERJS
                   1406: 
                   1407:     my $start_page_msg_central = 
                   1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1409: 				       {'js_ready'  => 1,
                   1410: 					'only_body' => 1,
                   1411: 					'bgcolor'   =>'#FFFFFF',});
                   1412:     my $end_page_msg_central = 
                   1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1414: 
                   1415: 
                   1416:     my $start_page_highlight_central = 
                   1417:         &Apache::loncommon::start_page('Highlight Central',
                   1418: 				       $inner_js_highlight_central,
1.350     albertel 1419: 				       {'js_ready'  => 1,
                   1420: 					'only_body' => 1,
                   1421: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1422:     my $end_page_highlight_central = 
1.350     albertel 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1424: 
1.219     www      1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1426:     $docopen=~s/^document\.//;
1.736     damieng  1427:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1429:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1430:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1431:                 col1 => 'red',
                   1432:                 col2 => 'green',
                   1433:                 col3 => 'blue',
                   1434:                 siz1 => 'normal',
                   1435:                 siz2 => '+1',
                   1436:                 siz3 => '+2',
                   1437:                 sty1 => 'normal',
                   1438:                 sty2 => 'italic',
                   1439:                 sty3 => 'bold',
                   1440:              );
                   1441:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1442:                 comp => 'Compose Message for: ',
                   1443:                 incl => 'Include',
1.656     raeburn  1444:                 type => 'Type',
1.652     raeburn  1445:                 subj => 'Subject',
                   1446:                 mesa => 'Message',
                   1447:                 new  => 'New',
                   1448:                 save => 'Save',
                   1449:                 canc => 'Cancel',
                   1450:                 kehi => 'Keyword Highlight Options',
                   1451:                 txtc => 'Text Color',
                   1452:                 font => 'Font Size',
1.656     raeburn  1453:                 fnst => 'Font Style',
1.652     raeburn  1454:              );
1.736     damieng  1455:     &js_escape(\%js_lt);
                   1456:     &html_escape(\%html_js_lt);
                   1457:     &js_escape(\%html_js_lt);
1.597     wenzelju 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1459: 
1.44      ng       1460: //===================== Show list of keywords ====================
1.122     ng       1461:   function keywords(formname) {
1.736     damieng  1462:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1463:     if (nret==null) return;
1.122     ng       1464:     formname.keywords.value = nret;
1.44      ng       1465: 
1.122     ng       1466:     if (formname.keywords.value != "") {
1.128     ng       1467: 	formname.refresh.value = "on";
1.122     ng       1468: 	formname.submit();
1.44      ng       1469:     }
                   1470:     return;
                   1471:   }
                   1472: 
                   1473: //===================== Script to view submitted by ==================
                   1474:   function viewSubmitter(submitter) {
                   1475:     document.SCORE.refresh.value = "on";
                   1476:     document.SCORE.NCT.value = "1";
                   1477:     document.SCORE.unamedom0.value = submitter;
                   1478:     document.SCORE.submit();
                   1479:     return;
                   1480:   }
                   1481: 
                   1482: //===================== Script to add keyword(s) ==================
                   1483:   function getSel() {
                   1484:     if (document.getSelection) txt = document.getSelection();
                   1485:     else if (document.selection) txt = document.selection.createRange().text;
                   1486:     else return;
                   1487:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1488:     if (cleantxt=="") {
1.736     damieng  1489: 	alert("$js_lt{'plse'}");
1.44      ng       1490: 	return;
                   1491:     }
1.736     damieng  1492:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1493:     if (nret==null) return;
1.127     ng       1494:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1495:     if (document.SCORE.keywords.value != "") {
1.127     ng       1496: 	document.SCORE.refresh.value = "on";
1.44      ng       1497: 	document.SCORE.submit();
                   1498:     }
                   1499:     return;
                   1500:   }
                   1501: 
                   1502: //====================== Script for composing message ==============
1.80      ng       1503:    // preload images
                   1504:    img1 = new Image();
                   1505:    img1.src = "$iconpath/mailbkgrd.gif";
                   1506:    img2 = new Image();
                   1507:    img2.src = "$iconpath/mailto.gif";
                   1508: 
1.44      ng       1509:   function msgCenter(msgform,usrctr,fullname) {
                   1510:     var Nmsg  = msgform.savemsgN.value;
                   1511:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1512:     var subject = msgform.msgsub.value;
1.127     ng       1513:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1514:     re = /msgsub/;
                   1515:     var shwsel = "";
                   1516:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1517:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1518:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1519:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1520: 	var testmsg = "savemsg"+i+",";
                   1521: 	re = new RegExp(testmsg,"g");
1.44      ng       1522: 	shwsel = "";
                   1523: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1524: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1525: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1526: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1527: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1528:     }
1.125     ng       1529:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1530:     shwsel = "";
                   1531:     re = /newmsg/;
                   1532:     if (re.test(msgchk)) { shwsel = "checked" }
                   1533:     newMsg(newmsg,shwsel);
                   1534:     msgTail(); 
                   1535:     return;
                   1536:   }
                   1537: 
1.123     ng       1538:   function checkEntities(strx) {
                   1539:     if (strx.length == 0) return strx;
                   1540:     var orgStr = ["&", "<", ">", '"']; 
                   1541:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1542:     var counter = 0;
                   1543:     while (counter < 4) {
                   1544: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1545: 	counter++;
                   1546:     }
                   1547:     return strx;
                   1548:   }
                   1549: 
                   1550:   function strReplace(strx, orgStr, newStr) {
                   1551:     return strx.split(orgStr).join(newStr);
                   1552:   }
                   1553: 
1.44      ng       1554:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1555:     var height = 70*Nmsg+250;
1.44      ng       1556:     if (height > 600) {
                   1557: 	height = 600;
                   1558:     }
1.118     ng       1559:     var xpos = (screen.width-600)/2;
                   1560:     xpos = (xpos < 0) ? '0' : xpos;
                   1561:     var ypos = (screen.height-height)/2-30;
                   1562:     ypos = (ypos < 0) ? '0' : ypos;
                   1563: 
1.668     www      1564:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1565:     pWin.focus();
                   1566:     pDoc = pWin.document;
1.219     www      1567:     pDoc.$docopen;
1.351     albertel 1568:     pDoc.write('$start_page_msg_central');
1.76      ng       1569: 
                   1570:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1571:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1572:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1573: 
1.676     golterma 1574:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1575:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1576: }
                   1577:     function displaySubject(msg,shwsel) {
1.76      ng       1578:     pDoc = pWin.document;
1.676     golterma 1579:     pDoc.write("<tr>");
                   1580:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1581:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1582:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1583: }
                   1584: 
1.72      ng       1585:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1586:     pDoc = pWin.document;
1.676     golterma 1587:     pDoc.write("<tr>");
                   1588:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1589:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1590:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1591: }
                   1592: 
                   1593:   function newMsg(newmsg,shwsel) {
1.76      ng       1594:     pDoc = pWin.document;
1.676     golterma 1595:     pDoc.write("<tr>");
                   1596:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1597:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1598:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1599: }
                   1600: 
                   1601:   function msgTail() {
1.76      ng       1602:     pDoc = pWin.document;
1.676     golterma 1603:     //pDoc.write("<\\/table>");
1.465     albertel 1604:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1605:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1606:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1607:     pDoc.write("<\\/form>");
1.351     albertel 1608:     pDoc.write('$end_page_msg_central');
1.128     ng       1609:     pDoc.close();
1.44      ng       1610: }
                   1611: 
                   1612: //====================== Script for keyword highlight options ==============
                   1613:   function kwhighlight() {
                   1614:     var kwclr    = document.SCORE.kwclr.value;
                   1615:     var kwsize   = document.SCORE.kwsize.value;
                   1616:     var kwstyle  = document.SCORE.kwstyle.value;
                   1617:     var redsel = "";
                   1618:     var grnsel = "";
                   1619:     var blusel = "";
1.736     damieng  1620:     var txtcol1 = "$js_lt{'col1'}";
                   1621:     var txtcol2 = "$js_lt{'col2'}";
                   1622:     var txtcol3 = "$js_lt{'col3'}";
                   1623:     var txtsiz1 = "$js_lt{'siz1'}";
                   1624:     var txtsiz2 = "$js_lt{'siz2'}";
                   1625:     var txtsiz3 = "$js_lt{'siz3'}";
                   1626:     var txtsty1 = "$js_lt{'sty1'}";
                   1627:     var txtsty2 = "$js_lt{'sty2'}";
                   1628:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1629:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1630:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1631:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1632:     var sznsel = "";
                   1633:     var sz1sel = "";
                   1634:     var sz2sel = "";
1.718     bisitz   1635:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1636:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1637:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1638:     var synsel = "";
                   1639:     var syisel = "";
                   1640:     var sybsel = "";
1.718     bisitz   1641:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1642:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1643:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1644:     highlightCentral();
1.718     bisitz   1645:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1646:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1647:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1648:     highlightend();
                   1649:     return;
                   1650:   }
                   1651: 
                   1652:   function highlightCentral() {
1.76      ng       1653: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1654:     var xpos = (screen.width-400)/2;
                   1655:     xpos = (xpos < 0) ? '0' : xpos;
                   1656:     var ypos = (screen.height-330)/2-30;
                   1657:     ypos = (ypos < 0) ? '0' : ypos;
                   1658: 
1.206     albertel 1659:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1660:     hwdWin.focus();
                   1661:     var hDoc = hwdWin.document;
1.219     www      1662:     hDoc.$docopen;
1.351     albertel 1663:     hDoc.write('$start_page_highlight_central');
1.76      ng       1664:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1665:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1666: 
1.718     bisitz   1667:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1668:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1669:   }
                   1670: 
                   1671:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1672:     var hDoc = hwdWin.document;
1.718     bisitz   1673:     hDoc.write("<tr>");
1.76      ng       1674:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1675:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1676:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1677:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1678:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1679:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1680:     hDoc.write("<\\/tr>");
1.44      ng       1681:   }
                   1682: 
                   1683:   function highlightend() { 
1.76      ng       1684:     var hDoc = hwdWin.document;
1.718     bisitz   1685:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1686:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1687:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1688:     hDoc.write("<\\/form>");
1.351     albertel 1689:     hDoc.write('$end_page_highlight_central');
1.128     ng       1690:     hDoc.close();
1.44      ng       1691:   }
                   1692: 
                   1693: SUBJAVASCRIPT
                   1694: }
                   1695: 
1.349     albertel 1696: sub get_increment {
1.348     bowersj2 1697:     my $increment = $env{'form.increment'};
                   1698:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1699:         $increment != .1) {
                   1700:         $increment = 1;
                   1701:     }
                   1702:     return $increment;
                   1703: }
                   1704: 
1.585     bisitz   1705: sub gradeBox_start {
                   1706:     return (
                   1707:         &Apache::loncommon::start_data_table()
                   1708:        .&Apache::loncommon::start_data_table_header_row()
                   1709:        .'<th>'.&mt('Part').'</th>'
                   1710:        .'<th>'.&mt('Points').'</th>'
                   1711:        .'<th>&nbsp;</th>'
                   1712:        .'<th>'.&mt('Assign Grade').'</th>'
                   1713:        .'<th>'.&mt('Weight').'</th>'
                   1714:        .'<th>'.&mt('Grade Status').'</th>'
                   1715:        .&Apache::loncommon::end_data_table_header_row()
                   1716:     );
                   1717: }
                   1718: 
                   1719: sub gradeBox_end {
                   1720:     return (
                   1721:         &Apache::loncommon::end_data_table()
                   1722:     );
                   1723: }
1.71      ng       1724: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1725: sub gradeBox {
1.322     albertel 1726:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1727:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1728: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1729:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1730:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1731:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1732:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1733:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1734: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1735:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1736:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1737:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1738: 				       [$partid]);
                   1739:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1740:     if ($last_resets{$partid}) {
                   1741:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1742:     }
1.695     bisitz   1743:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1744:     my $ctr = 0;
1.348     bowersj2 1745:     my $thisweight = 0;
1.349     albertel 1746:     my $increment = &get_increment();
1.485     albertel 1747: 
                   1748:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1749:     while ($thisweight<=$wgt) {
1.532     bisitz   1750: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1751:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1752: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1753: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1754: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1755:         $thisweight += $increment;
1.71      ng       1756: 	$ctr++;
                   1757:     }
1.485     albertel 1758:     $radio.='</tr></table>';
                   1759: 
                   1760:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1761: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1762: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1763: 	$wgt.')" /></td>'."\n";
1.485     albertel 1764:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1765: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1766: 	' </td>'."\n";
                   1767:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1768: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1769:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1770: 	$line.='<option></option>'.
                   1771: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1772:     } else {
1.485     albertel 1773: 	$line.='<option selected="selected"></option>'.
                   1774: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1775:     }
1.485     albertel 1776:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1777: 
                   1778: 
                   1779:     $result .= 
1.695     bisitz   1780: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1781:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1782:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1783:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1784: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1785: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1786: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1787:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1788:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1789:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1790:         $aggtries.'" />'."\n";
1.582     raeburn  1791:     my $res_error;
                   1792:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1793:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1794:     if ($res_error) {
                   1795:         return &navmap_errormsg();
                   1796:     }
1.318     banghart 1797:     return $result;
                   1798: }
1.322     albertel 1799: 
                   1800: sub handback_box {
1.623     www      1801:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1802:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1803:     my (@respids);
1.652     raeburn  1804:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1805:     foreach my $part_response_id (@part_response_id) {
                   1806:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1807:         if ($part eq $partid) {
1.375     albertel 1808:             push(@respids,$resp);
1.323     banghart 1809:         }
                   1810:     }
1.318     banghart 1811:     my $result;
1.323     banghart 1812:     foreach my $respid (@respids) {
1.322     albertel 1813: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1814: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1815: 	next if (!@$files);
1.654     raeburn  1816: 	my $file_counter = 0;
1.313     banghart 1817: 	foreach my $file (@$files) {
1.368     banghart 1818: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1819:                 $file_counter++;
1.368     banghart 1820:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1821:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1822:     	        $file_disp = "$name.$ext";
                   1823:     	        $file = $file_path.$file_disp;
                   1824:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1825:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1826:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1827:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1828: 	    }
1.322     albertel 1829: 	}
1.654     raeburn  1830:         if ($file_counter) {
                   1831:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1832:                        '<span class="LC_info">'.
                   1833:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1834:         }
1.313     banghart 1835:     }
1.318     banghart 1836:     return $result;    
1.71      ng       1837: }
1.44      ng       1838: 
1.58      albertel 1839: sub show_problem {
1.382     albertel 1840:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1841:     my $rendered;
1.382     albertel 1842:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1843:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1844:     if ($mode eq 'both' or $mode eq 'text') {
                   1845: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1846: 						       $env{'request.course.id'},
                   1847: 						       undef,\%form);
1.144     albertel 1848:     }
1.58      albertel 1849:     if ($removeform) {
                   1850: 	$rendered=~s|<form(.*?)>||g;
                   1851: 	$rendered=~s|</form>||g;
1.374     albertel 1852: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1853:     }
1.144     albertel 1854:     my $companswer;
                   1855:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1856: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1857: 	$companswer=
                   1858: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1859: 						    $env{'request.course.id'},
                   1860: 						    %form);
1.144     albertel 1861:     }
1.58      albertel 1862:     if ($removeform) {
                   1863: 	$companswer=~s|<form(.*?)>||g;
                   1864: 	$companswer=~s|</form>||g;
1.144     albertel 1865: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1866:     }
1.671     raeburn  1867:     my $renderheading = &mt('View of the problem');
                   1868:     my $answerheading = &mt('Correct answer');
                   1869:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1870:         my $stu_fullname = $env{'form.fullname'};
                   1871:         if ($stu_fullname eq '') {
                   1872:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1873:         }
                   1874:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1875:         if ($forwhom ne '') {
                   1876:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1877:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1878:         }
                   1879:     }
1.468     albertel 1880:     $rendered=
1.588     bisitz   1881:         '<div class="LC_Box">'
1.671     raeburn  1882:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1883:        .$rendered
                   1884:        .'</div>';
1.468     albertel 1885:     $companswer=
1.588     bisitz   1886:         '<div class="LC_Box">'
1.671     raeburn  1887:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1888:        .$companswer
                   1889:        .'</div>';
1.468     albertel 1890:     my $result;
1.144     albertel 1891:     if ($mode eq 'both') {
1.588     bisitz   1892:         $result=$rendered.$companswer;
1.144     albertel 1893:     } elsif ($mode eq 'text') {
1.588     bisitz   1894:         $result=$rendered;
1.144     albertel 1895:     } elsif ($mode eq 'answer') {
1.588     bisitz   1896:         $result=$companswer;
1.144     albertel 1897:     }
1.71      ng       1898:     return $result;
1.58      albertel 1899: }
1.397     albertel 1900: 
1.396     banghart 1901: sub files_exist {
                   1902:     my ($r, $symb) = @_;
                   1903:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1904: 
1.396     banghart 1905:     foreach my $student (@students) {
                   1906:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1907:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1908: 					      $udom,$uname);
1.396     banghart 1909:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1910:         foreach my $submission (@$string) {
                   1911:             my ($partid,$respid) =
                   1912: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1913:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1914: 					   \%record);
                   1915:             return 1 if (@$files);
1.396     banghart 1916:         }
                   1917:     }
1.397     albertel 1918:     return 0;
1.396     banghart 1919: }
1.397     albertel 1920: 
1.394     banghart 1921: sub download_all_link {
                   1922:     my ($r,$symb) = @_;
1.621     www      1923:     unless (&files_exist($r, $symb)) {
                   1924:        $r->print(&mt('There are currently no submitted documents.'));
                   1925:        return;
                   1926:     }
                   1927: 
1.395     albertel 1928:     my $all_students = 
                   1929: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1930: 
                   1931:     my $parts =
                   1932: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1933: 
1.394     banghart 1934:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1935:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1936:                              'cgi.'.$identifier.'.symb' => $symb,
                   1937:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1938:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1939: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1940:     return;
                   1941: }
                   1942: 
                   1943: sub submit_download_link {
                   1944:     my ($request,$symb) = @_;
                   1945:     if (!$symb) { return ''; }
                   1946: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1947:     &download_all_link($request,$symb);
1.394     banghart 1948: }
1.395     albertel 1949: 
1.432     banghart 1950: sub build_section_inputs {
                   1951:     my $section_inputs;
                   1952:     if ($env{'form.section'} eq '') {
                   1953:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1954:     } else {
                   1955:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1956:         foreach my $section (@sections) {
1.432     banghart 1957:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1958:         }
                   1959:     }
                   1960:     return $section_inputs;
                   1961: }
                   1962: 
1.44      ng       1963: # --------------------------- show submissions of a student, option to grade 
                   1964: sub submission {
1.608     www      1965:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1966:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1967:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1968:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1969:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1970: 
1.605     www      1971:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1972:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1973: 
                   1974:     if (!&canview($usec)) {
1.712     bisitz   1975:         $request->print(
                   1976:             '<span class="LC_warning">'.
1.713     bisitz   1977:             &mt('Unable to view requested student.').
1.712     bisitz   1978:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1979:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1980:             '</span>');
1.104     albertel 1981: 	return;
                   1982:     }
                   1983: 
1.257     albertel 1984:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1985:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1986:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1987:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1988:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1989: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1990: 	'/check.gif" height="16" border="0" />';
1.41      ng       1991: 
                   1992:     # header info
                   1993:     if ($counter == 0) {
                   1994: 	&sub_page_js($request);
1.621     www      1995: 	&sub_page_kw_js($request);
1.118     ng       1996: 
1.44      ng       1997: 	# option to display problem, only once else it cause problems 
                   1998:         # with the form later since the problem has a form.
1.257     albertel 1999: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2000: 	    my $mode;
1.257     albertel 2001: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2002: 		$mode='both';
1.257     albertel 2003: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2004: 		$mode='text';
1.257     albertel 2005: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2006: 		$mode='answer';
                   2007: 	    }
1.329     albertel 2008: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2009: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2010: 	}
1.441     www      2011: 
1.704     raeburn  2012: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2013:         # if this subroutine has been called once.
1.41      ng       2014: 	my %keyhash = ();
1.624     www      2015: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2016:         if (1) {
1.41      ng       2017: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2018: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2019: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2020: 
1.257     albertel 2021: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2022: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2023: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2024: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2025: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2026: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2027: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2028: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2029: 	}
1.257     albertel 2030: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2031: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2032: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2033: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2034: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2035: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2036: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2037: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2038: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2039: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2040: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2041: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2042: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2043: 			&build_section_inputs().
1.326     albertel 2044: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2045: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2046: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2047: #	if ($env{'form.handgrade'} eq 'yes') {
                   2048:         if (1) {
1.257     albertel 2049: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2050: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2051: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2052: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2053: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2054: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2055: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2056: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2057: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2058: 	    }
1.123     ng       2059: 	}
1.41      ng       2060: 	
                   2061: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2062: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2063: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2064: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2065: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2066: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2067: 		'" />'."\n".
                   2068: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2069: 	    $cts++;
                   2070: 	}
                   2071: 	$request->print($prnmsg);
1.32      ng       2072: 
1.624     www      2073: #	if ($env{'form.handgrade'} eq 'yes') {
                   2074:         if (1) {
1.652     raeburn  2075: 
                   2076:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2077:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2078:                           keyw => 'Keyword Options',
1.655     raeburn  2079:                           list => 'List',
1.652     raeburn  2080:                           past => 'Paste Selection to List',
1.661     www      2081:                           high => 'Highlight Attribute',
1.652     raeburn  2082:                      );    
1.88      www      2083: #
                   2084: # Print out the keyword options line
                   2085: #
1.718     bisitz   2086: 	    $request->print(
                   2087:                 '<div class="LC_columnSection">'
                   2088:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2089:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2090:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2091:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2092:  class="page">'.$lt{'past'}.'</a>',
                   2093:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2094:                     {legend => $lt{'keyw'}})
                   2095:                .'</fieldset></div>'
                   2096:             );
                   2097: 
1.88      www      2098: #
                   2099: # Load the other essays for similarity check
                   2100: #
1.324     albertel 2101:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2102: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2103: 	    $apath=&escape($apath);
1.88      www      2104: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2105:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2106:         }
                   2107:     }
1.44      ng       2108: 
1.441     www      2109: # This is where output for one specific student would start
1.592     bisitz   2110:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2111:     $request->print(
                   2112:         "\n\n"
                   2113:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2114:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2115:        ."\n"
                   2116:     );
1.441     www      2117: 
1.592     bisitz   2118:     # Show additional functions if allowed
                   2119:     if ($perm{'vgr'}) {
                   2120:         $request->print(
                   2121:             &Apache::loncommon::track_student_link(
1.708     bisitz   2122:                 'View recent activity',
1.592     bisitz   2123:                 $uname,$udom,'check')
                   2124:            .' '
                   2125:         );
                   2126:     }
                   2127:     if ($perm{'opa'}) {
                   2128:         $request->print(
                   2129:             &Apache::loncommon::pprmlink(
                   2130:                 &mt('Set/Change parameters'),
                   2131:                 $uname,$udom,$symb,'check'));
                   2132:     }
                   2133: 
                   2134:     # Show Problem
1.257     albertel 2135:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2136: 	my $mode;
1.257     albertel 2137: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2138: 	    $mode='both';
1.257     albertel 2139: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2140: 	    $mode='text';
1.257     albertel 2141: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2142: 	    $mode='answer';
                   2143: 	}
1.329     albertel 2144: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2145: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2146:     }
1.144     albertel 2147: 
1.257     albertel 2148:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2149:     my $res_error;
                   2150:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2151:     if ($res_error) {
                   2152:         $request->print(&navmap_errormsg());
                   2153:         return;
                   2154:     }
1.41      ng       2155: 
1.44      ng       2156:     # Display student info
1.41      ng       2157:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2158: 
                   2159:     my $result='<div class="LC_Box">'
                   2160:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2161:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2162:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2163: #    if ($env{'form.handgrade'} eq 'no') {
                   2164:     if (1) {
1.588     bisitz   2165:         $result.='<p class="LC_info">'
                   2166:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2167:                 ."</p>\n";
1.469     albertel 2168:     }
                   2169: 
1.118     ng       2170:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2171:     my $fullname;
                   2172:     my $col_fullnames = [];
1.624     www      2173: #    if ($env{'form.handgrade'} eq 'yes') {
                   2174:     if (1) {
1.464     albertel 2175: 	(my $sub_result,$fullname,$col_fullnames)=
                   2176: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2177: 				 $counter);
                   2178: 	$result.=$sub_result;
1.41      ng       2179:     }
1.44      ng       2180:     $request->print($result."\n");
1.702     kruse    2181:     
1.44      ng       2182:     # print student answer/submission
1.588     bisitz   2183:     # Options are (1) Handgraded submission only
1.44      ng       2184:     #             (2) Last submission, includes submission that is not handgraded 
                   2185:     #                  (for multi-response type part)
                   2186:     #             (3) Last submission plus the parts info
                   2187:     #             (4) The whole record for this student
1.702     kruse    2188:     
                   2189:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2190: 	
1.702     kruse    2191:     my $lastsubonly;
1.468     albertel 2192: 
1.702     kruse    2193:     if ($$timestamp eq '') {
                   2194:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2195:     } else {
                   2196:         $lastsubonly =
                   2197:             '<div class="LC_grade_submissions_body">'
                   2198:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2199: 
                   2200: 	my %seenparts;
                   2201: 	my @part_response_id = &flatten_responseType($responseType);
                   2202: 	foreach my $part (@part_response_id) {
                   2203: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2204: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2205: 
1.702     kruse    2206: 	    my ($partid,$respid) = @{ $part };
                   2207: 	    my $display_part=&get_display_part($partid,$symb);
                   2208: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2209: 		if (exists($seenparts{$partid})) { next; }
                   2210: 		$seenparts{$partid}=1;
                   2211:                 $request->print(
                   2212:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2213:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2214:                                '<a href="javascript:viewSubmitter(\''.
                   2215:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2216:                                '\');" target="_self">'.
                   2217:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2218:                     '<br />');
                   2219: 		next;
                   2220: 		}
                   2221: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2222: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2223:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2224:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2225:                     ' <span class="LC_internal_info">'.
                   2226:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2227:                     '</span>&nbsp; &nbsp;'.
                   2228: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2229: 		next;
                   2230: 	    }
                   2231: 	    foreach my $submission (@$string) {
                   2232: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2233: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2234: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2235: 		# Similarity check
                   2236:                 my $similar='';
                   2237:                 my ($type,$trial,$rndseed);
                   2238:                 if ($hide eq 'rand') {
                   2239:                     $type = 'randomizetry';
                   2240:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2241:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2242:                 }
                   2243: 	        if ($env{'form.checkPlag'}) {
                   2244:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2245: 		        &most_similar($uname,$udom,$symb,$subval);
                   2246: 		    if ($osim) {
                   2247: 			$osim=int($osim*100.0);
                   2248: 			my %old_course_desc = 
                   2249: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2250: 							{'one_time' => 1});
                   2251: 
                   2252:                         if ($hide eq 'anon') {
                   2253:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2254:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2255:                         } else {
                   2256: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2257: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2258: 				    $osim,
                   2259: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2260: 				        $old_course_desc{'description'},
                   2261: 				        $old_course_desc{'num'},
                   2262: 				        $old_course_desc{'domain'}).
                   2263: 				    '</span></h3><blockquote><i>'.
                   2264: 				    &keywords_highlight($oessay).
                   2265: 				    '</i></blockquote><hr />';
1.702     kruse    2266:                         }
                   2267: 	            }
                   2268: 		}
                   2269: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2270:                                      undef,$type,$trial,$rndseed);
                   2271:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2272: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2273: 		    my $display_part=&get_display_part($partid,$symb);
                   2274:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2275:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2276:                         ' <span class="LC_internal_info">'.
                   2277:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2278:                         '</span>&nbsp; &nbsp;';
                   2279: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2280:                         
                   2281: 		    if (@$files) {
                   2282:                         if ($hide eq 'anon') {
                   2283:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2284:                         } else {
                   2285:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2286:                                         .'<br /><span class="LC_warning">';
                   2287:                             if(@$files == 1) {
                   2288:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2289:                             } else {
1.702     kruse    2290:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2291:                             }
                   2292:                             $lastsubonly .= '</span>';                         
                   2293:                             foreach my $file (@$files) {
                   2294:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2295:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2296:                             }
                   2297:                         }
1.702     kruse    2298: 			$lastsubonly.='<br />';
                   2299:                     }
                   2300:                     if ($hide eq 'anon') {
                   2301:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2302:                     } else {
1.724     raeburn  2303:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2304:                         if ($draft) {
                   2305:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2306:                         }
                   2307:                         $subval =
1.702     kruse    2308: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2309: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2310:                         if ($responsetype eq 'essay') {
                   2311:                             $subval =~ s{\n}{<br />}g;
                   2312:                         }
                   2313:                         $lastsubonly.=$subval."\n";
1.702     kruse    2314:                     }
                   2315: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2316: 		    $lastsubonly.='</div>';
1.41      ng       2317: 		}
1.702     kruse    2318:             }
1.151     albertel 2319: 	}
1.702     kruse    2320: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2321:     }
                   2322:     $request->print($lastsubonly);
                   2323:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2324:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2325: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2326:   
1.702     kruse    2327:     } 
                   2328:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2329:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2330:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2331: 								 $env{'request.course.id'},
1.44      ng       2332: 								 $last,'.submission',
1.726     raeburn  2333: 								 'Apache::grades::keywords_highlight',
                   2334:                                                                  $usec,$identifier));
1.41      ng       2335:     }
1.121     ng       2336:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2337: 	.$udom.'" />'."\n");
1.44      ng       2338:     # return if view submission with no grading option
1.618     www      2339:     if (!&canmodify($usec)) {
1.633     www      2340: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2341: 	return;
1.180     albertel 2342:     } else {
1.468     albertel 2343: 	$request->print('</div>'."\n");
1.41      ng       2344:     }
1.33      ng       2345: 
1.121     ng       2346:     # essay grading message center
1.624     www      2347: #    if ($env{'form.handgrade'} eq 'yes') {
                   2348:     if (1) {
1.468     albertel 2349: 	my $result='<div class="LC_grade_message_center">';
                   2350:     
                   2351: 	$result.='<div class="LC_grade_message_center_header">'.
                   2352: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2353: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2354: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2355: 	if (scalar(@$col_fullnames) > 0) {
                   2356: 	    my $lastone = pop(@$col_fullnames);
                   2357: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2358: 	}
                   2359: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2360: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2361: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2362: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2363: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2364: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2365: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2366: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2367: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2368: 	    '<br />&nbsp;('.
1.468     albertel 2369: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2370: 	$result.='</div></div>';
1.121     ng       2371: 	$request->print($result);
1.118     ng       2372:     }
1.41      ng       2373: 
                   2374:     my %seen = ();
                   2375:     my @partlist;
1.129     ng       2376:     my @gradePartRespid;
1.375     albertel 2377:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2378:     $request->print(
1.588     bisitz   2379:         '<div class="LC_Box">'
                   2380:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2381:     );
1.592     bisitz   2382:     $request->print(&gradeBox_start());
1.375     albertel 2383:     foreach my $part_response_id (@part_response_id) {
                   2384:     	my ($partid,$respid) = @{ $part_response_id };
                   2385: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2386: 	next if ($seen{$partid} > 0);
1.41      ng       2387: 	$seen{$partid}++;
1.393     albertel 2388: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2389: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2390: 	push(@partlist,$partid);
                   2391: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2392: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2393:     }
1.585     bisitz   2394:     $request->print(&gradeBox_end()); # </div>
                   2395:     $request->print('</div>');
1.468     albertel 2396: 
                   2397:     $request->print('<div class="LC_grade_info_links">');
                   2398:     $request->print('</div>');
                   2399: 
1.45      ng       2400:     $result='<input type="hidden" name="partlist'.$counter.
                   2401: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2402:     $result.='<input type="hidden" name="gradePartRespid'.
                   2403: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2404:     my $ctr = 0;
                   2405:     while ($ctr < scalar(@partlist)) {
                   2406: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2407: 	    $partlist[$ctr].'" />'."\n";
                   2408: 	$ctr++;
                   2409:     }
1.468     albertel 2410:     $request->print($result.''."\n");
1.41      ng       2411: 
1.441     www      2412: # Done with printing info for one student
                   2413: 
1.468     albertel 2414:     $request->print('</div>');#LC_grade_show_user
1.441     www      2415: 
                   2416: 
1.41      ng       2417:     # print end of form
                   2418:     if ($counter == $total) {
1.592     bisitz   2419:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2420: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2421: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2422: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2423: 	my $ntstu ='<select name="NTSTU">'.
                   2424: 	    '<option>1</option><option>2</option>'.
                   2425: 	    '<option>3</option><option>5</option>'.
                   2426: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2427: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2428: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2429:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2430: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2431: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2432: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2433: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2434:         $endform.='<span class="LC_warning">'.
                   2435:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2436:                   '</span>'."\n" ;
1.349     albertel 2437:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2438:             "' name='increment' />";
1.485     albertel 2439: 	$endform.='</td></tr></table></form>';
1.41      ng       2440: 	$request->print($endform);
                   2441:     }
                   2442:     return '';
1.38      ng       2443: }
                   2444: 
1.464     albertel 2445: sub check_collaborators {
                   2446:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2447:     my ($result,@col_fullnames);
                   2448:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2449:     foreach my $part (keys(%$handgrade)) {
                   2450: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2451: 					'.maxcollaborators',
                   2452: 					$symb,$udom,$uname);
                   2453: 	next if ($ncol <= 0);
                   2454: 	$part =~ s/\_/\./g;
                   2455: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2456: 	my (@good_collaborators, @bad_collaborators);
                   2457: 	foreach my $possible_collaborator
1.630     www      2458: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2459: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2460: 	    next if ($possible_collaborator eq '');
1.631     www      2461: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2462: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2463: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2464: 	    # Doing this grep allows 'fuzzy' specification
                   2465: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2466: 			       keys(%$classlist));
                   2467: 	    if (! scalar(@matches)) {
                   2468: 		push(@bad_collaborators, $possible_collaborator);
                   2469: 	    } else {
                   2470: 		push(@good_collaborators, @matches);
                   2471: 	    }
                   2472: 	}
                   2473: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2474: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2475: 	    foreach my $name (@good_collaborators) {
                   2476: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2477: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2478: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2479: 	    }
1.630     www      2480: 	    $result.='</ol><br />'."\n";
1.466     albertel 2481: 	    my ($part)=split(/\./,$part);
1.464     albertel 2482: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2483: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2484: 		"\n";
                   2485: 	}
                   2486: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2487: 	    $result.='<div class="LC_warning">';
1.464     albertel 2488: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2489: 	    $result .= '</div>';
                   2490: 	}         
                   2491: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2492: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2493: 	    $result .= &mt('This student has submitted too many '.
                   2494: 		'collaborators.  Maximum is [_1].',$ncol);
                   2495: 	    $result .= '</div>';
                   2496: 	}
                   2497:     }
                   2498:     return ($result,$fullname,\@col_fullnames);
                   2499: }
                   2500: 
1.44      ng       2501: #--- Retrieve the last submission for all the parts
1.38      ng       2502: sub get_last_submission {
1.119     ng       2503:     my ($returnhash)=@_;
1.596     raeburn  2504:     my (@string,$timestamp,%lasthidden);
1.119     ng       2505:     if ($$returnhash{'version'}) {
1.46      ng       2506: 	my %lasthash=();
                   2507: 	my ($version);
1.119     ng       2508: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2509: 	    foreach my $key (sort(split(/\:/,
                   2510: 					$$returnhash{$version.':keys'}))) {
                   2511: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2512: 		$timestamp = 
1.545     raeburn  2513: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2514: 	    }
                   2515: 	}
1.640     raeburn  2516:         my (%typeparts,%randombytry);
1.596     raeburn  2517:         my $showsurv = 
                   2518:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2519:         foreach my $key (sort(keys(%lasthash))) {
                   2520:             if ($key =~ /\.type$/) {
                   2521:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2522:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2523:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2524:                     my ($ign,@parts) = split(/\./,$key);
                   2525:                     pop(@parts);
1.641     raeburn  2526:                     my $id = join('.',@parts);
1.640     raeburn  2527:                     if ($lasthash{$key} eq 'randomizetry') {
                   2528:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2529:                     } else {
                   2530:                         unless ($showsurv) {
                   2531:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2532:                         }
1.596     raeburn  2533:                     }
                   2534:                     delete($lasthash{$key});
                   2535:                 }
                   2536:             }
                   2537:         }
                   2538:         my @hidden = keys(%typeparts);
1.640     raeburn  2539:         my @randomize = keys(%randombytry);
1.397     albertel 2540: 	foreach my $key (keys(%lasthash)) {
                   2541: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2542:             my $hide;
                   2543:             if (@hidden) {
                   2544:                 foreach my $id (@hidden) {
                   2545:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2546:                         $hide = 'anon';
1.596     raeburn  2547:                         last;
                   2548:                     }
                   2549:                 }
                   2550:             }
1.640     raeburn  2551:             unless ($hide) {
                   2552:                 if (@randomize) {
1.732     raeburn  2553:                     foreach my $id (@randomize) {
1.640     raeburn  2554:                         if ($key =~ /^\Q$id\E/) {
                   2555:                             $hide = 'rand';
                   2556:                             last;
                   2557:                         }
                   2558:                     }
                   2559:                 }
                   2560:             }
1.397     albertel 2561: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2562: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2563:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2564:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2565:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2566: 	}
                   2567:     }
1.397     albertel 2568:     if (!@string) {
                   2569: 	$string[0] =
1.539     riegler  2570: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2571:     }
                   2572:     return (\@string,\$timestamp);
1.38      ng       2573: }
1.35      ng       2574: 
1.44      ng       2575: #--- High light keywords, with style choosen by user.
1.38      ng       2576: sub keywords_highlight {
1.44      ng       2577:     my $string    = shift;
1.257     albertel 2578:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2579:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2580:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2581:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2582:     foreach my $keyword (@keylist) {
                   2583: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2584:     }
                   2585:     return $string;
1.38      ng       2586: }
1.36      ng       2587: 
1.671     raeburn  2588: # For Tasks provide a mechanism to display previous version for one specific student
                   2589: 
                   2590: sub show_previous_task_version {
                   2591:     my ($request,$symb) = @_;
                   2592:     if ($symb eq '') {
1.717     bisitz   2593:         $request->print(
                   2594:             '<span class="LC_error">'.
                   2595:             &mt('Unable to handle ambiguous references.').
                   2596:             '</span>');
1.671     raeburn  2597:         return '';
                   2598:     }
                   2599:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2600:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2601:     if (!&canview($usec)) {
1.712     bisitz   2602:         $request->print(
                   2603:             '<span class="LC_warning">'.
1.713     bisitz   2604:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2605:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2606:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2607:             '</span>');
1.671     raeburn  2608:         return;
                   2609:     }
                   2610:     my $mode = 'both';
                   2611:     my $isTask = ($symb =~/\.task$/);
                   2612:     if ($isTask) {
                   2613:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2614:             if ($env{'form.fullname'} eq '') {
                   2615:                 $env{'form.fullname'} =
                   2616:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2617:             }
                   2618:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2619:             $request->print("\n\n".
                   2620:                             '<div class="LC_grade_show_user">'.
                   2621:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2622:                             '</h2>'."\n");
                   2623:             &Apache::lonxml::clear_problem_counter();
                   2624:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2625:                             {'previousversion' => $env{'form.previousversion'} }));
                   2626:             $request->print("\n</div>");
                   2627:         }
                   2628:     }
                   2629:     return;
                   2630: }
                   2631: 
                   2632: sub choose_task_version_form {
                   2633:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2634:     my $isTask = ($symb =~/\.task$/);
                   2635:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2636:     if ($isTask) {
                   2637:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2638:                                               $udom,$uname);
                   2639:         if (($record{'resource.0.version'} eq '') ||
                   2640:             ($record{'resource.0.version'} < 2)) {
                   2641:             return ($record{'resource.0.version'},
                   2642:                     $record{'resource.0.version'},$result,$js);
                   2643:         } else {
                   2644:             $current = $record{'resource.0.version'};
                   2645:         }
                   2646:         if ($env{'form.previousversion'}) {
                   2647:             $displayed = $env{'form.previousversion'};
                   2648:             $rowtitle = &mt('Choose another version:')
                   2649:         } else {
                   2650:             $displayed = $current;
                   2651:             $rowtitle = &mt('Show earlier version:');
                   2652:         }
                   2653:         $result = '<div class="LC_left_float">';
                   2654:         my $list;
                   2655:         my $numversions = 0;
                   2656:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2657:             if ($i == $current) {
                   2658:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2659:                     next;
                   2660:                 } else {
                   2661:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2662:                     $numversions ++;
                   2663:                 }
                   2664:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2665:                 unless ($i == $env{'form.previousversion'}) {
                   2666:                     $numversions ++;
                   2667:                 }
                   2668:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2669:             }
                   2670:         }
                   2671:         if ($numversions) {
                   2672:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2673:             $result .=
                   2674:                 '<form name="getprev" method="post" action=""'.
                   2675:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2676:                 &Apache::loncommon::start_data_table().
                   2677:                 &Apache::loncommon::start_data_table_row().
                   2678:                 '<th align="left">'.$rowtitle.'</th>'.
                   2679:                 '<td><select name="version">'.
                   2680:                 '<option>'.&mt('Select').'</option>'.
                   2681:                 $list.
                   2682:                 '</select></td>'.
                   2683:                 &Apache::loncommon::end_data_table_row();
                   2684:             unless ($nomenu) {
                   2685:                 $result .= &Apache::loncommon::start_data_table_row().
                   2686:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2687:                 '<td><span class="LC_nobreak">'.
                   2688:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2689:                 &mt('Yes').'</label>'.
                   2690:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2691:                 '</span></td>'.
                   2692:                 &Apache::loncommon::end_data_table_row();
                   2693:             }
                   2694:             $result .=
                   2695:                 &Apache::loncommon::start_data_table_row().
                   2696:                 '<th align="left">&nbsp;</th>'.
                   2697:                 '<td>'.
                   2698:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2699:                 '</td>'.
                   2700:                 &Apache::loncommon::end_data_table_row().
                   2701:                 &Apache::loncommon::end_data_table().
                   2702:                 '</form>';
                   2703:             $js = &previous_display_javascript($nomenu,$current);
                   2704:         } elsif ($displayed && $nomenu) {
                   2705:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2706:         } else {
                   2707:             $result .= &mt('No previous versions to show for this student');
                   2708:         }
                   2709:         $result .= '</div>';
                   2710:     }
                   2711:     return ($current,$displayed,$result,$js);
                   2712: }
                   2713: 
                   2714: sub previous_display_javascript {
                   2715:     my ($nomenu,$current) = @_;
                   2716:     my $js = <<"JSONE";
                   2717: <script type="text/javascript">
                   2718: // <![CDATA[
                   2719: function previousVersion(uname,udom,symb) {
                   2720:     var current = '$current';
                   2721:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2722:     var prevstr = new RegExp("^\\\\d+\$");
                   2723:     if (!prevstr.test(version)) {
                   2724:         return false;
                   2725:     }
                   2726:     var url = '';
                   2727:     if (version == current) {
                   2728:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2729:     } else {
                   2730:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2731:     }
                   2732: JSONE
                   2733:     if ($nomenu) {
                   2734:         $js .= <<"JSTWO";
                   2735:     document.location.href = url;
                   2736: JSTWO
                   2737:     } else {
                   2738:         $js .= <<"JSTHREE";
                   2739:     var newwin = 0;
                   2740:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2741:         if (document.getprev.prevwin[i].checked == true) {
                   2742:             newwin = document.getprev.prevwin[i].value;
                   2743:         }
                   2744:     }
                   2745:     if (newwin == 1) {
                   2746:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2747:         url = url+'&inhibitmenu=yes';
                   2748:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2749:             previousWin = window.open(url,'',options,1);
                   2750:         } else {
                   2751:             previousWin.location.href = url;
                   2752:         }
                   2753:         previousWin.focus();
                   2754:         return false;
                   2755:     } else {
                   2756:         document.location.href = url;
                   2757:         return false;
                   2758:     }
                   2759: JSTHREE
                   2760:     }
                   2761:     $js .= <<"ENDJS";
                   2762:     return false;
                   2763: }
                   2764: // ]]>
                   2765: </script>
                   2766: ENDJS
                   2767: 
                   2768: }
                   2769: 
1.44      ng       2770: #--- Called from submission routine
1.38      ng       2771: sub processHandGrade {
1.608     www      2772:     my ($request,$symb) = @_;
1.324     albertel 2773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2774:     my $button = $env{'form.gradeOpt'};
                   2775:     my $ngrade = $env{'form.NCT'};
                   2776:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2777:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2778:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2779: 
1.44      ng       2780:     if ($button eq 'Save & Next') {
                   2781: 	my $ctr = 0;
                   2782: 	while ($ctr < $ngrade) {
1.257     albertel 2783: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2784: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2785:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2786: 	    if ($errorflag eq 'no_score') {
                   2787: 		$ctr++;
                   2788: 		next;
                   2789: 	    }
1.104     albertel 2790: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2791: 		$request->print(
                   2792:                     '<span class="LC_error">'
                   2793:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2794:                    .'</span>');
1.104     albertel 2795: 		$ctr++;
                   2796: 		next;
                   2797: 	    }
1.726     raeburn  2798:             if ($numhidden) {
                   2799:                 $request->print(
                   2800:                     '<span class="LC_info">'
                   2801:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2802:                    .'</span><br />');
                   2803:             }
1.257     albertel 2804: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2805: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2806: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2807:             my ($feedurl,$showsymb) =
                   2808: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2809: 	    my $messagetail;
1.62      albertel 2810: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2811: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2812: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2813: 		$subject.=' ['.$restitle.']';
1.44      ng       2814: 		my (@msgnum) = split(/,/,$includemsg);
                   2815: 		foreach (@msgnum) {
1.257     albertel 2816: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2817: 		}
1.80      ng       2818: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2819: 		if ($env{'form.withgrades'.$ctr}) {
                   2820: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2821: 		    $messagetail = " for <a href=\"".
1.605     www      2822: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2823: 		}
                   2824: 		$msgstatus = 
                   2825:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2826: 						     $message.$messagetail,
1.418     albertel 2827:                                                      undef,$feedurl,undef,
1.386     raeburn  2828:                                                      undef,undef,$showsymb,
                   2829:                                                      $restitle);
1.574     bisitz   2830: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2831: 				$msgstatus.'<br />');
1.44      ng       2832: 	    }
1.257     albertel 2833: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2834: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2835: 		foreach my $collabstr (@collabstrs) {
                   2836: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2837: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2838: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2839: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2840: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2841: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2842: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2843: 			    next;
1.418     albertel 2844: 			} elsif ($message ne '') {
                   2845: 			    my ($baseurl,$showsymb) = 
                   2846: 				&get_feedurl_and_symb($symb,$collaborator,
                   2847: 						      $udom);
                   2848: 			    if ($env{'form.withgrades'.$ctr}) {
                   2849: 				$messagetail = " for <a href=\"".
1.605     www      2850:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2851: 			    }
1.418     albertel 2852: 			    $msgstatus = 
                   2853: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2854: 			}
1.44      ng       2855: 		    }
                   2856: 		}
                   2857: 	    }
                   2858: 	    $ctr++;
                   2859: 	}
                   2860:     }
                   2861: 
1.624     www      2862: #    if ($env{'form.handgrade'} eq 'yes') {
                   2863:     if (1) {
1.119     ng       2864: 	# Keywords sorted in alphabatical order
1.257     albertel 2865: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2866: 	my %keyhash = ();
1.257     albertel 2867: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2868: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2869: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2870: 	$env{'form.keywords'} = join(' ',@keywords);
                   2871: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2872: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2873: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2874: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2875: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2876: 
                   2877: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2878: 	# New messages are saved in env for the next student.
1.119     ng       2879: 	# All messages are saved in nohist_handgrade.db
                   2880: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2881: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2882: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2883: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2884: 		$idx++;
                   2885: 	    }
                   2886: 	    $ctr++;
1.41      ng       2887: 	}
1.119     ng       2888: 	$ctr = 0;
                   2889: 	while ($ctr < $ngrade) {
1.257     albertel 2890: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2891: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2892: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2893: 		$idx++;
                   2894: 	    }
                   2895: 	    $ctr++;
1.41      ng       2896: 	}
1.257     albertel 2897: 	$env{'form.savemsgN'} = --$idx;
                   2898: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2899: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2900: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2901:     }
1.44      ng       2902:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2903:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2904:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2905: 	my ($ctr,$total) = (0,0);
                   2906: 	while ($ctr < $ngrade) {
1.257     albertel 2907: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2908: 	    $ctr++;
                   2909: 	}
1.257     albertel 2910: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2911: 	$ctr = 0;
                   2912: 	while ($ctr < $total) {
1.257     albertel 2913: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2914: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2915: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2916: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2917: 	    $ctr++;
                   2918: 	}
                   2919: 	return '';
                   2920:     }
1.36      ng       2921: 
1.44      ng       2922:     # Get the next/previous one or group of students
1.257     albertel 2923:     my $firststu = $env{'form.unamedom0'};
                   2924:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2925:     my $ctr = 2;
1.41      ng       2926:     while ($laststu eq '') {
1.257     albertel 2927: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2928: 	$ctr++;
                   2929: 	$laststu = $firststu if ($ctr > $ngrade);
                   2930:     }
1.44      ng       2931: 
1.41      ng       2932:     my (@parsedlist,@nextlist);
                   2933:     my ($nextflg) = 0;
1.524     raeburn  2934:     foreach my $item (sort 
1.294     albertel 2935: 	     {
                   2936: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2937: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2938: 		 }
                   2939: 		 return $a cmp $b;
                   2940: 	     } (keys(%$fullname))) {
1.605     www      2941: # FIXME: this is fishy, looks like the button label
1.41      ng       2942: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2943: 	    push(@parsedlist,$item);
1.41      ng       2944: 	}
1.524     raeburn  2945: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2946: 	if ($button eq 'Previous') {
1.524     raeburn  2947: 	    last if ($item eq $firststu);
                   2948: 	    push(@parsedlist,$item);
1.41      ng       2949: 	}
                   2950:     }
                   2951:     $ctr = 0;
1.605     www      2952: # FIXME: this is fishy, looks like the button label
1.41      ng       2953:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2954:     my $res_error;
                   2955:     my ($partlist) = &response_type($symb,\$res_error);
                   2956:     if ($res_error) {
                   2957:         $request->print(&navmap_errormsg());
                   2958:         return;
                   2959:     }
1.41      ng       2960:     foreach my $student (@parsedlist) {
1.257     albertel 2961: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2962: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2963: 	
                   2964: 	if ($submitonly eq 'queued') {
                   2965: 	    my %queue_status = 
                   2966: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2967: 							$udom,$uname);
                   2968: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2969: 	}
                   2970: 
1.156     albertel 2971: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2972: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2973: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2974: 	    my $submitted = 0;
1.248     albertel 2975: 	    my $ungraded = 0;
                   2976: 	    my $incorrect = 0;
1.524     raeburn  2977: 	    foreach my $item (keys(%status)) {
                   2978: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2979: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2980: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2981: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2982: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2983: 		    $submitted = 0;
                   2984: 		}
1.41      ng       2985: 	    }
1.156     albertel 2986: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2987: 				     $submitonly eq 'incorrect' ||
                   2988: 				     $submitonly eq 'graded'));
1.248     albertel 2989: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2990: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2991: 	}
1.524     raeburn  2992: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2993: 	last if ($ctr == $ntstu);
1.41      ng       2994: 	$ctr++;
                   2995:     }
1.36      ng       2996: 
1.41      ng       2997:     $ctr = 0;
                   2998:     my $total = scalar(@nextlist)-1;
1.39      ng       2999: 
1.524     raeburn  3000:     foreach (sort(@nextlist)) {
1.41      ng       3001: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3002: 	$env{'form.student'}  = $uname;
                   3003: 	$env{'form.userdom'}  = $udom;
                   3004: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3005: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3006: 	$ctr++;
                   3007:     }
                   3008:     if ($total < 0) {
1.653     raeburn  3009: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3010: 	$request->print($the_end);
                   3011:     }
                   3012:     return '';
1.38      ng       3013: }
1.36      ng       3014: 
1.44      ng       3015: #---- Save the score and award for each student, if changed
1.38      ng       3016: sub saveHandGrade {
1.324     albertel 3017:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3018:     my @version_parts;
1.104     albertel 3019:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3020: 					   $env{'request.course.id'});
1.104     albertel 3021:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3022:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3023:     my @parts_graded;
1.77      ng       3024:     my %newrecord  = ();
1.726     raeburn  3025:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3026:     my %aggregate = ();
                   3027:     my $aggregateflag = 0;
1.726     raeburn  3028:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3029:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3030:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3031:         $totchg += $numchgs;
                   3032:     }
1.301     albertel 3033:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3034:     foreach my $new_part (@parts) {
1.337     banghart 3035: 	#collaborator ($submi may vary for different parts
1.259     banghart 3036: 	if ($submitter && $new_part ne $part) { next; }
                   3037: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3038: 	if ($dropMenu eq 'excused') {
1.259     banghart 3039: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3040: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3041: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3042: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3043: 		}
1.364     banghart 3044: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3045: 	    }
1.125     ng       3046: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3047: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3048: 	    foreach my $key (keys(%record)) {
1.259     banghart 3049: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3050: 	    }
1.259     banghart 3051: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3052: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3053:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3054: 
                   3055:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3056: 					       [$new_part]);
                   3057:             my $aggtries =$totaltries;
1.269     raeburn  3058:             if ($last_resets{$new_part}) {
1.270     albertel 3059:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3060: 					   $new_part);
1.269     raeburn  3061:             }
1.270     albertel 3062: 
                   3063:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3064:             if ($aggtries > 0) {
1.327     albertel 3065:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3066:                 $aggregateflag = 1;
                   3067:             }
1.125     ng       3068: 	} elsif ($dropMenu eq '') {
1.259     banghart 3069: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3070: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3071: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3072: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3073: 		next;
                   3074: 	    }
1.259     banghart 3075: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3076: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3077: 	    my $partial= $pts/$wgt;
1.259     banghart 3078: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3079: 		#do not update score for part if not changed.
1.346     banghart 3080:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3081: 		next;
1.251     banghart 3082: 	    } else {
1.524     raeburn  3083: 	        push(@parts_graded,$new_part);
1.153     albertel 3084: 	    }
1.259     banghart 3085: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3086: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3087: 	    }
1.259     banghart 3088: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3089: 	    if ($partial == 0) {
1.153     albertel 3090: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3091: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3092: 		}
1.41      ng       3093: 	    } else {
1.153     albertel 3094: 		if ($record{$reckey} ne 'correct_by_override') {
                   3095: 		    $newrecord{$reckey} = 'correct_by_override';
                   3096: 		}
                   3097: 	    }	    
                   3098: 	    if ($submitter && 
1.259     banghart 3099: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3100: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3101: 	    }
1.259     banghart 3102: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3103: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3104: 	}
1.259     banghart 3105: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3106: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3107: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3108: 	        $dropMenu eq 'reset status')
                   3109: 	   {
1.524     raeburn  3110: 	    push(@version_parts,$new_part);
1.259     banghart 3111: 	}
1.41      ng       3112:     }
1.301     albertel 3113:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3114:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3115: 
1.344     albertel 3116:     if (%newrecord) {
                   3117:         if (@version_parts) {
1.364     banghart 3118:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3119:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3120: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3121: 	    foreach my $new_part (@version_parts) {
                   3122: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3123: 				$new_part,\%newrecord);
                   3124: 	    }
1.259     banghart 3125:         }
1.44      ng       3126: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3127: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3128: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3129: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3130:     }
1.269     raeburn  3131:     if ($aggregateflag) {
                   3132:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3133: 			      $cdom,$cnum);
1.269     raeburn  3134:     }
1.726     raeburn  3135:     return ('',$pts,$wgt,$totchg);
                   3136: }
                   3137: 
                   3138: sub makehidden {
1.728     raeburn  3139:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3140:     return unless (ref($record) eq 'HASH');
                   3141:     my %modified;
                   3142:     my $numchanged = 0;
                   3143:     if (exists($record->{$version.':keys'})) {
                   3144:         my $partsregexp = $parts;
                   3145:         $partsregexp =~ s/,/|/g;
                   3146:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3147:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3148:                  my $item = $1;
                   3149:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3150:                      $modified{$key} = $record->{$version.':'.$key};
                   3151:                  }
                   3152:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3153:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3154:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3155:                 $modified{$key} = $record->{$version.':'.$key};
                   3156:             }
                   3157:         }
                   3158:         if (keys(%modified)) {
                   3159:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3160:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3161:                 $numchanged ++;
                   3162:             }
                   3163:         }
                   3164:     }
                   3165:     return $numchanged;
1.36      ng       3166: }
1.322     albertel 3167: 
1.380     albertel 3168: sub check_and_remove_from_queue {
                   3169:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3170:     my @ungraded_parts;
                   3171:     foreach my $part (@{$parts}) {
                   3172: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3173: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3174: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3175: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3176: 		) {
                   3177: 	    push(@ungraded_parts, $part);
                   3178: 	}
                   3179:     }
                   3180:     if ( !@ungraded_parts ) {
                   3181: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3182: 					       $cnum,$domain,$stuname);
                   3183:     }
                   3184: }
                   3185: 
1.337     banghart 3186: sub handback_files {
                   3187:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3188:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3189:     my $res_error;
                   3190:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3191:     if ($res_error) {
                   3192:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3193:         return;
                   3194:     }
1.654     raeburn  3195:     my @handedback;
                   3196:     my $file_msg;
1.375     albertel 3197:     my @part_response_id = &flatten_responseType($responseType);
                   3198:     foreach my $part_response_id (@part_response_id) {
                   3199:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3200: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3201:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3202:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3203:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3204:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3205:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3206:                     my ($directory,$answer_file) = 
1.654     raeburn  3207:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3208:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3209: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3210: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3211:                     my $getpropath = 1;
1.662     raeburn  3212:                     my ($dir_list,$listerror) = 
                   3213:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3214:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3215: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3216:                     # fix filename
1.355     banghart 3217:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3218:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3219:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3220:             	                                $save_file_name);
1.337     banghart 3221:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3222:                         $request->print('<br /><span class="LC_error">'.
                   3223:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3224:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3225:                                         '</span>');
1.356     banghart 3226:                     } else {
1.360     banghart 3227:                         # mark the file as read only
1.654     raeburn  3228:                         push(@handedback,$save_file_name);
1.367     albertel 3229: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3230: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3231: 			}
                   3232:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3233: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3234:                     }
1.686     bisitz   3235:                     $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 3236:                 }
                   3237:             }
                   3238:         }
1.654     raeburn  3239:     }
                   3240:     if (@handedback > 0) {
                   3241:         $request->print('<br />');
                   3242:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3243:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3244:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3245:         my ($subject,$message);
                   3246:         if (scalar(@handedback) == 1) {
                   3247:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3248:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3249:         } else {
                   3250:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3251:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3252:         }
                   3253:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3254:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3255:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3256:         my ($feedurl,$showsymb) =
                   3257:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3258:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3259:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3260:         my $msgstatus =
                   3261:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3262:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3263:                  $restitle);
                   3264:         if ($msgstatus) {
                   3265:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3266:         }
                   3267:     }
1.338     banghart 3268:     return;
1.337     banghart 3269: }
                   3270: 
1.418     albertel 3271: sub get_feedurl_and_symb {
                   3272:     my ($symb,$uname,$udom) = @_;
                   3273:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3274:     $url = &Apache::lonnet::clutter($url);
                   3275:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3276: 					$symb,$udom,$uname);
                   3277:     if ($encrypturl =~ /^yes$/i) {
                   3278: 	&Apache::lonenc::encrypted(\$url,1);
                   3279: 	&Apache::lonenc::encrypted(\$symb,1);
                   3280:     }
                   3281:     return ($url,$symb);
                   3282: }
                   3283: 
1.313     banghart 3284: sub get_submitted_files {
                   3285:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3286:     my @files;
                   3287:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3288:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3289:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3290:     	    push(@files,$file_url.$file);
                   3291:         }
                   3292:     }
                   3293:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3294:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3295:     }
                   3296:     return (\@files);
                   3297: }
1.322     albertel 3298: 
1.269     raeburn  3299: # ----------- Provides number of tries since last reset.
                   3300: sub get_num_tries {
                   3301:     my ($record,$last_reset,$part) = @_;
                   3302:     my $timestamp = '';
                   3303:     my $num_tries = 0;
                   3304:     if ($$record{'version'}) {
                   3305:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3306:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3307:                 $timestamp = $$record{$version.':timestamp'};
                   3308:                 if ($timestamp > $last_reset) {
                   3309:                     $num_tries ++;
                   3310:                 } else {
                   3311:                     last;
                   3312:                 }
                   3313:             }
                   3314:         }
                   3315:     }
                   3316:     return $num_tries;
                   3317: }
                   3318: 
                   3319: # ----------- Determine decrements required in aggregate totals 
                   3320: sub decrement_aggs {
                   3321:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3322:     my %decrement = (
                   3323:                         attempts => 0,
                   3324:                         users => 0,
                   3325:                         correct => 0
                   3326:                     );
                   3327:     $decrement{'attempts'} = $aggtries;
                   3328:     if ($solvedstatus =~ /^correct/) {
                   3329:         $decrement{'correct'} = 1;
                   3330:     }
                   3331:     if ($aggtries == $totaltries) {
                   3332:         $decrement{'users'} = 1;
                   3333:     }
1.524     raeburn  3334:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3335:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3336:     }
                   3337:     return;
                   3338: }
                   3339: 
                   3340: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3341: sub get_last_resets {
1.270     albertel 3342:     my ($symb,$courseid,$partids) =@_;
                   3343:     my %last_resets;
1.269     raeburn  3344:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3345:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3346:     my @keys;
                   3347:     foreach my $part (@{$partids}) {
                   3348: 	push(@keys,"$symb\0$part\0resettime");
                   3349:     }
                   3350:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3351: 				     $cdom,$cname);
                   3352:     foreach my $part (@{$partids}) {
                   3353: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3354:     }
1.270     albertel 3355:     return %last_resets;
1.269     raeburn  3356: }
                   3357: 
1.251     banghart 3358: # ----------- Handles creating versions for portfolio files as answers
                   3359: sub version_portfiles {
1.343     banghart 3360:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3361:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3362:     my @returned_keys;
1.255     banghart 3363:     my $parts = join('|', @$parts_graded);
1.277     albertel 3364:     foreach my $key (keys(%$record)) {
1.259     banghart 3365:         my $new_portfiles;
1.263     banghart 3366:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3367:             my @versioned_portfiles;
1.367     albertel 3368:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3369:             if (@portfiles) {
                   3370:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3371:                                                       \@versioned_portfiles);
1.252     banghart 3372:             }
1.343     banghart 3373:             $$record{$key} = join(',',@versioned_portfiles);
                   3374:             push(@returned_keys,$key);
1.251     banghart 3375:         }
                   3376:     } 
1.343     banghart 3377:     return (@returned_keys);   
1.305     banghart 3378: }
                   3379: 
1.44      ng       3380: #--------------------------------------------------------------------------------------
                   3381: #
                   3382: #-------------------------- Next few routines handles grading by section or whole class
                   3383: #
                   3384: #--- Javascript to handle grading by section or whole class
1.42      ng       3385: sub viewgrades_js {
                   3386:     my ($request) = shift;
                   3387: 
1.539     riegler  3388:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3389:     &js_escape(\$alertmsg);
1.597     wenzelju 3390:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3391:    function writePoint(partid,weight,point) {
1.125     ng       3392: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3393: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3394: 	if (point == "textval") {
1.125     ng       3395: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3396: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3397: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3398: 		var resetbox = false;
                   3399: 		for (var i=0; i<radioButton.length; i++) {
                   3400: 		    if (radioButton[i].checked) {
                   3401: 			textbox.value = i;
                   3402: 			resetbox = true;
                   3403: 		    }
                   3404: 		}
                   3405: 		if (!resetbox) {
                   3406: 		    textbox.value = "";
                   3407: 		}
                   3408: 		return;
                   3409: 	    }
1.109     matthew  3410: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3411: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3412: 				   ") greater than the weight for the part. Accept?");
                   3413: 		if (resp == false) {
                   3414: 		    textbox.value = "";
                   3415: 		    return;
                   3416: 		}
                   3417: 	    }
1.42      ng       3418: 	    for (var i=0; i<radioButton.length; i++) {
                   3419: 		radioButton[i].checked=false;
1.109     matthew  3420: 		if (parseFloat(point) == i) {
1.42      ng       3421: 		    radioButton[i].checked=true;
                   3422: 		}
                   3423: 	    }
1.41      ng       3424: 
1.42      ng       3425: 	} else {
1.125     ng       3426: 	    textbox.value = parseFloat(point);
1.42      ng       3427: 	}
1.41      ng       3428: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3429: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3430: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3431: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3432: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3433: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3434: 	    if (saveval != "correct") {
                   3435: 		scorename.value = point;
1.43      ng       3436: 		if (selname[0].selected != true) {
                   3437: 		    selname[0].selected = true;
                   3438: 		}
1.42      ng       3439: 	    }
                   3440: 	}
1.125     ng       3441: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3442:     }
                   3443: 
                   3444:     function writeRadText(partid,weight) {
1.125     ng       3445: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3446: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3447:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3448: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3449: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3450: 	    for (var i=0; i<radioButton.length; i++) {
                   3451: 		radioButton[i].checked=false;
                   3452: 
                   3453: 	    }
                   3454: 	    textbox.value = "";
                   3455: 
                   3456: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3457: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3458: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3459: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3460: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3461: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3462: 		if ((saveval != "correct") || override) {
1.42      ng       3463: 		    scorename.value = "";
1.125     ng       3464: 		    if (selval[1].selected) {
                   3465: 			selname[1].selected = true;
                   3466: 		    } else {
                   3467: 			selname[2].selected = true;
                   3468: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3469: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3470: 		    }
1.42      ng       3471: 		}
                   3472: 	    }
1.43      ng       3473: 	} else {
                   3474: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3475: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3476: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3477: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3478: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3479: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3480: 		if ((saveval != "correct") || override) {
1.125     ng       3481: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3482: 		    selname[0].selected = true;
                   3483: 		}
                   3484: 	    }
                   3485: 	}	    
1.42      ng       3486:     }
                   3487: 
                   3488:     function changeSelect(partid,user) {
1.125     ng       3489: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3490: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3491: 	var point  = textbox.value;
1.125     ng       3492: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3493: 
1.109     matthew  3494: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3495: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3496: 	    textbox.value = "";
                   3497: 	    return;
                   3498: 	}
1.109     matthew  3499: 	if (parseFloat(point) > parseFloat(weight)) {
                   3500: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3501: 			       ") greater than the weight of the part. Accept?");
                   3502: 	    if (resp == false) {
                   3503: 		textbox.value = "";
                   3504: 		return;
                   3505: 	    }
                   3506: 	}
1.42      ng       3507: 	selval[0].selected = true;
                   3508:     }
                   3509: 
                   3510:     function changeOneScore(partid,user) {
1.125     ng       3511: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3512: 	if (selval[1].selected || selval[2].selected) {
                   3513: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3514: 	    if (selval[2].selected) {
                   3515: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3516: 	    }
1.269     raeburn  3517:         }
1.42      ng       3518:     }
                   3519: 
                   3520:     function resetEntry(numpart) {
                   3521: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3522: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3523: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3524: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3525: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3526: 	    for (var i=0; i<radioButton.length; i++) {
                   3527: 		radioButton[i].checked=false;
                   3528: 
                   3529: 	    }
                   3530: 	    textbox.value = "";
                   3531: 	    selval[0].selected = true;
                   3532: 
                   3533: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3534: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3535: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3536: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3537: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3538: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3539: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3540: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3541: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3542: 		if (saveselval == "excused") {
1.43      ng       3543: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3544: 		} else {
1.43      ng       3545: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3546: 		}
                   3547: 	    }
1.41      ng       3548: 	}
1.42      ng       3549:     }
                   3550: 
1.41      ng       3551: VIEWJAVASCRIPT
1.42      ng       3552: }
                   3553: 
1.44      ng       3554: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3555: sub viewgrades {
1.608     www      3556:     my ($request,$symb) = @_;
1.42      ng       3557:     &viewgrades_js($request);
1.41      ng       3558: 
1.168     albertel 3559:     #need to make sure we have the correct data for later EXT calls, 
                   3560:     #thus invalidate the cache
                   3561:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3562:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3563:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3564:     &Apache::lonnet::clear_EXT_cache_status();
                   3565: 
1.398     albertel 3566:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3567: 
                   3568:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3569:     $result.=&jscriptNform($symb);
1.41      ng       3570: 
1.44      ng       3571:     #beginning of class grading form
1.442     banghart 3572:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3573:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3574: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3575: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3576: 	&build_section_inputs().
1.442     banghart 3577: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3578: 
1.560     raeburn  3579:     my ($common_header,$specific_header);
1.257     albertel 3580:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3581: 	$common_header = &mt('Assign Common Grade to Class');
                   3582:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3583:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3584:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3585: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3586:     } else {
1.560     raeburn  3587:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3588:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3589: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3590:     }
1.560     raeburn  3591:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3592:     #radio buttons/text box for assigning points for a section or class.
                   3593:     #handles different parts of a problem
1.582     raeburn  3594:     my $res_error;
                   3595:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3596:     if ($res_error) {
                   3597:         return &navmap_errormsg();
                   3598:     }
1.42      ng       3599:     my %weight = ();
                   3600:     my $ctsparts = 0;
1.45      ng       3601:     my %seen = ();
1.375     albertel 3602:     my @part_response_id = &flatten_responseType($responseType);
                   3603:     foreach my $part_response_id (@part_response_id) {
                   3604:     	my ($partid,$respid) = @{ $part_response_id };
                   3605: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3606: 	next if $seen{$partid};
                   3607: 	$seen{$partid}++;
1.375     albertel 3608: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3609: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3610: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3611: 
1.324     albertel 3612: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3613: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3614: 	my $ctr = 0;
1.42      ng       3615: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3616: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3617: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3618: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3619: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3620: 	    $ctr++;
                   3621: 	}
1.485     albertel 3622: 	$radio.='</tr></table>';
                   3623: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3624: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3625: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3626: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3627:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3628:             '<select name="SELVAL_'.$partid.'" '.
                   3629:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3630:                 $weight{$partid}.')"> '.
1.401     albertel 3631: 	    '<option selected="selected"> </option>'.
1.485     albertel 3632: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3633: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3634: 	    '</select></td>'.
                   3635:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3636: 	$line.='<input type="hidden" name="partid_'.
                   3637: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3638: 	$line.='<input type="hidden" name="weight_'.
                   3639: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3640: 
                   3641: 	$result.=
                   3642: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3643: 	    '<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 3644: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3645: 	$ctsparts++;
1.41      ng       3646:     }
1.474     albertel 3647:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3648: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3649:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3650: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3651: 
1.44      ng       3652:     #table listing all the students in a section/class
                   3653:     #header of table
1.560     raeburn  3654:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3655:               &Apache::loncommon::start_data_table().
                   3656: 	      &Apache::loncommon::start_data_table_header_row().
                   3657: 	      '<th>'.&mt('No.').'</th>'.
                   3658: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3659:     my $partserror;
                   3660:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3661:     if ($partserror) {
                   3662:         return &navmap_errormsg();
                   3663:     }
1.324     albertel 3664:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3665:     my @partids = ();
1.41      ng       3666:     foreach my $part (@parts) {
                   3667: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3668:         my $narrowtext = &mt('Tries');
                   3669: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3670: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3671: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3672:         push(@partids,$partid);
1.628     www      3673: #
                   3674: # FIXME: Looks like $display looks at English text
                   3675: #
1.324     albertel 3676: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3677: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3678: 	    $result.='<th>'.
1.697     bisitz   3679: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3680: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3681: 	    next;
1.485     albertel 3682: 	    
1.207     albertel 3683: 	} else {
1.485     albertel 3684: 	    if ($display =~ /Problem Status/) {
                   3685: 		my $grade_status_mt = &mt('Grade Status');
                   3686: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3687: 	    }
                   3688: 	    my $part_mt = &mt('Part:');
                   3689: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3690: 	}
1.485     albertel 3691: 
1.474     albertel 3692: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3693:     }
1.474     albertel 3694:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3695: 
1.270     albertel 3696:     my %last_resets = 
                   3697: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3698: 
1.41      ng       3699:     #get info for each student
1.44      ng       3700:     #list all the students - with points and grade status
1.257     albertel 3701:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3702:     my $ctr = 0;
1.294     albertel 3703:     foreach (sort 
                   3704: 	     {
                   3705: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3706: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3707: 		 }
                   3708: 		 return $a cmp $b;
                   3709: 	     } (keys(%$fullname))) {
1.126     ng       3710: 	$ctr++;
1.324     albertel 3711: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3712: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3713:     }
1.474     albertel 3714:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3715:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3716:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3717: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3718:     if (scalar(%$fullname) eq 0) {
                   3719: 	my $colspan=3+scalar(@parts);
1.433     banghart 3720: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3721:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3722: 	$result='<span class="LC_warning">'.
1.485     albertel 3723: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3724: 	        $section_display, $stu_status).
1.433     banghart 3725: 	    '</span>';
1.96      albertel 3726:     }
1.41      ng       3727:     return $result;
                   3728: }
                   3729: 
1.44      ng       3730: #--- call by previous routine to display each student
1.41      ng       3731: sub viewstudentgrade {
1.324     albertel 3732:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3733:     my ($uname,$udom) = split(/:/,$student);
                   3734:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3735:     my %aggregates = (); 
1.474     albertel 3736:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3737: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3738: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3739: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3740: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3741: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3742:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3743:     foreach my $apart (@$parts) {
                   3744: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3745: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3746:         $result.='<td align="center">';
1.269     raeburn  3747:         my ($aggtries,$totaltries);
                   3748:         unless (exists($aggregates{$part})) {
1.270     albertel 3749: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3750: 
                   3751: 	    $aggtries = $totaltries;
1.269     raeburn  3752:             if ($$last_resets{$part}) {  
1.270     albertel 3753:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3754: 					   $part);
                   3755:             }
1.269     raeburn  3756:             $result.='<input type="hidden" name="'.
                   3757:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3758:             $result.='<input type="hidden" name="'.
                   3759:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3760:             $aggregates{$part} = 1;
                   3761:         }
1.41      ng       3762: 	if ($type eq 'awarded') {
1.320     albertel 3763: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3764: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3765: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3766: 	    $result.='<input type="text" name="'.
1.89      albertel 3767: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3768:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3769: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3770: 	} elsif ($type eq 'solved') {
                   3771: 	    my ($status,$foo)=split(/_/,$score,2);
                   3772: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3773: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3774: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3775: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3776: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3777:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3778: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3779: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3780: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3781: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3782: 	} else {
                   3783: 	    $result.='<input type="hidden" name="'.
                   3784: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3785: 		    "\n";
1.233     albertel 3786: 	    $result.='<input type="text" name="'.
1.122     ng       3787: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3788: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3789: 	}
                   3790:     }
1.474     albertel 3791:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3792:     return $result;
1.38      ng       3793: }
                   3794: 
1.44      ng       3795: #--- change scores for all the students in a section/class
                   3796: #    record does not get update if unchanged
1.38      ng       3797: sub editgrades {
1.608     www      3798:     my ($request,$symb) = @_;
1.41      ng       3799: 
1.433     banghart 3800:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3801:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3802:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3803: 
1.477     albertel 3804:     my $result= &Apache::loncommon::start_data_table().
                   3805: 	&Apache::loncommon::start_data_table_header_row().
                   3806: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3807: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3808:     my %scoreptr = (
                   3809: 		    'correct'  =>'correct_by_override',
                   3810: 		    'incorrect'=>'incorrect_by_override',
                   3811: 		    'excused'  =>'excused',
                   3812: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3813:                     'credited' =>'credit_attempted',
1.43      ng       3814: 		    'nothing'  => '',
                   3815: 		    );
1.257     albertel 3816:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3817: 
1.44      ng       3818:     my (@partid);
                   3819:     my %weight = ();
1.54      albertel 3820:     my %columns = ();
1.44      ng       3821:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3822: 
1.582     raeburn  3823:     my $partserror;
                   3824:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3825:     if ($partserror) {
                   3826:         return &navmap_errormsg();
                   3827:     }
1.54      albertel 3828:     my $header;
1.257     albertel 3829:     while ($ctr < $env{'form.totalparts'}) {
                   3830: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3831: 	push(@partid,$partid);
1.257     albertel 3832: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3833: 	$ctr++;
1.54      albertel 3834:     }
1.324     albertel 3835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3836:     foreach my $partid (@partid) {
1.478     albertel 3837: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3838: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3839: 	$columns{$partid}=2;
                   3840: 	foreach my $stores (@parts) {
                   3841: 	    my ($part,$type) = &split_part_type($stores);
                   3842: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3843: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3844: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3845: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3846:             my $narrowtext = &mt('Tries');
                   3847: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3848: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3849: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3850: 	    $columns{$partid}+=2;
                   3851: 	}
                   3852:     }
                   3853:     foreach my $partid (@partid) {
1.324     albertel 3854: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3855: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3856: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3857: 	    '</th>';
1.54      albertel 3858: 
1.44      ng       3859:     }
1.477     albertel 3860:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3861: 	&Apache::loncommon::start_data_table_header_row().
                   3862: 	$header.
                   3863: 	&Apache::loncommon::end_data_table_header_row();
                   3864:     my @noupdate;
1.126     ng       3865:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3866:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3867: 	my $line;
1.257     albertel 3868: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3869: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3870: 	my %newrecord;
                   3871: 	my $updateflag = 0;
1.281     albertel 3872: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3873: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3874: 	if (!&canmodify($usec)) {
1.126     ng       3875: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3876: 	    push(@noupdate,
1.478     albertel 3877: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3878: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3879: 	    next;
                   3880: 	}
1.269     raeburn  3881:         my %aggregate = ();
                   3882:         my $aggregateflag = 0;
1.281     albertel 3883: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3884: 	foreach (@partid) {
1.257     albertel 3885: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3886: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3887: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3888: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3889: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3890: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3891: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3892: 	    my $score;
                   3893: 	    if ($partial eq '') {
1.257     albertel 3894: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3895: 	    } elsif ($partial > 0) {
                   3896: 		$score = 'correct_by_override';
                   3897: 	    } elsif ($partial == 0) {
                   3898: 		$score = 'incorrect_by_override';
                   3899: 	    }
1.257     albertel 3900: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3901: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3902: 
1.292     albertel 3903: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3904: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3905: 	    if ($dropMenu eq 'reset status' &&
                   3906: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3907: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3908: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3909: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3910: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3911: 		$updateflag = 1;
1.269     raeburn  3912:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3913:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3914:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3915:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3916:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3917:                     $aggregateflag = 1;
                   3918:                 }
1.139     albertel 3919: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3920: 		$updateflag = 1;
                   3921: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3922: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3923: 		$rec_update++;
1.125     ng       3924: 	    }
                   3925: 
1.93      albertel 3926: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3927: 		'<td align="center">'.$awarded.
                   3928: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3929: 
1.54      albertel 3930: 
                   3931: 	    my $partid=$_;
                   3932: 	    foreach my $stores (@parts) {
                   3933: 		my ($part,$type) = &split_part_type($stores);
                   3934: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3935: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3936: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3937: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3938: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3939: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3940: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3941: 		    $updateflag=1;
                   3942: 		}
1.93      albertel 3943: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3944: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3945: 	    }
1.44      ng       3946: 	}
1.477     albertel 3947: 	$line.="\n";
1.301     albertel 3948: 
                   3949: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3950: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3951: 
1.44      ng       3952: 	if ($updateflag) {
                   3953: 	    $count++;
1.257     albertel 3954: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3955: 				    $udom,$uname);
1.301     albertel 3956: 
                   3957: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3958: 					      $cnum,$udom,$uname)) {
                   3959: 		# need to figure out if should be in queue.
                   3960: 		my %record =  
                   3961: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3962: 					     $udom,$uname);
                   3963: 		my $all_graded = 1;
                   3964: 		my $none_graded = 1;
                   3965: 		foreach my $part (@parts) {
                   3966: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3967: 			$all_graded = 0;
                   3968: 		    } else {
                   3969: 			$none_graded = 0;
                   3970: 		    }
                   3971: 		}
                   3972: 
                   3973: 		if ($all_graded || $none_graded) {
                   3974: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3975: 							   $symb,$cdom,$cnum,
                   3976: 							   $udom,$uname);
                   3977: 		}
                   3978: 	    }
                   3979: 
1.477     albertel 3980: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3981: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3982: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3983: 	    $updateCtr++;
1.93      albertel 3984: 	} else {
1.477     albertel 3985: 	    push(@noupdate,
                   3986: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3987: 	    $noupdateCtr++;
1.44      ng       3988: 	}
1.269     raeburn  3989:         if ($aggregateflag) {
                   3990:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3991: 				  $cdom,$cnum);
1.269     raeburn  3992:         }
1.93      albertel 3993:     }
1.477     albertel 3994:     if (@noupdate) {
1.126     ng       3995: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3996: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3997: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3998: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3999: 	    &mt('No Changes Occurred For the Students Below').
                   4000: 	    '</td>'.
1.477     albertel 4001: 	    &Apache::loncommon::end_data_table_row();
                   4002: 	foreach my $line (@noupdate) {
                   4003: 	    $result.=
                   4004: 		&Apache::loncommon::start_data_table_row().
                   4005: 		$line.
                   4006: 		&Apache::loncommon::end_data_table_row();
                   4007: 	}
1.44      ng       4008:     }
1.614     www      4009:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4010:     my $msg = '<p><b>'.
                   4011: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4012: 	    $rec_update,$count).'</b><br />'.
                   4013: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4014: 	'</b></p>';
1.44      ng       4015:     return $title.$msg.$result;
1.5       albertel 4016: }
1.54      albertel 4017: 
                   4018: sub split_part_type {
                   4019:     my ($partstr) = @_;
                   4020:     my ($temp,@allparts)=split(/_/,$partstr);
                   4021:     my $type=pop(@allparts);
1.439     albertel 4022:     my $part=join('_',@allparts);
1.54      albertel 4023:     return ($part,$type);
                   4024: }
                   4025: 
1.44      ng       4026: #------------- end of section for handling grading by section/class ---------
                   4027: #
                   4028: #----------------------------------------------------------------------------
                   4029: 
1.5       albertel 4030: 
1.44      ng       4031: #----------------------------------------------------------------------------
                   4032: #
                   4033: #-------------------------- Next few routines handles grading by csv upload
                   4034: #
                   4035: #--- Javascript to handle csv upload
1.27      albertel 4036: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4037:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4038:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4039:   &js_escape(\$error1);
                   4040:   &js_escape(\$error2);
1.27      albertel 4041:   return(<<ENDPICK);
                   4042:   function verify(vf) {
                   4043:     var foundsomething=0;
                   4044:     var founduname=0;
1.243     albertel 4045:     var foundID=0;
1.27      albertel 4046:     for (i=0;i<=vf.nfields.value;i++) {
                   4047:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4048:       if (i==0 && tw!=0) { foundID=1; }
                   4049:       if (i==1 && tw!=0) { founduname=1; }
                   4050:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4051:     }
1.246     albertel 4052:     if (founduname==0 && foundID==0) {
                   4053: 	alert('$error1');
                   4054: 	return;
1.27      albertel 4055:     }
                   4056:     if (foundsomething==0) {
1.246     albertel 4057: 	alert('$error2');
                   4058: 	return;
1.27      albertel 4059:     }
                   4060:     vf.submit();
                   4061:   }
                   4062:   function flip(vf,tf) {
                   4063:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4064:     var i;
                   4065:     for (i=0;i<=vf.nfields.value;i++) {
                   4066:       //can not pick the same destination field for both name and domain
                   4067:       if (((i ==0)||(i ==1)) && 
                   4068:           ((tf==0)||(tf==1)) && 
                   4069:           (i!=tf) &&
                   4070:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4071:         eval('vf.f'+i+'.selectedIndex=0;')
                   4072:       }
                   4073:     }
                   4074:   }
                   4075: ENDPICK
                   4076: }
                   4077: 
                   4078: sub csvupload_javascript_forward_associate {
1.573     bisitz   4079:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4080:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4081:   &js_escape(\$error1);
                   4082:   &js_escape(\$error2);
1.27      albertel 4083:   return(<<ENDPICK);
                   4084:   function verify(vf) {
                   4085:     var foundsomething=0;
                   4086:     var founduname=0;
1.243     albertel 4087:     var foundID=0;
1.27      albertel 4088:     for (i=0;i<=vf.nfields.value;i++) {
                   4089:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4090:       if (tw==1) { foundID=1; }
                   4091:       if (tw==2) { founduname=1; }
                   4092:       if (tw>3) { foundsomething=1; }
1.27      albertel 4093:     }
1.246     albertel 4094:     if (founduname==0 && foundID==0) {
                   4095: 	alert('$error1');
                   4096: 	return;
1.27      albertel 4097:     }
                   4098:     if (foundsomething==0) {
1.246     albertel 4099: 	alert('$error2');
                   4100: 	return;
1.27      albertel 4101:     }
                   4102:     vf.submit();
                   4103:   }
                   4104:   function flip(vf,tf) {
                   4105:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4106:     var i;
                   4107:     //can not pick the same destination field twice
                   4108:     for (i=0;i<=vf.nfields.value;i++) {
                   4109:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4110:         eval('vf.f'+i+'.selectedIndex=0;')
                   4111:       }
                   4112:     }
                   4113:   }
                   4114: ENDPICK
                   4115: }
                   4116: 
1.26      albertel 4117: sub csvuploadmap_header {
1.324     albertel 4118:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4119:     my $javascript;
1.257     albertel 4120:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4121: 	$javascript=&csvupload_javascript_reverse_associate();
                   4122:     } else {
                   4123: 	$javascript=&csvupload_javascript_forward_associate();
                   4124:     }
1.45      ng       4125: 
1.418     albertel 4126:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4127:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4128:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4129:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4130:     my $reverse=&mt("Reverse Association");
1.41      ng       4131:     $request->print(<<ENDPICK);
1.632     www      4132: <br />
                   4133: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4134: <input type="hidden" name="associate"  value="" />
                   4135: <input type="hidden" name="phase"      value="three" />
                   4136: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4137: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4138: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4139: <input type="hidden" name="upfile_associate" 
1.257     albertel 4140:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4141: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4142: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4143: <hr />
                   4144: ENDPICK
1.597     wenzelju 4145:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4146:     return '';
1.26      albertel 4147: 
                   4148: }
                   4149: 
                   4150: sub csvupload_fields {
1.582     raeburn  4151:     my ($symb,$errorref) = @_;
                   4152:     my (@parts) = &getpartlist($symb,$errorref);
                   4153:     if (ref($errorref)) {
                   4154:         if ($$errorref) {
                   4155:             return;
                   4156:         }
                   4157:     }
                   4158: 
1.556     weissno  4159:     my @fields=(['ID','Student/Employee ID'],
1.737   ! raeburn  4160:                 ['clicker','Clicker ID'],
1.243     albertel 4161: 		['username','Student Username'],
                   4162: 		['domain','Student Domain']);
1.324     albertel 4163:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4164:     foreach my $part (sort(@parts)) {
                   4165: 	my @datum;
                   4166: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4167: 	my $name=$part;
                   4168: 	if  (!$display) { $display = $name; }
                   4169: 	@datum=($name,$display);
1.244     albertel 4170: 	if ($name=~/^stores_(.*)_awarded/) {
                   4171: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4172: 	}
1.41      ng       4173: 	push(@fields,\@datum);
                   4174:     }
                   4175:     return (@fields);
1.26      albertel 4176: }
                   4177: 
                   4178: sub csvuploadmap_footer {
1.41      ng       4179:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4180:     my $buttontext = &mt('Assign Grades');
1.41      ng       4181:     $request->print(<<ENDPICK);
1.26      albertel 4182: </table>
                   4183: <input type="hidden" name="nfields" value="$i" />
                   4184: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4185: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4186: </form>
                   4187: ENDPICK
                   4188: }
                   4189: 
1.283     albertel 4190: sub checkforfile_js {
1.638     www      4191:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4192:     &js_escape(\$alertmsg);
1.597     wenzelju 4193:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4194:     function checkUpload(formname) {
                   4195: 	if (formname.upfile.value == "") {
1.539     riegler  4196: 	    alert("$alertmsg");
1.86      ng       4197: 	    return false;
                   4198: 	}
                   4199: 	formname.submit();
                   4200:     }
                   4201: CSVFORMJS
1.283     albertel 4202:     return $result;
                   4203: }
                   4204: 
                   4205: sub upcsvScores_form {
1.608     www      4206:     my ($request,$symb) = @_;
1.283     albertel 4207:     if (!$symb) {return '';}
                   4208:     my $result=&checkforfile_js();
1.632     www      4209:     $result.=&Apache::loncommon::start_data_table().
                   4210:              &Apache::loncommon::start_data_table_header_row().
                   4211:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4212:              &Apache::loncommon::end_data_table_header_row().
                   4213:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4214:     my $upload=&mt("Upload Scores");
1.86      ng       4215:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4216:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4217:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4218:     $result.=<<ENDUPFORM;
1.106     albertel 4219: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4220: <input type="hidden" name="symb" value="$symb" />
                   4221: <input type="hidden" name="command" value="csvuploadmap" />
                   4222: $upfile_select
1.589     bisitz   4223: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4224: </form>
                   4225: ENDUPFORM
1.370     www      4226:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4227:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4228:              '</td>'.
                   4229:             &Apache::loncommon::end_data_table_row().
                   4230:             &Apache::loncommon::end_data_table();
1.86      ng       4231:     return $result;
                   4232: }
                   4233: 
                   4234: 
1.26      albertel 4235: sub csvuploadmap {
1.608     www      4236:     my ($request,$symb)= @_;
1.41      ng       4237:     if (!$symb) {return '';}
1.72      ng       4238: 
1.41      ng       4239:     my $datatoken;
1.257     albertel 4240:     if (!$env{'form.datatoken'}) {
1.41      ng       4241: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4242:     } else {
1.257     albertel 4243: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4244: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4245:     }
1.41      ng       4246:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4247:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4248:     my ($i,$keyfields);
                   4249:     if (@records) {
1.582     raeburn  4250:         my $fieldserror;
                   4251: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4252:         if ($fieldserror) {
                   4253:             $request->print(&navmap_errormsg());
                   4254:             return;
                   4255:         }
1.257     albertel 4256: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4257: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4258: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4259: 							  \@fields);
                   4260: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4261: 	    chop($keyfields);
                   4262: 	} else {
                   4263: 	    unshift(@fields,['none','']);
                   4264: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4265: 							    \@fields);
1.311     banghart 4266:             foreach my $rec (@records) {
                   4267:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4268:                 if (%temp) {
                   4269:                     $keyfields=join(',',sort(keys(%temp)));
                   4270:                     last;
                   4271:                 }
                   4272:             }
1.41      ng       4273: 	}
                   4274:     }
                   4275:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4276: 
1.41      ng       4277:     return '';
1.27      albertel 4278: }
                   4279: 
1.246     albertel 4280: sub csvuploadoptions {
1.608     www      4281:     my ($request,$symb)= @_;
1.632     www      4282:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4283:     $request->print(<<ENDPICK);
                   4284: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4285: <input type="hidden" name="command"    value="csvuploadassign" />
                   4286: <p>
                   4287: <label>
                   4288:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4289:    $overwrite
1.246     albertel 4290: </label>
                   4291: </p>
                   4292: ENDPICK
                   4293:     my %fields=&get_fields();
                   4294:     if (!defined($fields{'domain'})) {
1.257     albertel 4295: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4296: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4297:     }
1.257     albertel 4298:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4299: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4300: 	my $cleankey=$1;
                   4301: 	if ($cleankey eq 'command') { next; }
                   4302: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4303: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4304:     }
                   4305:     # FIXME do a check for any duplicated user ids...
                   4306:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4307:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4308: <hr /></form>'."\n");
1.246     albertel 4309:     return '';
                   4310: }
                   4311: 
                   4312: sub get_fields {
                   4313:     my %fields;
1.257     albertel 4314:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4315:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4316: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4317: 	    if ($env{'form.f'.$i} ne 'none') {
                   4318: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4319: 	    }
                   4320: 	} else {
1.257     albertel 4321: 	    if ($env{'form.f'.$i} ne 'none') {
                   4322: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4323: 	    }
                   4324: 	}
1.27      albertel 4325:     }
1.246     albertel 4326:     return %fields;
                   4327: }
                   4328: 
                   4329: sub csvuploadassign {
1.608     www      4330:     my ($request,$symb)= @_;
1.246     albertel 4331:     if (!$symb) {return '';}
1.345     bowersj2 4332:     my $error_msg = '';
1.246     albertel 4333:     &Apache::loncommon::load_tmp_file($request);
                   4334:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4335:     my %fields=&get_fields();
1.257     albertel 4336:     my $courseid=$env{'request.course.id'};
1.97      albertel 4337:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4338:     my @notallowed;
1.41      ng       4339:     my @skipped;
1.657     raeburn  4340:     my @warnings;
1.41      ng       4341:     my $countdone=0;
                   4342:     foreach my $grade (@gradedata) {
                   4343: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4344: 	my $domain;
                   4345: 	if ($entries{$fields{'domain'}}) {
                   4346: 	    $domain=$entries{$fields{'domain'}};
                   4347: 	} else {
1.257     albertel 4348: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4349: 	}
1.243     albertel 4350: 	$domain=~s/\s//g;
1.41      ng       4351: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4352: 	$username=~s/\s//g;
1.243     albertel 4353: 	if (!$username) {
                   4354: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4355: 	    $id=~s/\s//g;
1.737   ! raeburn  4356:             if ($id ne '') {
        !          4357: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
        !          4358: 	        $username=$ids{$id};
        !          4359:             } else {
        !          4360:                 if ($entries{$fields{'clicker'}}) {
        !          4361:                     my $clicker = $entries{$fields{'clicker'}};
        !          4362:                     $clicker=~s/\s//g;
        !          4363:                     if ($clicker ne '') {
        !          4364:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
        !          4365:                         if ($clickers{$clicker} ne '') {  
        !          4366:                             my $match = 0;
        !          4367:                             my @inclass;
        !          4368:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
        !          4369:                                 if (exists($$classlist{"$poss:$domain"})) {
        !          4370:                                     $username = $poss;
        !          4371:                                     push(@inclass,$poss);
        !          4372:                                     $match ++;
        !          4373:                                     
        !          4374:                                 }
        !          4375:                             }
        !          4376:                             if ($match > 1) {
        !          4377:                                 undef($username); 
        !          4378:                                 $request->print('<p class="LC_warning">'.
        !          4379:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
        !          4380:                                                 $clicker,join(', ',@inclass)).'</p>');
        !          4381:                             }
        !          4382:                         }
        !          4383:                     }
        !          4384:                 }
        !          4385:             }
1.243     albertel 4386: 	}
1.41      ng       4387: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4388: 	    my $id=$entries{$fields{'ID'}};
                   4389: 	    $id=~s/\s//g;
1.737   ! raeburn  4390:             my $clicker = $entries{$fields{'clicker'}};
        !          4391:             $clicker=~s/\s//g;
        !          4392:             if ($clicker) {
        !          4393:                 push(@skipped,"$clicker:$domain");
        !          4394: 	    } elsif ($id) {
1.247     albertel 4395: 		push(@skipped,"$id:$domain");
                   4396: 	    } else {
                   4397: 		push(@skipped,"$username:$domain");
                   4398: 	    }
1.41      ng       4399: 	    next;
                   4400: 	}
1.108     albertel 4401: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4402: 	if (!&canmodify($usec)) {
                   4403: 	    push(@notallowed,"$username:$domain");
                   4404: 	    next;
                   4405: 	}
1.244     albertel 4406: 	my %points;
1.41      ng       4407: 	my %grades;
                   4408: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4409: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4410: 		$dest eq 'domain') { next; }
                   4411: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4412: 	    if ($dest=~/stores_(.*)_points/) {
                   4413: 		my $part=$1;
                   4414: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4415: 					      $symb,$domain,$username);
1.345     bowersj2 4416:                 if ($wgt) {
                   4417:                     $entries{$fields{$dest}}=~s/\s//g;
                   4418:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4419:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4420:                                           : 'correct_by_override';
1.638     www      4421:                     if ($pcr>1) {
1.657     raeburn  4422:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4423:                     }
1.345     bowersj2 4424:                     $grades{"resource.$part.awarded"}=$pcr;
                   4425:                     $grades{"resource.$part.solved"}=$award;
                   4426:                     $points{$part}=1;
                   4427:                 } else {
                   4428:                     $error_msg = "<br />" .
                   4429:                         &mt("Some point values were assigned"
                   4430:                             ." for problems with a weight "
                   4431:                             ."of zero. These values were "
                   4432:                             ."ignored.");
                   4433:                 }
1.244     albertel 4434: 	    } else {
                   4435: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4436: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4437: 		my $store_key=$dest;
                   4438: 		$store_key=~s/^stores/resource/;
                   4439: 		$store_key=~s/_/\./g;
                   4440: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4441: 	    }
1.41      ng       4442: 	}
1.508     www      4443: 	if (! %grades) { 
                   4444:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4445:         } else {
                   4446: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4447: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4448: 					   $env{'request.course.id'},
                   4449: 					   $domain,$username);
1.508     www      4450: 	   if ($result eq 'ok') {
1.627     www      4451: # Successfully stored
1.508     www      4452: 	      $request->print('.');
1.627     www      4453: # Remove from grading queue
                   4454:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4455:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4456:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4457:                                              $domain,$username);
                   4458:               $countdone++;
                   4459:            } else {
1.508     www      4460: 	      $request->print("<p><span class=\"LC_error\">".
                   4461:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4462:                                   "$username:$domain",$result)."</span></p>");
                   4463: 	   }
                   4464: 	   $request->rflush();
                   4465:         }
1.41      ng       4466:     }
1.570     www      4467:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4468:     if (@warnings) {
                   4469:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4470:         $request->print(join(', ',@warnings));
                   4471:     }
1.41      ng       4472:     if (@skipped) {
1.571     www      4473: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4474:         $request->print(join(', ',@skipped));
1.106     albertel 4475:     }
                   4476:     if (@notallowed) {
1.571     www      4477: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4478: 	$request->print(join(', ',@notallowed));
1.41      ng       4479:     }
1.106     albertel 4480:     $request->print("<br />\n");
1.345     bowersj2 4481:     return $error_msg;
1.26      albertel 4482: }
1.44      ng       4483: #------------- end of section for handling csv file upload ---------
                   4484: #
                   4485: #-------------------------------------------------------------------
                   4486: #
1.122     ng       4487: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4488: #
                   4489: #--- Select a page/sequence and a student to grade
1.68      ng       4490: sub pickStudentPage {
1.608     www      4491:     my ($request,$symb) = @_;
1.68      ng       4492: 
1.539     riegler  4493:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4494:     &js_escape(\$alertmsg);
1.597     wenzelju 4495:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4496: 
                   4497: function checkPickOne(formname) {
1.76      ng       4498:     if (radioSelection(formname.student) == null) {
1.539     riegler  4499: 	alert("$alertmsg");
1.68      ng       4500: 	return;
                   4501:     }
1.125     ng       4502:     ptr = pullDownSelection(formname.selectpage);
                   4503:     formname.page.value = formname["page"+ptr].value;
                   4504:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4505:     formname.submit();
                   4506: }
                   4507: 
                   4508: LISTJAVASCRIPT
1.118     ng       4509:     &commonJSfunctions($request);
1.608     www      4510: 
1.257     albertel 4511:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4512:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4513:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4514: 
1.398     albertel 4515:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4516: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4517: 
1.80      ng       4518:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4519:     my $map_error;
                   4520:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4521:     if ($map_error) {
                   4522:         $request->print(&navmap_errormsg());
                   4523:         return; 
                   4524:     }
1.137     albertel 4525:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4526: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4527: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4528: 
                   4529:     # Collection of hidden fields
1.70      ng       4530:     my $ctr=0;
1.68      ng       4531:     foreach (@$titles) {
1.700     bisitz   4532:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4533:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4534:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4535:         $ctr++;
1.68      ng       4536:     }
1.700     bisitz   4537:     $result.='<input type="hidden" name="page" />'."\n".
                   4538:         '<input type="hidden" name="title" />'."\n";
                   4539: 
                   4540:     $result.=&build_section_inputs();
                   4541:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4542:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4543: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4544: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4545: 
1.700     bisitz   4546:     # Show grading options
                   4547:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4548:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4549:     $ctr=0;
                   4550:     foreach (@$titles) {
                   4551: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4552: 	$select.='<option value="'.$ctr.'"'.
                   4553: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4554: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4555: 	$ctr++;
                   4556:     }
1.700     bisitz   4557:     $select.= '</select>';
1.68      ng       4558: 
1.700     bisitz   4559:     $result.=
                   4560:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4561:        .$select
                   4562:        .&Apache::lonhtmlcommon::row_closure();
                   4563: 
                   4564:     $result.=
                   4565:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4566:        .'<label><input type="radio" name="vProb" value="no"'
                   4567:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4568:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4569:            .&mt('yes').'</label>'."\n"
                   4570:        .&Apache::lonhtmlcommon::row_closure();
                   4571: 
                   4572:     $result.=
                   4573:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4574:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4575:            .&mt('none').' </label>'."\n"
                   4576:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4577:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4578:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4579:            .&mt('all submissions with details').' </label>'
                   4580:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4581:     
1.700     bisitz   4582:     $result.=
                   4583:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4584:        .'<input type="text" name="CODE" value="" />'
                   4585:        .&Apache::lonhtmlcommon::row_closure(1)
                   4586:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4587: 
1.700     bisitz   4588:     # Show list of students to select for grading
                   4589:     $result.='<br /><input type="button" '.
1.589     bisitz   4590:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4591: 
1.68      ng       4592:     $request->print($result);
                   4593: 
1.485     albertel 4594:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4595: 	&Apache::loncommon::start_data_table().
                   4596: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4597: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4598: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4599: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4600: 	'<th>'.&nameUserString('header').'</th>'.
                   4601: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4602:  
1.76      ng       4603:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4604:     my $ptr = 1;
1.294     albertel 4605:     foreach my $student (sort 
                   4606: 			 {
                   4607: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4608: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4609: 			     }
                   4610: 			     return $a cmp $b;
                   4611: 			 } (keys(%$fullname))) {
1.68      ng       4612: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4613: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4614:                                   : '</td>');
1.126     ng       4615: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4616: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4617: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4618: 	$studentTable.=
                   4619: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4620:                          : '');
1.68      ng       4621: 	$ptr++;
                   4622:     }
1.484     albertel 4623:     if ($ptr%2 == 0) {
                   4624: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4625: 	    &Apache::loncommon::end_data_table_row();
                   4626:     }
                   4627:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4628:     $studentTable.='<input type="button" '.
1.589     bisitz   4629:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4630: 
                   4631:     $request->print($studentTable);
                   4632: 
                   4633:     return '';
                   4634: }
                   4635: 
                   4636: sub getSymbMap {
1.582     raeburn  4637:     my ($map_error) = @_;
1.132     bowersj2 4638:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4639:     unless (ref($navmap)) {
                   4640:         if (ref($map_error)) {
                   4641:             $$map_error = 'navmap';
                   4642:         }
                   4643:         return;
                   4644:     }
1.68      ng       4645:     my %symbx = ();
                   4646:     my @titles = ();
1.117     bowersj2 4647:     my $minder = 0;
                   4648: 
                   4649:     # Gather every sequence that has problems.
1.240     albertel 4650:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4651: 					       1,0,1);
1.117     bowersj2 4652:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4653: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4654: 	    my $title = $minder.'.'.
                   4655: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4656: 	    push(@titles, $title); # minder in case two titles are identical
                   4657: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4658: 	    $minder++;
1.241     albertel 4659: 	}
1.68      ng       4660:     }
                   4661:     return \@titles,\%symbx;
                   4662: }
                   4663: 
1.72      ng       4664: #
                   4665: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4666: sub displayPage {
1.608     www      4667:     my ($request,$symb) = @_;
1.257     albertel 4668:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4669:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4670:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4671:     my $pageTitle = $env{'form.page'};
1.103     albertel 4672:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4673:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4674:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4675: 
                   4676:     #need to make sure we have the correct data for later EXT calls, 
                   4677:     #thus invalidate the cache
                   4678:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4679:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4680:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4681:     &Apache::lonnet::clear_EXT_cache_status();
                   4682: 
1.103     albertel 4683:     if (!&canview($usec)) {
1.712     bisitz   4684:         $request->print(
                   4685:             '<span class="LC_warning">'.
                   4686:             &mt('Unable to view requested student. ([_1])',
                   4687:                     $env{'form.student'}).
                   4688:             '</span>');
                   4689:         return;
1.103     albertel 4690:     }
1.398     albertel 4691:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4692:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4693: 	'</h3>'."\n";
1.500     albertel 4694:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4695:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4696: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4697:     } else {
                   4698: 	delete($env{'form.CODE'});
                   4699:     }
1.71      ng       4700:     &sub_page_js($request);
                   4701:     $request->print($result);
                   4702: 
1.132     bowersj2 4703:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4704:     unless (ref($navmap)) {
                   4705:         $request->print(&navmap_errormsg());
                   4706:         return;
                   4707:     }
1.257     albertel 4708:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4709:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4710:     if (!$map) {
1.485     albertel 4711: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4712: 	return; 
                   4713:     }
1.68      ng       4714:     my $iterator = $navmap->getIterator($map->map_start(),
                   4715: 					$map->map_finish());
                   4716: 
1.71      ng       4717:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4718: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4719: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4720: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4721: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4722: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4723: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4724: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4725: 
1.382     albertel 4726:     if (defined($env{'form.CODE'})) {
                   4727: 	$studentTable.=
                   4728: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4729:     }
1.381     albertel 4730:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4731: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4732: 
1.594     bisitz   4733:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4734:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4735:         '</span>'."\n".
1.484     albertel 4736: 	&Apache::loncommon::start_data_table().
                   4737: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4738: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4739: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4740: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4741: 
1.329     albertel 4742:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4743:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4744:     $iterator->next(); # skip the first BEGIN_MAP
                   4745:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4746:     while ($depth > 0) {
1.68      ng       4747:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4748:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4749: 
1.385     albertel 4750:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4751: 	    my $parts = $curRes->parts();
1.68      ng       4752:             my $title = $curRes->compTitle();
1.71      ng       4753: 	    my $symbx = $curRes->symb();
1.484     albertel 4754: 	    $studentTable.=
                   4755: 		&Apache::loncommon::start_data_table_row().
                   4756: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4757: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4758: 		                        : '<br />('.&mt('[_1]parts',
                   4759: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4760: 		 ).
                   4761: 		 '</td>';
1.71      ng       4762: 	    $studentTable.='<td valign="top">';
1.382     albertel 4763: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4764: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4765: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4766: 					     undef,'both',\%form);
1.71      ng       4767: 	    } else {
1.382     albertel 4768: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4769: 		$companswer =~ s|<form(.*?)>||g;
                   4770: 		$companswer =~ s|</form>||g;
1.71      ng       4771: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4772: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4773: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4774: #		}
1.116     ng       4775: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4776: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4777: 	    }
                   4778: 
1.257     albertel 4779: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4780: 
1.257     albertel 4781: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4782: 		if ($record{'version'} eq '') {
1.485     albertel 4783: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4784: 		} else {
1.116     ng       4785: 		    my %responseType = ();
                   4786: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4787: 			my @responseIds =$curRes->responseIds($partid);
                   4788: 			my @responseType =$curRes->responseType($partid);
                   4789: 			my %responseIds;
                   4790: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4791: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4792: 			}
                   4793: 			$responseType{$partid} = \%responseIds;
1.116     ng       4794: 		    }
1.148     albertel 4795: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4796: 
1.71      ng       4797: 		}
1.257     albertel 4798: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4799: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  4800:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       4801: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4802: 									$env{'request.course.id'},
1.726     raeburn  4803: 									'','.submission',undef,
                   4804:                                                                         $usec,$identifier);
1.71      ng       4805:  
                   4806: 	    }
1.103     albertel 4807: 	    if (&canmodify($usec)) {
1.585     bisitz   4808:             $studentTable.=&gradeBox_start();
1.103     albertel 4809: 		foreach my $partid (@{$parts}) {
                   4810: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4811: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4812: 		    $question++;
                   4813: 		}
1.585     bisitz   4814:             $studentTable.=&gradeBox_end();
1.196     albertel 4815: 		$prob++;
1.71      ng       4816: 	    }
                   4817: 	    $studentTable.='</td></tr>';
1.68      ng       4818: 
1.103     albertel 4819: 	}
1.68      ng       4820:         $curRes = $iterator->next();
                   4821:     }
                   4822: 
1.589     bisitz   4823:     $studentTable.=
                   4824:         '</table>'."\n".
                   4825:         '<input type="button" value="'.&mt('Save').'" '.
                   4826:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4827:         '</form>'."\n";
1.71      ng       4828:     $request->print($studentTable);
                   4829: 
                   4830:     return '';
1.119     ng       4831: }
                   4832: 
                   4833: sub displaySubByDates {
1.148     albertel 4834:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4835:     my $isCODE=0;
1.335     albertel 4836:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4837:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4838:     my $studentTable=&Apache::loncommon::start_data_table().
                   4839: 	&Apache::loncommon::start_data_table_header_row().
                   4840: 	'<th>'.&mt('Date/Time').'</th>'.
                   4841: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4842:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4843: 	'<th>'.&mt('Submission').'</th>'.
                   4844: 	'<th>'.&mt('Status').'</th>'.
                   4845: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4846:     my ($version);
                   4847:     my %mark;
1.148     albertel 4848:     my %orders;
1.119     ng       4849:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4850:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4851: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4852:     }
1.335     albertel 4853: 
                   4854:     my $interaction;
1.525     raeburn  4855:     my $no_increment = 1;
1.735     raeburn  4856:     my (%lastrndseed,%lasttype);
1.119     ng       4857:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4858: 	my $timestamp = 
                   4859: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4860: 	if (exists($$record{$version.':resource.0.version'})) {
                   4861: 	    $interaction = $$record{$version.':resource.0.version'};
                   4862: 	}
1.671     raeburn  4863:         if ($isTask && $env{'form.previousversion'}) {
                   4864:             next unless ($interaction == $env{'form.previousversion'});
                   4865:         }
1.335     albertel 4866: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4867: 		             : "$version:resource");
1.467     albertel 4868: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4869: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4870: 	if ($isCODE) {
                   4871: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4872: 	}
1.671     raeburn  4873:         if ($isTask) {
                   4874:             $studentTable.='<td>'.$interaction.'</td>';
                   4875:         }
1.119     ng       4876: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4877: 	my @displaySub = ();
                   4878: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4879:             my ($hidden,$type);
                   4880:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4881:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4882:                 $hidden = 1;
                   4883:             }
1.335     albertel 4884: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4885: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4886: 	    
1.122     ng       4887: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4888: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4889: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4890: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4891: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4892:                     
1.335     albertel 4893: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4894: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4895:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4896:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4897:                                    .' <span class="LC_internal_info">'
1.625     www      4898:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4899:                                    .'</span>'
                   4900:                                    .' <b>';
1.596     raeburn  4901:                     if ($hidden) {
                   4902:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4903:                     } else {
1.640     raeburn  4904:                         my ($trial,$rndseed,$newvariation);
                   4905:                         if ($type eq 'randomizetry') {
                   4906:                             $trial = $$record{"$where.$partid.tries"};
1.733     raeburn  4907:                             $rndseed = $$record{"$where.$partid.rndseed"};
1.640     raeburn  4908:                         }
1.596     raeburn  4909: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4910: 			    $displaySub[0].=&mt('Trial not counted');
                   4911: 		        } else {
                   4912: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4913: 					    $$record{"$where.$partid.tries"});
1.734     raeburn  4914:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
1.735     raeburn  4915:                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   4916:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.640     raeburn  4917:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4918:                                 }
                   4919:                             }
                   4920:                             $lastrndseed{$partid} = $rndseed;
1.735     raeburn  4921:                             $lasttype{$partid} = $type;
1.596     raeburn  4922: 		        }
                   4923: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4924:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4925: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4926: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4927: 			    $orders{$partid}->{$responseId}=
                   4928: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4929:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4930: 		        }
1.640     raeburn  4931: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4932: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4933: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4934:                     }
1.147     albertel 4935: 		}
                   4936: 	    }
1.335     albertel 4937: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4938: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4939: 				    $$record{"$where.$partid.checkedin"},
                   4940: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4941: 					'<br />';
1.335     albertel 4942: 	    }
                   4943: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4944: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4945: 		    lc($$record{"$where.$partid.award"}).' '.
                   4946: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4947: 		    '<br />';
                   4948: 	    }
1.335     albertel 4949: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4950: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4951: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4952: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4953: 		$displaySub[2].=
                   4954: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4955: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4956: 	    }
                   4957: 	}
                   4958: 	# needed because old essay regrader has not parts info
                   4959: 	if (exists $$record{"$version:resource.regrader"}) {
                   4960: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4961: 	}
                   4962: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4963: 	if ($displaySub[2]) {
1.467     albertel 4964: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4965: 	}
1.467     albertel 4966: 	$studentTable.='&nbsp;</td>'.
                   4967: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4968:     }
1.467     albertel 4969:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4970:     return $studentTable;
1.71      ng       4971: }
                   4972: 
                   4973: sub updateGradeByPage {
1.608     www      4974:     my ($request,$symb) = @_;
1.71      ng       4975: 
1.257     albertel 4976:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4977:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4978:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4979:     my $pageTitle = $env{'form.page'};
1.103     albertel 4980:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4981:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4982:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4983:     if (!&canmodify($usec)) {
1.526     raeburn  4984: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4985: 	return;
                   4986:     }
1.398     albertel 4987:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4988:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4989: 	'</h3>'."\n";
1.70      ng       4990: 
1.68      ng       4991:     $request->print($result);
                   4992: 
1.582     raeburn  4993: 
1.132     bowersj2 4994:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4995:     unless (ref($navmap)) {
                   4996:         $request->print(&navmap_errormsg());
                   4997:         return;
                   4998:     }
1.257     albertel 4999:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5000:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5001:     if (!$map) {
1.527     raeburn  5002: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5003: 	return; 
                   5004:     }
1.71      ng       5005:     my $iterator = $navmap->getIterator($map->map_start(),
                   5006: 					$map->map_finish());
1.70      ng       5007: 
1.484     albertel 5008:     my $studentTable=
                   5009: 	&Apache::loncommon::start_data_table().
                   5010: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5011: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5012: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5013: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5014: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5015: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5016: 
                   5017:     $iterator->next(); # skip the first BEGIN_MAP
                   5018:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5019:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5020:     while ($depth > 0) {
1.71      ng       5021:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5022:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5023: 
1.385     albertel 5024:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5025: 	    my $parts = $curRes->parts();
1.71      ng       5026:             my $title = $curRes->compTitle();
                   5027: 	    my $symbx = $curRes->symb();
1.484     albertel 5028: 	    $studentTable.=
                   5029: 		&Apache::loncommon::start_data_table_row().
                   5030: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5031: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5032:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5033: 		.')').'</td>';
1.71      ng       5034: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5035: 
                   5036: 	    my %newrecord=();
                   5037: 	    my @displayPts=();
1.269     raeburn  5038:             my %aggregate = ();
                   5039:             my $aggregateflag = 0;
1.726     raeburn  5040:             if ($env{'form.HIDE'.$prob}) {
                   5041:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5042:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5043:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5044:                 $hideflag += $numchgs;
                   5045:             }
1.71      ng       5046: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5047: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5048: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5049: 
1.257     albertel 5050: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5051: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5052: 		my $partial = $newpts/$wgt;
                   5053: 		my $score;
                   5054: 		if ($partial > 0) {
                   5055: 		    $score = 'correct_by_override';
1.125     ng       5056: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5057: 		    $score = 'incorrect_by_override';
                   5058: 		}
1.257     albertel 5059: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5060: 		if ($dropMenu eq 'excused') {
1.71      ng       5061: 		    $partial = '';
                   5062: 		    $score = 'excused';
1.125     ng       5063: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5064: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5065: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5066: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5067: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5068: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5069: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5070: 		    $changeflag++;
                   5071: 		    $newpts = '';
1.269     raeburn  5072:                     
                   5073:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5074:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5075:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5076:                     if ($aggtries > 0) {
                   5077:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5078:                         $aggregateflag = 1;
                   5079:                     }
1.71      ng       5080: 		}
1.324     albertel 5081: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5082: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5083: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5084: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5085: 		    '&nbsp;<br />';
1.526     raeburn  5086: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5087: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5088: 		    '&nbsp;<br />';
1.71      ng       5089: 		$question++;
1.380     albertel 5090: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5091: 
1.71      ng       5092: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5093: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5094: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5095: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5096: 
                   5097: 		$changeflag++;
                   5098: 	    }
                   5099: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5100: 		my %record = 
                   5101: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5102: 					     $udom,$uname);
                   5103: 
                   5104: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5105: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5106: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5107: 		    $newrecord{'resource.CODE'} = '';
                   5108: 		}
1.257     albertel 5109: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5110: 					$udom,$uname);
1.382     albertel 5111: 		%record = &Apache::lonnet::restore($symbx,
                   5112: 						   $env{'request.course.id'},
                   5113: 						   $udom,$uname);
1.380     albertel 5114: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5115: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5116: 	    }
1.380     albertel 5117: 	    
1.269     raeburn  5118:             if ($aggregateflag) {
                   5119:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5120:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5121:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5122:             }
1.125     ng       5123: 
1.71      ng       5124: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5125: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5126: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5127: 
1.196     albertel 5128: 	    $prob++;
1.68      ng       5129: 	}
1.71      ng       5130:         $curRes = $iterator->next();
1.68      ng       5131:     }
1.98      albertel 5132: 
1.484     albertel 5133:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5134:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5135: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5136: 		  $changeflag).'<br />');
                   5137:     my $hidemsg=($hideflag == 0 ? '' :
                   5138:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5139:                      $hideflag).'<br />');
                   5140:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5141: 
1.70      ng       5142:     return '';
                   5143: }
                   5144: 
1.72      ng       5145: #-------- end of section for handling grading by page/sequence ---------
                   5146: #
                   5147: #-------------------------------------------------------------------
                   5148: 
1.581     www      5149: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5150: #
                   5151: #------ start of section for handling grading by page/sequence ---------
                   5152: 
1.423     albertel 5153: =pod
                   5154: 
                   5155: =head1 Bubble sheet grading routines
                   5156: 
1.424     albertel 5157:   For this documentation:
                   5158: 
                   5159:    'scanline' refers to the full line of characters
                   5160:    from the file that we are parsing that represents one entire sheet
                   5161: 
                   5162:    'bubble line' refers to the data
1.659     raeburn  5163:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5164: 
                   5165: 
1.659     raeburn  5166: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5167: into a course. When a user wants to grade, they select a
1.659     raeburn  5168: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5169: one of the predefined configurations for what each scanline looks
                   5170: like.
                   5171: 
                   5172: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5173: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5174: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5175: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5176: invalid student/employee ID
1.424     albertel 5177: 
                   5178: If the CODE option is used that determines the randomization of the
1.556     weissno  5179: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5180: username:domain.
                   5181: 
                   5182: During the validation phase the instructor can choose to skip scanlines. 
                   5183: 
1.659     raeburn  5184: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5185: 
                   5186:   scantron_original_filename (unmodified original file)
                   5187:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5188:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5189: 
                   5190: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5191: correction information that isn't representable in the bubblesheet
1.424     albertel 5192: file (see &scantron_getfile() for more information)
                   5193: 
                   5194: After all scanlines are either valid, marked as valid or skipped, then
                   5195: foreach line foreach problem in the picked sequence, an ssi request is
                   5196: made that simulates a user submitting their selected letter(s) against
                   5197: the homework problem.
1.423     albertel 5198: 
                   5199: =over 4
                   5200: 
                   5201: 
                   5202: 
                   5203: =item defaultFormData
                   5204: 
                   5205:   Returns html hidden inputs used to hold context/default values.
                   5206: 
                   5207:  Arguments:
                   5208:   $symb - $symb of the current resource 
                   5209: 
                   5210: =cut
1.422     foxr     5211: 
1.81      albertel 5212: sub defaultFormData {
1.324     albertel 5213:     my ($symb)=@_;
1.613     www      5214:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5215: }
                   5216: 
1.447     foxr     5217: 
1.423     albertel 5218: =pod 
                   5219: 
                   5220: =item getSequenceDropDown
                   5221: 
                   5222:    Return html dropdown of possible sequences to grade
                   5223:  
                   5224:  Arguments:
1.582     raeburn  5225:    $symb - $symb of the current resource
                   5226:    $map_error - ref to scalar which will container error if
                   5227:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5228: 
                   5229: =cut
1.422     foxr     5230: 
1.75      albertel 5231: sub getSequenceDropDown {
1.582     raeburn  5232:     my ($symb,$map_error)=@_;
1.75      albertel 5233:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5234:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5235:     if (ref($map_error)) {
                   5236:         return if ($$map_error);
                   5237:     }
1.137     albertel 5238:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5239:     my $ctr=0;
                   5240:     foreach (@$titles) {
                   5241: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5242: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5243: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5244: 	    '>'.$showtitle.'</option>'."\n";
                   5245: 	$ctr++;
                   5246:     }
                   5247:     $result.= '</select>';
                   5248:     return $result;
                   5249: }
                   5250: 
1.495     albertel 5251: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5252:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5253: 
                   5254: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5255: 
1.509     raeburn  5256: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5257:                                    # matchresponse or rankresponse, where 
                   5258:                                    # an individual response can have multiple 
                   5259:                                    # lines
1.503     raeburn  5260: 
                   5261: my %responsetype_per_response;     # responsetype for each response
                   5262: 
1.691     raeburn  5263: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5264:                                    # numbered response. Needed when randomorder
                   5265:                                    # or randompick are in use. Key is ID, value 
                   5266:                                    # is response number.
                   5267: 
1.495     albertel 5268: # Save and restore the bubble lines array to the form env.
                   5269: 
                   5270: 
                   5271: sub save_bubble_lines {
                   5272:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5273: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5274: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5275: 	    $first_bubble_line{$line};
1.503     raeburn  5276:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5277:             $subdivided_bubble_lines{$line};
                   5278:         $env{"form.scantron.responsetype.$line"} =
                   5279:             $responsetype_per_response{$line};
1.495     albertel 5280:     }
1.691     raeburn  5281:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5282:         my $line = $masterseq_id_responsenum{$resid};
                   5283:         $env{"form.scantron.residpart.$line"} = $resid;
                   5284:     }
1.495     albertel 5285: }
                   5286: 
                   5287: 
                   5288: sub restore_bubble_lines {
                   5289:     my $line = 0;
                   5290:     %bubble_lines_per_response = ();
1.691     raeburn  5291:     %masterseq_id_responsenum = ();
1.495     albertel 5292:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5293: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5294: 	$bubble_lines_per_response{$line} = $value;
                   5295: 	$first_bubble_line{$line}  =
                   5296: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5297:         $subdivided_bubble_lines{$line} =
                   5298:             $env{"form.scantron.sub_bubblelines.$line"};
                   5299:         $responsetype_per_response{$line} =
                   5300:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5301:         my $id = $env{"form.scantron.residpart.$line"};
                   5302:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5303: 	$line++;
                   5304:     }
                   5305: }
                   5306: 
1.423     albertel 5307: =pod 
                   5308: 
                   5309: =item scantron_filenames
                   5310: 
                   5311:    Returns a list of the scantron files in the current course 
                   5312: 
                   5313: =cut
1.422     foxr     5314: 
1.202     albertel 5315: sub scantron_filenames {
1.257     albertel 5316:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5317:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5318:     my $getpropath = 1;
1.662     raeburn  5319:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5320:                                                         $cname,$getpropath);
1.202     albertel 5321:     my @possiblenames;
1.662     raeburn  5322:     if (ref($dirlist) eq 'ARRAY') {
                   5323:         foreach my $filename (sort(@{$dirlist})) {
                   5324: 	    ($filename)=split(/&/,$filename);
                   5325: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5326: 	    $filename=~s/^scantron_orig_//;
                   5327: 	    push(@possiblenames,$filename);
                   5328:         }
1.202     albertel 5329:     }
                   5330:     return @possiblenames;
                   5331: }
                   5332: 
1.423     albertel 5333: =pod 
                   5334: 
                   5335: =item scantron_uploads
                   5336: 
                   5337:    Returns  html drop-down list of scantron files in current course.
                   5338: 
                   5339:  Arguments:
                   5340:    $file2grade - filename to set as selected in the dropdown
                   5341: 
                   5342: =cut
1.422     foxr     5343: 
1.202     albertel 5344: sub scantron_uploads {
1.209     ng       5345:     my ($file2grade) = @_;
1.202     albertel 5346:     my $result=	'<select name="scantron_selectfile">';
                   5347:     $result.="<option></option>";
                   5348:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5349: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5350:     }
                   5351:     $result.="</select>";
                   5352:     return $result;
                   5353: }
                   5354: 
1.423     albertel 5355: =pod 
                   5356: 
                   5357: =item scantron_scantab
                   5358: 
                   5359:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5360:   file.
                   5361: 
                   5362: =cut
1.422     foxr     5363: 
1.82      albertel 5364: sub scantron_scantab {
                   5365:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5366:     $result.='<option></option>'."\n";
1.518     raeburn  5367:     my @lines = &get_scantronformat_file();
                   5368:     if (@lines > 0) {
                   5369:         foreach my $line (@lines) {
                   5370:             next if (($line =~ /^\#/) || ($line eq ''));
                   5371: 	    my ($name,$descrip)=split(/:/,$line);
                   5372: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5373:         }
1.82      albertel 5374:     }
                   5375:     $result.='</select>'."\n";
1.518     raeburn  5376:     return $result;
                   5377: }
                   5378: 
                   5379: =pod
                   5380: 
                   5381: =item get_scantronformat_file
                   5382: 
                   5383:   Returns an array containing lines from the scantron format file for
                   5384:   the domain of the course.
                   5385: 
                   5386:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5387:   lines are from this file.
                   5388: 
                   5389:   Otherwise, if a default.tab has been published in RES space by the 
                   5390:   domainconfig user, lines are from this file.
                   5391: 
                   5392:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5393:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5394: 
1.518     raeburn  5395: =cut
                   5396: 
                   5397: sub get_scantronformat_file {
                   5398:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5399:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5400:     my $gottab = 0;
                   5401:     my @lines;
                   5402:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5403:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5404:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5405:             if ($formatfile ne '-1') {
                   5406:                 @lines = split("\n",$formatfile,-1);
                   5407:                 $gottab = 1;
                   5408:             }
                   5409:         }
                   5410:     }
                   5411:     if (!$gottab) {
                   5412:         my $confname = $cdom.'-domainconfig';
                   5413:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5414:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5415:         if ($formatfile ne '-1') {
                   5416:             @lines = split("\n",$formatfile,-1);
                   5417:             $gottab = 1;
                   5418:         }
                   5419:     }
                   5420:     if (!$gottab) {
1.519     raeburn  5421:         my @domains = &Apache::lonnet::current_machine_domains();
                   5422:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5423:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5424:             @lines = <$fh>;
                   5425:             close($fh);
                   5426:         } else {
                   5427:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5428:             @lines = <$fh>;
                   5429:             close($fh);
                   5430:         }
1.518     raeburn  5431:     }
                   5432:     return @lines;
1.82      albertel 5433: }
                   5434: 
1.423     albertel 5435: =pod 
                   5436: 
                   5437: =item scantron_CODElist
                   5438: 
                   5439:   Returns html drop down of the saved CODE lists from current course,
                   5440:   generated from earlier printings.
                   5441: 
                   5442: =cut
1.422     foxr     5443: 
1.186     albertel 5444: sub scantron_CODElist {
1.257     albertel 5445:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5446:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5447:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5448:     my $namechoice='<option></option>';
1.225     albertel 5449:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5450: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5451: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5452: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5453:     }
                   5454:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5455:     return $namechoice;
                   5456: }
                   5457: 
1.423     albertel 5458: =pod 
                   5459: 
                   5460: =item scantron_CODEunique
                   5461: 
                   5462:   Returns the html for "Each CODE to be used once" radio.
                   5463: 
                   5464: =cut
1.422     foxr     5465: 
1.186     albertel 5466: sub scantron_CODEunique {
1.532     bisitz   5467:     my $result='<span class="LC_nobreak">
1.272     albertel 5468:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5469:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5470:                 </span>
1.532     bisitz   5471:                 <span class="LC_nobreak">
1.272     albertel 5472:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5473:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5474:                 </span>';
1.186     albertel 5475:     return $result;
                   5476: }
1.423     albertel 5477: 
                   5478: =pod 
                   5479: 
                   5480: =item scantron_selectphase
                   5481: 
1.659     raeburn  5482:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5483:   Allows for - starting a grading run.
1.424     albertel 5484:              - downloading existing scan data (original, corrected
1.423     albertel 5485:                                                 or skipped info)
                   5486: 
                   5487:              - uploading new scan data
                   5488: 
                   5489:  Arguments:
                   5490:   $r          - The Apache request object
                   5491:   $file2grade - name of the file that contain the scanned data to score
                   5492: 
                   5493: =cut
1.186     albertel 5494: 
1.75      albertel 5495: sub scantron_selectphase {
1.608     www      5496:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5497:     if (!$symb) {return '';}
1.582     raeburn  5498:     my $map_error;
                   5499:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5500:     if ($map_error) {
                   5501:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5502:         return;
                   5503:     }
1.324     albertel 5504:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5505:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5506:     my $format_selector=&scantron_scantab();
1.186     albertel 5507:     my $CODE_selector=&scantron_CODElist();
                   5508:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5509:     my $result;
1.422     foxr     5510: 
1.513     foxr     5511:     $ssi_error = 0;
                   5512: 
1.606     wenzelju 5513:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5514:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5515: 
                   5516: 	# Chunk of form to prompt for a scantron file upload.
                   5517: 
                   5518:         $r->print('
                   5519:     <br />
                   5520:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5521:        '.&Apache::loncommon::start_data_table_header_row().'
                   5522:             <th>
                   5523:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5524:             </th>
                   5525:        '.&Apache::loncommon::end_data_table_header_row().'
                   5526:        '.&Apache::loncommon::start_data_table_row().'
                   5527:             <td>
                   5528: ');
1.608     www      5529:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5530:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5531:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5532:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5533:     &js_escape(\$alertmsg);
1.606     wenzelju 5534:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5535:     function checkUpload(formname) {
                   5536: 	if (formname.upfile.value == "") {
1.736     damieng  5537: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5538: 	    return false;
                   5539: 	}
                   5540: 	formname.submit();
                   5541:     }'));
                   5542:     $r->print('
                   5543:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5544:                 '.$default_form_data.'
                   5545:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5546:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5547:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5548:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5549:                 <br />
                   5550:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5551:               </form>
                   5552: ');
                   5553: 
                   5554:         $r->print('
                   5555:             </td>
                   5556:        '.&Apache::loncommon::end_data_table_row().'
                   5557:        '.&Apache::loncommon::end_data_table().'
                   5558: ');
                   5559:     }
                   5560: 
1.422     foxr     5561:     # Chunk of form to prompt for a file to grade and how:
                   5562: 
1.489     albertel 5563:     $result.= '
                   5564:     <br />
                   5565:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5566:     <input type="hidden" name="command" value="scantron_warning" />
                   5567:     '.$default_form_data.'
                   5568:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5569:        '.&Apache::loncommon::start_data_table_header_row().'
                   5570:             <th colspan="2">
1.492     albertel 5571:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5572:             </th>
                   5573:        '.&Apache::loncommon::end_data_table_header_row().'
                   5574:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5575:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5576:        '.&Apache::loncommon::end_data_table_row().'
                   5577:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5578:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5579:        '.&Apache::loncommon::end_data_table_row().'
                   5580:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5581:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5582:        '.&Apache::loncommon::end_data_table_row().'
                   5583:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5584:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5585:        '.&Apache::loncommon::end_data_table_row().'
                   5586:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5587:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5588:        '.&Apache::loncommon::end_data_table_row().'
                   5589:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5590: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5591:             <td>
1.492     albertel 5592: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5593:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5594:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5595: 	    </td>
1.489     albertel 5596:        '.&Apache::loncommon::end_data_table_row().'
                   5597:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5598:             <td colspan="2">
1.572     www      5599:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5600:             </td>
1.489     albertel 5601:        '.&Apache::loncommon::end_data_table_row().'
                   5602:     '.&Apache::loncommon::end_data_table().'
                   5603:     </form>
                   5604: ';
1.162     albertel 5605:    
                   5606:     $r->print($result);
                   5607: 
1.422     foxr     5608: 
                   5609: 
                   5610:     # Chunk of the form that prompts to view a scoring office file,
                   5611:     # corrected file, skipped records in a file.
                   5612: 
1.489     albertel 5613:     $r->print('
                   5614:    <br />
                   5615:    <form action="/adm/grades" name="scantron_download">
                   5616:      '.$default_form_data.'
                   5617:      <input type="hidden" name="command" value="scantron_download" />
                   5618:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5619:        '.&Apache::loncommon::start_data_table_header_row().'
                   5620:               <th>
1.492     albertel 5621:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5622:               </th>
                   5623:        '.&Apache::loncommon::end_data_table_header_row().'
                   5624:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5625:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5626:                 <br />
1.492     albertel 5627:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5628:        '.&Apache::loncommon::end_data_table_row().'
                   5629:      '.&Apache::loncommon::end_data_table().'
                   5630:    </form>
                   5631:    <br />
                   5632: ');
1.162     albertel 5633: 
1.457     banghart 5634:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5635: 
1.694     bisitz   5636:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5637:              $default_form_data."\n".
                   5638:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5639:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5640:              '<th colspan="2">
1.572     www      5641:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5642:              '</th>'."\n".
                   5643:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5644:               &Apache::loncommon::start_data_table_row()."\n".
                   5645:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5646:               '<td> '.$sequence_selector.' </td>'.
                   5647:               &Apache::loncommon::end_data_table_row()."\n".
                   5648:               &Apache::loncommon::start_data_table_row()."\n".
                   5649:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5650:               '<td> '.$file_selector.' </td>'."\n".
                   5651:               &Apache::loncommon::end_data_table_row()."\n".
                   5652:               &Apache::loncommon::start_data_table_row()."\n".
                   5653:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5654:               '<td> '.$format_selector.' </td>'."\n".
                   5655:               &Apache::loncommon::end_data_table_row()."\n".
                   5656:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5657:               '<td> '.&mt('Options').' </td>'."\n".
                   5658:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5659:               &Apache::loncommon::end_data_table_row()."\n".
                   5660:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5661:               '<td colspan="2">'."\n".
                   5662:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5663:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5664:               '</td>'."\n".
                   5665:               &Apache::loncommon::end_data_table_row()."\n".
                   5666:               &Apache::loncommon::end_data_table()."\n".
                   5667:               '</form><br />');
                   5668:     return;
1.75      albertel 5669: }
                   5670: 
1.423     albertel 5671: =pod
                   5672: 
                   5673: =item get_scantron_config
                   5674: 
1.711     bisitz   5675:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5676:    hash of configuration file fields.
                   5677: 
                   5678:  Arguments:
                   5679:     which - the name of the configuration to parse from the file.
                   5680: 
                   5681: 
                   5682:  Returns:
                   5683:             If the named configuration is not in the file, an empty
                   5684:             hash is returned.
                   5685:     a hash with the fields
                   5686:       name         - internal name for the this configuration setup
                   5687:       description  - text to display to operator that describes this config
                   5688:       CODElocation - if 0 or the string 'none'
                   5689:                           - no CODE exists for this config
                   5690:                      if -1 || the string 'letter'
                   5691:                           - a CODE exists for this config and is
                   5692:                             a string of letters
                   5693:                      Unsupported value (but planned for future support)
                   5694:                           if a positive integer
                   5695:                                - The CODE exists as the first n items from
                   5696:                                  the question section of the form
                   5697:                           if the string 'number'
                   5698:                                - The CODE exists for this config and is
                   5699:                                  a string of numbers
                   5700:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5701:                      the CODE starts
                   5702:       CODElength  - length of the CODE
1.573     bisitz   5703:       IDstart     - column where the student/employee ID starts
1.556     weissno  5704:       IDlength    - length of the student/employee ID info
1.423     albertel 5705:       Qstart      - column where the information from the bubbled
                   5706:                     'questions' start
                   5707:       Qlength     - number of columns comprising a single bubble line from
                   5708:                     the sheet. (usually either 1 or 10)
1.424     albertel 5709:       Qon         - either a single character representing the character used
1.423     albertel 5710:                     to signal a bubble was chosen in the positional setup, or
                   5711:                     the string 'letter' if the letter of the chosen bubble is
                   5712:                     in the final, or 'number' if a number representing the
                   5713:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5714:       Qoff        - the character used to represent that a bubble was
                   5715:                     left blank
1.423     albertel 5716:       PaperID     - if the scanning process generates a unique number for each
                   5717:                     sheet scanned the column that this ID number starts in
                   5718:       PaperIDlength - number of columns that comprise the unique ID number
                   5719:                       for the sheet of paper
1.424     albertel 5720:       FirstName   - column that the first name starts in
1.423     albertel 5721:       FirstNameLength - number of columns that the first name spans
                   5722:  
                   5723:       LastName    - column that the last name starts in
                   5724:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5725:       BubblesPerRow - number of bubbles available in each row used to 
                   5726:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5727: 
1.423     albertel 5728: =cut
1.422     foxr     5729: 
1.82      albertel 5730: sub get_scantron_config {
                   5731:     my ($which) = @_;
1.518     raeburn  5732:     my @lines = &get_scantronformat_file();
1.82      albertel 5733:     my %config;
1.157     albertel 5734:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5735:     foreach my $line (@lines) {
1.82      albertel 5736: 	my ($name,$descrip)=split(/:/,$line);
                   5737: 	if ($name ne $which ) { next; }
                   5738: 	chomp($line);
                   5739: 	my @config=split(/:/,$line);
                   5740: 	$config{'name'}=$config[0];
                   5741: 	$config{'description'}=$config[1];
                   5742: 	$config{'CODElocation'}=$config[2];
                   5743: 	$config{'CODEstart'}=$config[3];
                   5744: 	$config{'CODElength'}=$config[4];
                   5745: 	$config{'IDstart'}=$config[5];
                   5746: 	$config{'IDlength'}=$config[6];
                   5747: 	$config{'Qstart'}=$config[7];
1.497     foxr     5748:  	$config{'Qlength'}=$config[8];
1.82      albertel 5749: 	$config{'Qoff'}=$config[9];
                   5750: 	$config{'Qon'}=$config[10];
1.157     albertel 5751: 	$config{'PaperID'}=$config[11];
                   5752: 	$config{'PaperIDlength'}=$config[12];
                   5753: 	$config{'FirstName'}=$config[13];
                   5754: 	$config{'FirstNamelength'}=$config[14];
                   5755: 	$config{'LastName'}=$config[15];
                   5756: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5757:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5758: 	last;
                   5759:     }
                   5760:     return %config;
                   5761: }
                   5762: 
1.423     albertel 5763: =pod 
                   5764: 
                   5765: =item username_to_idmap
                   5766: 
1.556     weissno  5767:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  5768:     student username:domain. If a single ID occurs for more than one student,
                   5769:     the status of the student is checked, and if Active, the value in the hash
                   5770:     will be set to the Active student.
1.423     albertel 5771: 
                   5772:   Arguments:
                   5773: 
                   5774:     $classlist - reference to the class list hash. This is a hash
                   5775:                  keyed by student name:domain  whose elements are references
1.424     albertel 5776:                  to arrays containing various chunks of information
1.423     albertel 5777:                  about the student. (See loncoursedata for more info).
                   5778: 
                   5779:   Returns
                   5780:     %idmap - the constructed hash
                   5781: 
                   5782: =cut
                   5783: 
1.82      albertel 5784: sub username_to_idmap {
                   5785:     my ($classlist)= @_;
                   5786:     my %idmap;
                   5787:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  5788:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   5789:         unless ($id eq '') {
                   5790:             if (!exists($idmap{$id})) {
                   5791:                 $idmap{$id} = $student;
                   5792:             } else {
                   5793:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   5794:                 if ($status eq 'Active') {
                   5795:                     $idmap{$id} = $student;
                   5796:                 }
                   5797:             }
                   5798:         }
1.82      albertel 5799:     }
                   5800:     return %idmap;
                   5801: }
1.423     albertel 5802: 
                   5803: =pod
                   5804: 
1.424     albertel 5805: =item scantron_fixup_scanline
1.423     albertel 5806: 
                   5807:    Process a requested correction to a scanline.
                   5808: 
                   5809:   Arguments:
                   5810:     $scantron_config   - hash from &get_scantron_config()
                   5811:     $scan_data         - hash of correction information 
                   5812:                           (see &scantron_getfile())
                   5813:     $line              - existing scanline
                   5814:     $whichline         - line number of the passed in scanline
                   5815:     $field             - type of change to process 
                   5816:                          (either 
1.573     bisitz   5817:                           'ID'     -> correct the student/employee ID
1.423     albertel 5818:                           'CODE'   -> correct the CODE
                   5819:                           'answer' -> fixup the submitted answers)
                   5820:     
                   5821:    $args               - hash of additional info,
                   5822:                           - 'ID' 
                   5823:                                'newid' -> studentID to use in replacement
1.424     albertel 5824:                                           of existing one
1.423     albertel 5825:                           - 'CODE' 
                   5826:                                'CODE_ignore_dup' - set to true if duplicates
                   5827:                                                    should be ignored.
                   5828: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5829:                                         if the existing unfound code should
1.423     albertel 5830:                                         be used as is
                   5831:                           - 'answer'
                   5832:                                'response' - new answer or 'none' if blank
                   5833:                                'question' - the bubble line to change
1.503     raeburn  5834:                                'questionnum' - the question identifier,
                   5835:                                                may include subquestion. 
1.423     albertel 5836: 
                   5837:   Returns:
                   5838:     $line - the modified scanline
                   5839: 
                   5840:   Side effects: 
                   5841:     $scan_data - may be updated
                   5842: 
                   5843: =cut
                   5844: 
1.82      albertel 5845: 
1.157     albertel 5846: sub scantron_fixup_scanline {
                   5847:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5848:     if ($field eq 'ID') {
                   5849: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5850: 	    return ($line,1,'New value too large');
1.157     albertel 5851: 	}
                   5852: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5853: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5854: 				     $args->{'newid'});
                   5855: 	}
                   5856: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5857: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5858: 	if ($args->{'newid'}=~/^\s*$/) {
                   5859: 	    &scan_data($scan_data,"$whichline.user",
                   5860: 		       $args->{'username'}.':'.$args->{'domain'});
                   5861: 	}
1.186     albertel 5862:     } elsif ($field eq 'CODE') {
1.192     albertel 5863: 	if ($args->{'CODE_ignore_dup'}) {
                   5864: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5865: 	}
                   5866: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5867: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5868: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5869: 		return ($line,1,'New CODE value too large');
                   5870: 	    }
                   5871: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5872: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5873: 	    }
                   5874: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5875: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5876: 	}
1.157     albertel 5877:     } elsif ($field eq 'answer') {
1.497     foxr     5878: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5879: 	my $off=$scantron_config->{'Qoff'};
                   5880: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5881: 	my $answer=${off}x$length;
                   5882: 	if ($args->{'response'} eq 'none') {
                   5883: 	    &scan_data($scan_data,
1.503     raeburn  5884: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5885: 	} else {
                   5886: 	    if ($on eq 'letter') {
                   5887: 		my @alphabet=('A'..'Z');
                   5888: 		$answer=$alphabet[$args->{'response'}];
                   5889: 	    } elsif ($on eq 'number') {
                   5890: 		$answer=$args->{'response'}+1;
                   5891: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5892: 	    } else {
1.497     foxr     5893: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5894: 	    }
1.497     foxr     5895: 	    &scan_data($scan_data,
1.503     raeburn  5896: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5897: 	}
1.497     foxr     5898: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5899: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5900:     }
                   5901:     return $line;
                   5902: }
1.423     albertel 5903: 
                   5904: =pod
                   5905: 
                   5906: =item scan_data
                   5907: 
                   5908:     Edit or look up  an item in the scan_data hash.
                   5909: 
                   5910:   Arguments:
                   5911:     $scan_data  - The hash (see scantron_getfile)
                   5912:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5913:                   scantronfilename_key).
1.423     albertel 5914:     $data        - New value of the hash entry.
                   5915:     $delete      - If true, the entry is removed from the hash.
                   5916: 
                   5917:   Returns:
                   5918:     The new value of the hash table field (undefined if deleted).
                   5919: 
                   5920: =cut
                   5921: 
                   5922: 
1.157     albertel 5923: sub scan_data {
                   5924:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5925:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5926:     if (defined($value)) {
                   5927: 	$scan_data->{$filename.'_'.$key} = $value;
                   5928:     }
                   5929:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5930:     return $scan_data->{$filename.'_'.$key};
                   5931: }
1.423     albertel 5932: 
1.495     albertel 5933: # ----- These first few routines are general use routines.----
                   5934: 
                   5935: # Return the number of occurences of a pattern in a string.
                   5936: 
                   5937: sub occurence_count {
                   5938:     my ($string, $pattern) = @_;
                   5939: 
                   5940:     my @matches = ($string =~ /$pattern/g);
                   5941: 
                   5942:     return scalar(@matches);
                   5943: }
                   5944: 
                   5945: 
                   5946: # Take a string known to have digits and convert all the
                   5947: # digits into letters in the range J,A..I.
                   5948: 
                   5949: sub digits_to_letters {
                   5950:     my ($input) = @_;
                   5951: 
                   5952:     my @alphabet = ('J', 'A'..'I');
                   5953: 
                   5954:     my @input    = split(//, $input);
                   5955:     my $output ='';
                   5956:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5957: 	if ($input[$i] =~ /\d/) {
                   5958: 	    $output .= $alphabet[$input[$i]];
                   5959: 	} else {
                   5960: 	    $output .= $input[$i];
                   5961: 	}
                   5962:     }
                   5963:     return $output;
                   5964: }
                   5965: 
1.423     albertel 5966: =pod 
                   5967: 
                   5968: =item scantron_parse_scanline
                   5969: 
1.711     bisitz   5970:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5971: 
                   5972:  Arguments:
1.711     bisitz   5973:     line             - The text of the bubblesheet file line to process
1.423     albertel 5974:     whichline        - Line number
1.711     bisitz   5975:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5976:     scan_data        - Hash of extra information about the scanline
                   5977:                        (see scantron_getfile for more information)
                   5978:     just_header      - True if should not process question answers but only
                   5979:                        the stuff to the left of the answers.
1.691     raeburn  5980:     randomorder      - True if randomorder in use
                   5981:     randompick       - True if randompick in use
                   5982:     sequence         - Exam folder URL
                   5983:     master_seq       - Ref to array containing symbs in exam folder
                   5984:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5985:                        (corresponding values are resource objects)
                   5986:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5987:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5988:                        are refs to an array of resource objects, ordered
                   5989:                        according to order used for CODE, when randomorder
                   5990:                        and or randompick are in use.
                   5991:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5992:                        for current line to question number used for same question
                   5993:                         in "Master Sequence" (as seen by Course Coordinator).
                   5994:     startline        - Ref to hash where key is question number (0 is first)
                   5995:                        and value is number of first bubble line for current 
                   5996:                        student or code-based randompick and/or randomorder.
                   5997:     totalref         - Ref of scalar used to score total number of bubble
                   5998:                        lines needed for responses in a scan line (used when
                   5999:                        randompick in use. 
                   6000:     
1.423     albertel 6001:  Returns:
                   6002:    Hash containing the result of parsing the scanline
                   6003: 
                   6004:    Keys are all proceeded by the string 'scantron.'
                   6005: 
                   6006:        CODE    - the CODE in use for this scanline
                   6007:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6008:                  by the operator
                   6009:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6010:                             CODEs were selected, but the usage has been
                   6011:                             forced by the operator
1.556     weissno  6012:        ID  - student/employee ID
1.423     albertel 6013:        PaperID - if used, the ID number printed on the sheet when the 
                   6014:                  paper was scanned
                   6015:        FirstName - first name from the sheet
                   6016:        LastName  - last name from the sheet
                   6017: 
                   6018:      if just_header was not true these key may also exist
                   6019: 
1.447     foxr     6020:        missingerror - a list of bubble ranges that are considered to be answers
                   6021:                       to a single question that don't have any bubbles filled in.
                   6022:                       Of the form questionnumber:firstbubblenumber:count.
                   6023:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6024:                       to a single question that have more than one bubble filled in.
                   6025:                       Of the form questionnumber::firstbubblenumber:count
                   6026:    
                   6027:                 In the above, count is the number of bubble responses in the
                   6028:                 input line needed to represent the possible answers to the question.
                   6029:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6030:                 per line would have count = 2.
                   6031: 
1.423     albertel 6032:        maxquest     - the number of the last bubble line that was parsed
                   6033: 
                   6034:        (<number> starts at 1)
                   6035:        <number>.answer - zero or more letters representing the selected
                   6036:                          letters from the scanline for the bubble line 
                   6037:                          <number>.
                   6038:                          if blank there was either no bubble or there where
                   6039:                          multiple bubbles, (consult the keys missingerror and
                   6040:                          doubleerror if this is an error condition)
                   6041: 
                   6042: =cut
                   6043: 
1.82      albertel 6044: sub scantron_parse_scanline {
1.691     raeburn  6045:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6046:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6047:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6048: 
1.82      albertel 6049:     my %record;
1.691     raeburn  6050:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6051:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6052: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6053: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6054: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6055: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6056: 	    $record{'scantron.CODE'}=substr($data,
                   6057: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6058: 					    $$scantron_config{'CODElength'});
1.191     albertel 6059: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6060: 		$record{'scantron.useCODE'}=1;
                   6061: 	    }
1.192     albertel 6062: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6063: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6064: 	    }
1.82      albertel 6065: 	} else {
                   6066: 	    #FIXME interpret first N questions
                   6067: 	}
                   6068:     }
1.83      albertel 6069:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6070: 				  $$scantron_config{'IDlength'});
1.157     albertel 6071:     $record{'scantron.PaperID'}=
                   6072: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6073: 	       $$scantron_config{'PaperIDlength'});
                   6074:     $record{'scantron.FirstName'}=
                   6075: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6076: 	       $$scantron_config{'FirstNamelength'});
                   6077:     $record{'scantron.LastName'}=
                   6078: 	substr($data,$$scantron_config{'LastName'}-1,
                   6079: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6080:     if ($just_header) { return \%record; }
1.194     albertel 6081: 
1.82      albertel 6082:     my @alphabet=('A'..'Z');
                   6083:     my $questnum=0;
1.447     foxr     6084:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6085: 
1.691     raeburn  6086:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6087:     if ($randompick || $randomorder) {
                   6088:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6089:                                          $master_seq,$symb_to_resource,
                   6090:                                          $partids_by_symb,$orderedforcode,
                   6091:                                          $respnumlookup,$startline);
                   6092:         if ($total) {
                   6093:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6094:         }
                   6095:         if (ref($totalref)) {
                   6096:             $$totalref = $total;
                   6097:         }
                   6098:     }
                   6099:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6100:     chomp($questions);		# Get rid of any trailing \n.
                   6101:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6102:     while (length($questions)) {
1.691     raeburn  6103:         my $answers_needed;
                   6104:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6105:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6106:         } else {
                   6107: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6108:         }
1.503     raeburn  6109:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6110:                              || 1;
                   6111:         $questnum++;
                   6112:         my $quest_id = $questnum;
                   6113:         my $currentquest = substr($questions,0,$answer_length);
                   6114:         $questions       = substr($questions,$answer_length);
                   6115:         if (length($currentquest) < $answer_length) { next; }
                   6116: 
1.691     raeburn  6117:         my $subdivided;
                   6118:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6119:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6120:         } else {
                   6121:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6122:         }
                   6123:         if ($subdivided =~ /,/) {
1.503     raeburn  6124:             my $subquestnum = 1;
                   6125:             my $subquestions = $currentquest;
1.691     raeburn  6126:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6127:             foreach my $subans (@subanswers_needed) {
                   6128:                 my $subans_length =
                   6129:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6130:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6131:                 $subquestions   = substr($subquestions,$subans_length);
                   6132:                 $quest_id = "$questnum.$subquestnum";
                   6133:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6134:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6135:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6136:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6137:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6138:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6139:                 } else {
                   6140:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6141:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6142:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6143:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6144:                 }
                   6145:                 $subquestnum ++;
                   6146:             }
                   6147:         } else {
                   6148:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6149:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6150:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6151:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6152:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6153:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6154:             } else {
                   6155:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6156:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6157:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6158:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6159:             }
                   6160:         }
                   6161:     }
                   6162:     $record{'scantron.maxquest'}=$questnum;
                   6163:     return \%record;
                   6164: }
1.447     foxr     6165: 
1.691     raeburn  6166: sub get_master_seq {
                   6167:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6168:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6169:                    (ref($symb_to_resource) eq 'HASH'));
                   6170:     my $resource_error;
                   6171:     foreach my $resource (@{$resources}) {
                   6172:         my $ressymb;
                   6173:         if (ref($resource)) {
                   6174:             $ressymb = $resource->symb();
                   6175:             push(@{$master_seq},$ressymb);
                   6176:             $symb_to_resource->{$ressymb} = $resource;
                   6177:         } else {
                   6178:             $resource_error = 1;
                   6179:             last;
                   6180:         }
                   6181:     }
                   6182:     return $resource_error;
                   6183: }
                   6184: 
                   6185: sub get_respnum_lookups {
                   6186:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6187:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6188:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6189:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6190:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6191:                    (ref($startline) eq 'HASH'));
                   6192:     my ($user,$scancode);
                   6193:     if ((exists($record->{'scantron.CODE'})) &&
                   6194:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6195:         $scancode = $record->{'scantron.CODE'};
                   6196:     } else {
                   6197:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6198:     }
                   6199:     my @mapresources =
                   6200:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6201:                      $orderedforcode);
                   6202:     my $total = 0;
                   6203:     my $count = 0;
                   6204:     foreach my $resource (@mapresources) {
                   6205:         my $id = $resource->id();
                   6206:         my $symb = $resource->symb();
                   6207:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6208:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6209:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6210:                 if ($respnum ne '') {
                   6211:                     $respnumlookup->{$count} = $respnum;
                   6212:                     $startline->{$count} = $total;
                   6213:                     $total += $bubble_lines_per_response{$respnum};
                   6214:                     $count ++;
                   6215:                 }
                   6216:             }
                   6217:         }
                   6218:     }
                   6219:     return $total;
                   6220: }
                   6221: 
1.503     raeburn  6222: sub scantron_validator_lettnum {
                   6223:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6224:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6225:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6226: 
                   6227:     # Qon 'letter' implies for each slot in currquest we have:
                   6228:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6229:     #    about anything else (esp. a value of Qoff) for missing
                   6230:     #    bubbles.
                   6231:     #
                   6232:     # Qon 'number' implies each slot gives a digit that indexes the
                   6233:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6234:     #    and * or ? for double bubbles on a single line.
                   6235:     #
1.447     foxr     6236: 
1.503     raeburn  6237:     my $matchon;
                   6238:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6239:         $matchon = '[A-Z]';
                   6240:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6241:         $matchon = '\d';
                   6242:     }
                   6243:     my $occurrences = 0;
1.691     raeburn  6244:     my $responsenum = $questnum-1;
                   6245:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6246:        $responsenum = $respnumlookup->{$questnum-1} 
                   6247:     }
                   6248:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6249:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6250:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6251:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6252:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6253:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6254:         my @singlelines = split('',$currquest);
                   6255:         foreach my $entry (@singlelines) {
                   6256:             $occurrences = &occurence_count($entry,$matchon);
                   6257:             if ($occurrences > 1) {
                   6258:                 last;
                   6259:             }
1.691     raeburn  6260:         }
1.503     raeburn  6261:     } else {
                   6262:         $occurrences = &occurence_count($currquest,$matchon); 
                   6263:     }
                   6264:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6265:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6266:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6267:             my $bubble = substr($currquest,$ans,1);
                   6268:             if ($bubble =~ /$matchon/ ) {
                   6269:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6270:                     if ($bubble == 0) {
                   6271:                         $bubble = 10; 
                   6272:                     }
                   6273:                     $record->{"scantron.$ansnum.answer"} = 
                   6274:                         $alphabet->[$bubble-1];
                   6275:                 } else {
                   6276:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6277:                 }
                   6278:             } else {
                   6279:                 $record->{"scantron.$ansnum.answer"}='';
                   6280:             }
                   6281:             $ansnum++;
                   6282:         }
                   6283:     } elsif (!defined($currquest)
                   6284:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6285:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6286:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6287:             $record->{"scantron.$ansnum.answer"}='';
                   6288:             $ansnum++;
                   6289:         }
                   6290:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6291:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6292:         }
                   6293:     } else {
                   6294:         if ($$scantron_config{'Qon'} eq 'number') {
                   6295:             $currquest = &digits_to_letters($currquest);            
                   6296:         }
                   6297:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6298:             my $bubble = substr($currquest,$ans,1);
                   6299:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6300:             $ansnum++;
                   6301:         }
                   6302:     }
                   6303:     return $ansnum;
                   6304: }
1.447     foxr     6305: 
1.503     raeburn  6306: sub scantron_validator_positional {
                   6307:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6308:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6309:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6310: 
1.503     raeburn  6311:     # Otherwise there's a positional notation;
                   6312:     # each bubble line requires Qlength items, and there are filled in
                   6313:     # bubbles for each case where there 'Qon' characters.
                   6314:     #
1.447     foxr     6315: 
1.503     raeburn  6316:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6317: 
1.503     raeburn  6318:     # If the split only gives us one element.. the full length of the
                   6319:     # answer string, no bubbles are filled in:
1.447     foxr     6320: 
1.507     raeburn  6321:     if ($answers_needed eq '') {
                   6322:         return;
                   6323:     }
                   6324: 
1.503     raeburn  6325:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6326:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6327:             $record->{"scantron.$ansnum.answer"}='';
                   6328:             $ansnum++;
                   6329:         }
                   6330:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6331:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6332:         }
                   6333:     } elsif (scalar(@array) == 2) {
                   6334:         my $location = length($array[0]);
                   6335:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6336:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6337:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6338:             if ($ans eq $line_num) {
                   6339:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6340:             } else {
                   6341:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6342:             }
                   6343:             $ansnum++;
                   6344:          }
                   6345:     } else {
                   6346:         #  If there's more than one instance of a bubble character
                   6347:         #  That's a double bubble; with positional notation we can
                   6348:         #  record all the bubbles filled in as well as the
                   6349:         #  fact this response consists of multiple bubbles.
                   6350:         #
1.691     raeburn  6351:         my $responsenum = $questnum-1;
                   6352:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6353:             $responsenum = $respnumlookup->{$questnum-1}
                   6354:         }
                   6355:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6356:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6357:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6358:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6359:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6360:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6361:             my $doubleerror = 0;
                   6362:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6363:                    (!$doubleerror)) {
                   6364:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6365:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6366:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6367:                if (length(@currarray) > 2) {
                   6368:                    $doubleerror = 1;
                   6369:                } 
                   6370:             }
                   6371:             if ($doubleerror) {
                   6372:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6373:             }
                   6374:         } else {
                   6375:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6376:         }
                   6377:         my $item = $ansnum;
                   6378:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6379:             $record->{"scantron.$item.answer"} = '';
                   6380:             $item ++;
                   6381:         }
1.447     foxr     6382: 
1.503     raeburn  6383:         my @ans=@array;
                   6384:         my $i=0;
                   6385:         my $increment = 0;
                   6386:         while ($#ans) {
                   6387:             $i+=length($ans[0]) + $increment;
                   6388:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6389:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6390:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6391:             shift(@ans);
                   6392:             $increment = 1;
                   6393:         }
                   6394:         $ansnum += $answers_needed;
1.82      albertel 6395:     }
1.503     raeburn  6396:     return $ansnum;
1.82      albertel 6397: }
                   6398: 
1.423     albertel 6399: =pod
                   6400: 
                   6401: =item scantron_add_delay
                   6402: 
                   6403:    Adds an error message that occurred during the grading phase to a
                   6404:    queue of messages to be shown after grading pass is complete
                   6405: 
                   6406:  Arguments:
1.424     albertel 6407:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6408:    $scanline    - the scanline that caused the error
                   6409:    $errormesage - the error message
                   6410:    $errorcode   - a numeric code for the error
                   6411: 
                   6412:  Side Effects:
1.424     albertel 6413:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6414: 
                   6415: =cut
                   6416: 
1.82      albertel 6417: sub scantron_add_delay {
1.140     albertel 6418:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6419:     push(@$delayqueue,
                   6420: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6421: 	  'ecode' => $errorcode }
                   6422: 	 );
1.82      albertel 6423: }
                   6424: 
1.423     albertel 6425: =pod
                   6426: 
                   6427: =item scantron_find_student
                   6428: 
1.424     albertel 6429:    Finds the username for the current scanline
                   6430: 
                   6431:   Arguments:
                   6432:    $scantron_record - hash result from scantron_parse_scanline
                   6433:    $scan_data       - hash of correction information 
                   6434:                       (see &scantron_getfile() form more information)
                   6435:    $idmap           - hash from &username_to_idmap()
                   6436:    $line            - number of current scanline
                   6437:  
                   6438:   Returns:
                   6439:    Either 'username:domain' or undef if unknown
                   6440: 
1.423     albertel 6441: =cut
                   6442: 
1.82      albertel 6443: sub scantron_find_student {
1.157     albertel 6444:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6445:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6446:     if ($scanID =~ /^\s*$/) {
                   6447:  	return &scan_data($scan_data,"$line.user");
                   6448:     }
1.83      albertel 6449:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6450:  	if (lc($id) eq lc($scanID)) {
                   6451:  	    return $$idmap{$id};
                   6452:  	}
1.83      albertel 6453:     }
                   6454:     return undef;
                   6455: }
                   6456: 
1.423     albertel 6457: =pod
                   6458: 
                   6459: =item scantron_filter
                   6460: 
1.424     albertel 6461:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6462:    hidden resources was selected
                   6463: 
1.423     albertel 6464: =cut
                   6465: 
1.83      albertel 6466: sub scantron_filter {
                   6467:     my ($curres)=@_;
1.331     albertel 6468: 
                   6469:     if (ref($curres) && $curres->is_problem()) {
                   6470: 	# if the user has asked to not have either hidden
                   6471: 	# or 'randomout' controlled resources to be graded
                   6472: 	# don't include them
                   6473: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6474: 	    && $curres->randomout) {
                   6475: 	    return 0;
                   6476: 	}
1.83      albertel 6477: 	return 1;
                   6478:     }
                   6479:     return 0;
1.82      albertel 6480: }
                   6481: 
1.423     albertel 6482: =pod
                   6483: 
                   6484: =item scantron_process_corrections
                   6485: 
1.424     albertel 6486:    Gets correction information out of submitted form data and corrects
                   6487:    the scanline
                   6488: 
1.423     albertel 6489: =cut
                   6490: 
1.157     albertel 6491: sub scantron_process_corrections {
                   6492:     my ($r) = @_;
1.257     albertel 6493:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6494:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6495:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6496:     my $which=$env{'form.scantron_line'};
1.200     albertel 6497:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6498:     my ($skip,$err,$errmsg);
1.257     albertel 6499:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6500: 	$skip=1;
1.257     albertel 6501:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6502: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6503: 	    $env{'form.scantron_domain'};
1.157     albertel 6504: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6505: 	($line,$err,$errmsg)=
                   6506: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6507: 				     'ID',{'newid'=>$newid,
1.257     albertel 6508: 				    'username'=>$env{'form.scantron_username'},
                   6509: 				    'domain'=>$env{'form.scantron_domain'}});
                   6510:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6511: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6512: 	my $newCODE;
1.192     albertel 6513: 	my %args;
1.190     albertel 6514: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6515: 	    $newCODE='use_unfound';
1.190     albertel 6516: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6517: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6518: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6519: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6520: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6521: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6522: 	}
1.257     albertel 6523: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6524: 	    $args{'CODE_ignore_dup'}=1;
                   6525: 	}
                   6526: 	$args{'CODE'}=$newCODE;
1.186     albertel 6527: 	($line,$err,$errmsg)=
                   6528: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6529: 				     'CODE',\%args);
1.257     albertel 6530:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6531: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6532: 	    ($line,$err,$errmsg)=
                   6533: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6534: 					 $which,'answer',
                   6535: 					 { 'question'=>$question,
1.503     raeburn  6536: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6537:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6538: 	    if ($err) { last; }
                   6539: 	}
                   6540:     }
                   6541:     if ($err) {
1.703     bisitz   6542:         $r->print(
                   6543:             '<p class="LC_error">'
                   6544:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6545:                 $errmsg)
1.704     raeburn  6546:            .'</p>');
1.157     albertel 6547:     } else {
1.200     albertel 6548: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6549: 	&scantron_putfile($scanlines,$scan_data);
                   6550:     }
                   6551: }
                   6552: 
1.423     albertel 6553: =pod
                   6554: 
                   6555: =item reset_skipping_status
                   6556: 
1.424     albertel 6557:    Forgets the current set of remember skipped scanlines (and thus
                   6558:    reverts back to considering all lines in the
                   6559:    scantron_skipped_<filename> file)
                   6560: 
1.423     albertel 6561: =cut
                   6562: 
1.200     albertel 6563: sub reset_skipping_status {
                   6564:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6565:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6566:     &scantron_putfile(undef,$scan_data);
                   6567: }
                   6568: 
1.423     albertel 6569: =pod
                   6570: 
                   6571: =item start_skipping
                   6572: 
1.424     albertel 6573:    Marks a scanline to be skipped. 
                   6574: 
1.423     albertel 6575: =cut
                   6576: 
1.376     albertel 6577: sub start_skipping {
1.200     albertel 6578:     my ($scan_data,$i)=@_;
                   6579:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6580:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6581: 	$remembered{$i}=2;
                   6582:     } else {
                   6583: 	$remembered{$i}=1;
                   6584:     }
1.200     albertel 6585:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6586: }
                   6587: 
1.423     albertel 6588: =pod
                   6589: 
                   6590: =item should_be_skipped
                   6591: 
1.424     albertel 6592:    Checks whether a scanline should be skipped.
                   6593: 
1.423     albertel 6594: =cut
                   6595: 
1.200     albertel 6596: sub should_be_skipped {
1.376     albertel 6597:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6598:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6599: 	# not redoing old skips
1.376     albertel 6600: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6601: 	return 0;
                   6602:     }
                   6603:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6604: 
                   6605:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6606: 	return 0;
                   6607:     }
1.200     albertel 6608:     return 1;
                   6609: }
                   6610: 
1.423     albertel 6611: =pod
                   6612: 
                   6613: =item remember_current_skipped
                   6614: 
1.424     albertel 6615:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6616:    file and remembers them into scan_data for later use.
                   6617: 
1.423     albertel 6618: =cut
                   6619: 
1.200     albertel 6620: sub remember_current_skipped {
                   6621:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6622:     my %to_remember;
                   6623:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6624: 	if ($scanlines->{'skipped'}[$i]) {
                   6625: 	    $to_remember{$i}=1;
                   6626: 	}
                   6627:     }
1.376     albertel 6628: 
1.200     albertel 6629:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6630:     &scantron_putfile(undef,$scan_data);
                   6631: }
                   6632: 
1.423     albertel 6633: =pod
                   6634: 
                   6635: =item check_for_error
                   6636: 
1.424     albertel 6637:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6638:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6639:     something went wrong.
                   6640: 
1.423     albertel 6641: =cut
                   6642: 
1.200     albertel 6643: sub check_for_error {
                   6644:     my ($r,$result)=@_;
                   6645:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6646: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6647:     }
                   6648: }
1.157     albertel 6649: 
1.423     albertel 6650: =pod
                   6651: 
                   6652: =item scantron_warning_screen
                   6653: 
1.424     albertel 6654:    Interstitial screen to make sure the operator has selected the
                   6655:    correct options before we start the validation phase.
                   6656: 
1.423     albertel 6657: =cut
                   6658: 
1.203     albertel 6659: sub scantron_warning_screen {
1.650     raeburn  6660:     my ($button_text,$symb)=@_;
1.257     albertel 6661:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6662:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6663:     my $CODElist;
1.284     albertel 6664:     if ($scantron_config{'CODElocation'} &&
                   6665: 	$scantron_config{'CODEstart'} &&
                   6666: 	$scantron_config{'CODElength'}) {
                   6667: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6668: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6669: 	$CODElist=
1.492     albertel 6670: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6671: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6672:     }
1.663     raeburn  6673:     my $lastbubblepoints;
                   6674:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6675:         $lastbubblepoints =
                   6676:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6677:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6678:     }
1.492     albertel 6679:     return ('
1.203     albertel 6680: <p>
1.492     albertel 6681: <span class="LC_warning">
1.705     raeburn  6682: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6683: </p>
                   6684: <table>
1.492     albertel 6685: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6686: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6687: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6688: </table>
1.680     raeburn  6689: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6690: '.&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 6691: 
                   6692: <br />
1.492     albertel 6693: ');
1.203     albertel 6694: }
                   6695: 
1.423     albertel 6696: =pod
                   6697: 
                   6698: =item scantron_do_warning
                   6699: 
1.424     albertel 6700:    Check if the operator has picked something for all required
                   6701:    fields. Error out if something is missing.
                   6702: 
1.423     albertel 6703: =cut
                   6704: 
1.203     albertel 6705: sub scantron_do_warning {
1.608     www      6706:     my ($r,$symb)=@_;
1.203     albertel 6707:     if (!$symb) {return '';}
1.324     albertel 6708:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6709:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6710:     if ( $env{'form.selectpage'} eq '' ||
                   6711: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6712: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6713: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6714: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6715: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6716: 	} 
1.257     albertel 6717: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6718: 	    $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 6719: 	} 
1.257     albertel 6720: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6721: 	    $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 6722: 	} 
                   6723:     } else {
1.650     raeburn  6724: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6725:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6726: 	$r->print('
1.663     raeburn  6727: '.$warning.$bubbledbyhand.'
1.492     albertel 6728: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6729: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6730: ');
1.237     albertel 6731:     }
1.614     www      6732:     $r->print("</form><br />");
1.203     albertel 6733:     return '';
                   6734: }
                   6735: 
1.423     albertel 6736: =pod
                   6737: 
                   6738: =item scantron_form_start
                   6739: 
1.424     albertel 6740:     html hidden input for remembering all selected grading options
                   6741: 
1.423     albertel 6742: =cut
                   6743: 
1.203     albertel 6744: sub scantron_form_start {
                   6745:     my ($max_bubble)=@_;
                   6746:     my $result= <<SCANTRONFORM;
                   6747: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6748:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6749:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6750:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6751:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6752:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6753:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6754:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6755:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6756:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6757: SCANTRONFORM
1.447     foxr     6758: 
                   6759:   my $line = 0;
                   6760:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6761:        my $chunk =
                   6762: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6763:        $chunk .=
                   6764: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6765:        $chunk .= 
                   6766:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6767:        $chunk .=
                   6768:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6769:        $chunk .=
                   6770:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6771:        $result .= $chunk;
                   6772:        $line++;
1.691     raeburn  6773:     }
1.203     albertel 6774:     return $result;
                   6775: }
                   6776: 
1.423     albertel 6777: =pod
                   6778: 
                   6779: =item scantron_validate_file
                   6780: 
1.659     raeburn  6781:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6782: 
                   6783:     Also processes any necessary information resets that need to
                   6784:     occur before validation begins (ignore previous corrections,
                   6785:     restarting the skipped records processing)
                   6786: 
1.423     albertel 6787: =cut
                   6788: 
1.157     albertel 6789: sub scantron_validate_file {
1.608     www      6790:     my ($r,$symb) = @_;
1.157     albertel 6791:     if (!$symb) {return '';}
1.324     albertel 6792:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6793:     
1.703     bisitz   6794:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6795:     # them when doing the corrections reset
1.257     albertel 6796:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6797: 	&reset_skipping_status();
                   6798:     }
1.257     albertel 6799:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6800: 	&remember_current_skipped();
1.257     albertel 6801: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6802:     }
                   6803: 
1.257     albertel 6804:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6805: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6806: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6807: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6808: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6809:     }
1.200     albertel 6810: 
1.257     albertel 6811:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6812: 	&scantron_process_corrections($r);
                   6813:     }
1.503     raeburn  6814:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6815:     #get the student pick code ready
                   6816:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6817:     my $nav_error;
1.649     raeburn  6818:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6819:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6820:     if ($nav_error) {
                   6821:         $r->print(&navmap_errormsg());
                   6822:         return '';
                   6823:     }
1.203     albertel 6824:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6825:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6826:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6827:     }
1.157     albertel 6828:     $r->print($result);
                   6829:     
1.334     albertel 6830:     my @validate_phases=( 'sequence',
                   6831: 			  'ID',
1.157     albertel 6832: 			  'CODE',
                   6833: 			  'doublebubble',
                   6834: 			  'missingbubbles');
1.257     albertel 6835:     if (!$env{'form.validatepass'}) {
                   6836: 	$env{'form.validatepass'} = 0;
1.157     albertel 6837:     }
1.257     albertel 6838:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6839: 
1.448     foxr     6840: 
1.157     albertel 6841:     my $stop=0;
                   6842:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6843: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6844: 	$r->rflush();
1.691     raeburn  6845:      
1.157     albertel 6846: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6847: 	{
                   6848: 	    no strict 'refs';
                   6849: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6850: 	}
                   6851:     }
                   6852:     if (!$stop) {
1.650     raeburn  6853: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6854: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6855:                   $warning.
                   6856:                   &mt('Perform verification for each student after storage of submissions?').
                   6857:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6858:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6859:                   ('&nbsp;'x3).'<label>'.
                   6860:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6861:                   '</label></span><br />'.
                   6862:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6863:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6864:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6865:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6866:     } else {
                   6867: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6868: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6869:     }
                   6870:     if ($stop) {
1.334     albertel 6871: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6872: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6873: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6874: 
1.650     raeburn  6875: 	    $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 6876: 	} else {
1.503     raeburn  6877:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6878: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6879:             } else {
1.539     riegler  6880:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6881:             }
1.492     albertel 6882: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6883: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6884: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6885: 	}
1.157     albertel 6886:     }
1.614     www      6887:     $r->print(" </form><br />");
1.157     albertel 6888:     return '';
                   6889: }
                   6890: 
1.423     albertel 6891: 
                   6892: =pod
                   6893: 
                   6894: =item scantron_remove_file
                   6895: 
1.659     raeburn  6896:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6897:    scantron_original_<filename> is never removed
                   6898: 
                   6899: 
1.423     albertel 6900: =cut
                   6901: 
1.200     albertel 6902: sub scantron_remove_file {
1.192     albertel 6903:     my ($which)=@_;
1.257     albertel 6904:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6905:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6906:     my $file='scantron_';
1.200     albertel 6907:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6908: 	$file.=$which.'_';
1.192     albertel 6909:     } else {
                   6910: 	return 'refused';
                   6911:     }
1.257     albertel 6912:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6913:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6914: }
                   6915: 
1.423     albertel 6916: 
                   6917: =pod
                   6918: 
                   6919: =item scantron_remove_scan_data
                   6920: 
1.659     raeburn  6921:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6922:    data file.  (In the case that both the are doing skipped records we need
                   6923:    to remember the old skipped lines for the time being so that element
                   6924:    persists for a while.)
                   6925: 
1.423     albertel 6926: =cut
                   6927: 
1.200     albertel 6928: sub scantron_remove_scan_data {
1.257     albertel 6929:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6930:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6931:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6932:     my @todelete;
1.257     albertel 6933:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6934:     foreach my $key (@keys) {
                   6935: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6936: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6937: 		$key=~/remember_skipping/) {
                   6938: 		next;
                   6939: 	    }
1.192     albertel 6940: 	    push(@todelete,$key);
                   6941: 	}
                   6942:     }
1.200     albertel 6943:     my $result;
1.192     albertel 6944:     if (@todelete) {
1.491     albertel 6945: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6946: 				       \@todelete,$cdom,$cname);
                   6947:     } else {
                   6948: 	$result = 'ok';
1.192     albertel 6949:     }
                   6950:     return $result;
                   6951: }
                   6952: 
1.423     albertel 6953: 
                   6954: =pod
                   6955: 
                   6956: =item scantron_getfile
                   6957: 
1.659     raeburn  6958:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6959:     the scan_data hash
                   6960:   
                   6961:   Arguments:
                   6962:     None
                   6963: 
                   6964:   Returns:
                   6965:     2 hash references
                   6966: 
                   6967:      - first one has 
                   6968:          orig      -
                   6969:          corrected -
                   6970:          skipped   -  each of which points to an array ref of the specified
                   6971:                       file broken up into individual lines
                   6972:          count     - number of scanlines
                   6973:  
                   6974:      - second is the scan_data hash possible keys are
1.425     albertel 6975:        ($number refers to scanline numbered $number and thus the key affects
                   6976:         only that scanline
                   6977:         $bubline refers to the specific bubble line element and the aspects
                   6978:         refers to that specific bubble line element)
                   6979: 
                   6980:        $number.user - username:domain to use
                   6981:        $number.CODE_ignore_dup 
                   6982:                     - ignore the duplicate CODE error 
                   6983:        $number.useCODE
                   6984:                     - use the CODE in the scanline as is
                   6985:        $number.no_bubble.$bubline
                   6986:                     - it is valid that there is no bubbled in bubble
                   6987:                       at $number $bubline
                   6988:        remember_skipping
                   6989:                     - a frozen hash containing keys of $number and values
                   6990:                       of either 
                   6991:                         1 - we are on a 'do skipped records pass' and plan
                   6992:                             on processing this line
                   6993:                         2 - we are on a 'do skipped records pass' and this
                   6994:                             scanline has been marked to skip yet again
1.424     albertel 6995: 
1.423     albertel 6996: =cut
                   6997: 
1.157     albertel 6998: sub scantron_getfile {
1.200     albertel 6999:     #FIXME really would prefer a scantron directory
1.257     albertel 7000:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7001:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7002:     my $lines;
                   7003:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7004: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7005:     my %scanlines;
                   7006:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7007:     my $temp=$scanlines{'orig'};
                   7008:     $scanlines{'count'}=$#$temp;
                   7009: 
                   7010:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7011: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7012:     if ($lines eq '-1') {
                   7013: 	$scanlines{'corrected'}=[];
                   7014:     } else {
                   7015: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7016:     }
                   7017:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7018: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7019:     if ($lines eq '-1') {
                   7020: 	$scanlines{'skipped'}=[];
                   7021:     } else {
                   7022: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7023:     }
1.175     albertel 7024:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7025:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7026:     my %scan_data = @tmp;
                   7027:     return (\%scanlines,\%scan_data);
                   7028: }
                   7029: 
1.423     albertel 7030: =pod
                   7031: 
                   7032: =item lonnet_putfile
                   7033: 
1.424     albertel 7034:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7035: 
                   7036:  Arguments:
                   7037:    $contents - data to store
                   7038:    $filename - filename to store $contents into
                   7039: 
                   7040:  Returns:
                   7041:    result value from &Apache::lonnet::finishuserfileupload
                   7042: 
1.423     albertel 7043: =cut
                   7044: 
1.157     albertel 7045: sub lonnet_putfile {
                   7046:     my ($contents,$filename)=@_;
1.257     albertel 7047:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7048:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7049:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7050:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7051: 
                   7052: }
                   7053: 
1.423     albertel 7054: =pod
                   7055: 
                   7056: =item scantron_putfile
                   7057: 
1.659     raeburn  7058:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7059:     scan_data hash. (Does not modify the original version only the
                   7060:     corrected and skipped versions.
                   7061: 
                   7062:  Arguments:
                   7063:     $scanlines - hash ref that looks like the first return value from
                   7064:                  &scantron_getfile()
                   7065:     $scan_data - hash ref that looks like the second return value from
                   7066:                  &scantron_getfile()
                   7067: 
1.423     albertel 7068: =cut
                   7069: 
1.157     albertel 7070: sub scantron_putfile {
                   7071:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7072:     #FIXME really would prefer a scantron directory
1.257     albertel 7073:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7074:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7075:     if ($scanlines) {
                   7076: 	my $prefix='scantron_';
1.157     albertel 7077: # no need to update orig, shouldn't change
                   7078: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7079: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7080: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7081: 			$prefix.'corrected_'.
1.257     albertel 7082: 			$env{'form.scantron_selectfile'});
1.200     albertel 7083: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7084: 			$prefix.'skipped_'.
1.257     albertel 7085: 			$env{'form.scantron_selectfile'});
1.200     albertel 7086:     }
1.175     albertel 7087:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7088: }
                   7089: 
1.423     albertel 7090: =pod
                   7091: 
                   7092: =item scantron_get_line
                   7093: 
1.424     albertel 7094:    Returns the correct version of the scanline
                   7095: 
                   7096:  Arguments:
                   7097:     $scanlines - hash ref that looks like the first return value from
                   7098:                  &scantron_getfile()
                   7099:     $scan_data - hash ref that looks like the second return value from
                   7100:                  &scantron_getfile()
                   7101:     $i         - number of the requested line (starts at 0)
                   7102: 
                   7103:  Returns:
                   7104:    A scanline, (either the original or the corrected one if it
                   7105:    exists), or undef if the requested scanline should be
                   7106:    skipped. (Either because it's an skipped scanline, or it's an
                   7107:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7108:    pass.
                   7109: 
1.423     albertel 7110: =cut
                   7111: 
1.157     albertel 7112: sub scantron_get_line {
1.200     albertel 7113:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7114:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7115:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7116:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7117:     return $scanlines->{'orig'}[$i]; 
                   7118: }
                   7119: 
1.423     albertel 7120: =pod
                   7121: 
                   7122: =item scantron_todo_count
                   7123: 
1.424     albertel 7124:     Counts the number of scanlines that need processing.
                   7125: 
                   7126:  Arguments:
                   7127:     $scanlines - hash ref that looks like the first return value from
                   7128:                  &scantron_getfile()
                   7129:     $scan_data - hash ref that looks like the second return value from
                   7130:                  &scantron_getfile()
                   7131: 
                   7132:  Returns:
                   7133:     $count - number of scanlines to process
                   7134: 
1.423     albertel 7135: =cut
                   7136: 
1.200     albertel 7137: sub get_todo_count {
                   7138:     my ($scanlines,$scan_data)=@_;
                   7139:     my $count=0;
                   7140:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7141: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7142: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7143: 	$count++;
                   7144:     }
                   7145:     return $count;
                   7146: }
                   7147: 
1.423     albertel 7148: =pod
                   7149: 
                   7150: =item scantron_put_line
                   7151: 
1.659     raeburn  7152:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7153:     data file.
                   7154: 
                   7155:  Arguments:
                   7156:     $scanlines - hash ref that looks like the first return value from
                   7157:                  &scantron_getfile()
                   7158:     $scan_data - hash ref that looks like the second return value from
                   7159:                  &scantron_getfile()
                   7160:     $i         - line number to update
                   7161:     $newline   - contents of the updated scanline
                   7162:     $skip      - if true make the line for skipping and update the
                   7163:                  'skipped' file
                   7164: 
1.423     albertel 7165: =cut
                   7166: 
1.157     albertel 7167: sub scantron_put_line {
1.200     albertel 7168:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7169:     if ($skip) {
                   7170: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7171: 	&start_skipping($scan_data,$i);
1.157     albertel 7172: 	return;
                   7173:     }
                   7174:     $scanlines->{'corrected'}[$i]=$newline;
                   7175: }
                   7176: 
1.423     albertel 7177: =pod
                   7178: 
                   7179: =item scantron_clear_skip
                   7180: 
1.424     albertel 7181:    Remove a line from the 'skipped' file
                   7182: 
                   7183:  Arguments:
                   7184:     $scanlines - hash ref that looks like the first return value from
                   7185:                  &scantron_getfile()
                   7186:     $scan_data - hash ref that looks like the second return value from
                   7187:                  &scantron_getfile()
                   7188:     $i         - line number to update
                   7189: 
1.423     albertel 7190: =cut
                   7191: 
1.376     albertel 7192: sub scantron_clear_skip {
                   7193:     my ($scanlines,$scan_data,$i)=@_;
                   7194:     if (exists($scanlines->{'skipped'}[$i])) {
                   7195: 	undef($scanlines->{'skipped'}[$i]);
                   7196: 	return 1;
                   7197:     }
                   7198:     return 0;
                   7199: }
                   7200: 
1.423     albertel 7201: =pod
                   7202: 
                   7203: =item scantron_filter_not_exam
                   7204: 
1.424     albertel 7205:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7206:    filter out resources that are not marked as 'exam' mode
                   7207: 
1.423     albertel 7208: =cut
                   7209: 
1.334     albertel 7210: sub scantron_filter_not_exam {
                   7211:     my ($curres)=@_;
                   7212:     
                   7213:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7214: 	# if the user has asked to not have either hidden
                   7215: 	# or 'randomout' controlled resources to be graded
                   7216: 	# don't include them
                   7217: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7218: 	    && $curres->randomout) {
                   7219: 	    return 0;
                   7220: 	}
                   7221: 	return 1;
                   7222:     }
                   7223:     return 0;
                   7224: }
                   7225: 
1.423     albertel 7226: =pod
                   7227: 
                   7228: =item scantron_validate_sequence
                   7229: 
1.424     albertel 7230:     Validates the selected sequence, checking for resource that are
                   7231:     not set to exam mode.
                   7232: 
1.423     albertel 7233: =cut
                   7234: 
1.334     albertel 7235: sub scantron_validate_sequence {
                   7236:     my ($r,$currentphase) = @_;
                   7237: 
                   7238:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7239:     unless (ref($navmap)) {
                   7240:         $r->print(&navmap_errormsg());
                   7241:         return (1,$currentphase);
                   7242:     }
1.334     albertel 7243:     my (undef,undef,$sequence)=
                   7244: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7245: 
                   7246:     my $map=$navmap->getResourceByUrl($sequence);
                   7247: 
                   7248:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7249:                                     value="ignore" />');
                   7250:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7251: 	my @resources=
                   7252: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7253: 	if (@resources) {
1.675     bisitz   7254: 	    $r->print(
                   7255:                 '<p class="LC_warning">'
                   7256:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7257:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7258:                    .' work correctly.')
                   7259:                .'</p>'
                   7260:             );
1.334     albertel 7261: 	    return (1,$currentphase);
                   7262: 	}
                   7263:     }
                   7264: 
                   7265:     return (0,$currentphase+1);
                   7266: }
                   7267: 
1.423     albertel 7268: 
                   7269: 
1.157     albertel 7270: sub scantron_validate_ID {
                   7271:     my ($r,$currentphase) = @_;
                   7272:     
                   7273:     #get student info
                   7274:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7275:     my %idmap=&username_to_idmap($classlist);
                   7276: 
                   7277:     #get scantron line setup
1.257     albertel 7278:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7279:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7280: 
                   7281:     my $nav_error;
1.649     raeburn  7282:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7283:     if ($nav_error) {
                   7284:         $r->print(&navmap_errormsg());
                   7285:         return(1,$currentphase);
                   7286:     }
1.157     albertel 7287: 
                   7288:     my %found=('ids'=>{},'usernames'=>{});
                   7289:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7290: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7291: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7292: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7293: 						 $scan_data);
                   7294: 	my $id=$$scan_record{'scantron.ID'};
                   7295: 	my $found;
                   7296: 	foreach my $checkid (keys(%idmap)) {
                   7297: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7298: 	}
                   7299: 	if ($found) {
                   7300: 	    my $username=$idmap{$found};
                   7301: 	    if ($found{'ids'}{$found}) {
                   7302: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7303: 					 $line,'duplicateID',$found);
1.194     albertel 7304: 		return(1,$currentphase);
1.157     albertel 7305: 	    } elsif ($found{'usernames'}{$username}) {
                   7306: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7307: 					 $line,'duplicateID',$username);
1.194     albertel 7308: 		return(1,$currentphase);
1.157     albertel 7309: 	    }
1.186     albertel 7310: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7311: 	    $found{'ids'}{$found}++;
                   7312: 	    $found{'usernames'}{$username}++;
                   7313: 	} else {
                   7314: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7315: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7316: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7317: 		    &scantron_get_correction($r,$i,$scan_record,
                   7318: 					     \%scantron_config,
                   7319: 					     $line,'duplicateID',$username);
1.194     albertel 7320: 		    return(1,$currentphase);
1.157     albertel 7321: 		} elsif (!defined($username)) {
                   7322: 		    &scantron_get_correction($r,$i,$scan_record,
                   7323: 					     \%scantron_config,
                   7324: 					     $line,'incorrectID');
1.194     albertel 7325: 		    return(1,$currentphase);
1.157     albertel 7326: 		}
                   7327: 		$found{'usernames'}{$username}++;
                   7328: 	    } else {
                   7329: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7330: 					 $line,'incorrectID');
1.194     albertel 7331: 		return(1,$currentphase);
1.157     albertel 7332: 	    }
                   7333: 	}
                   7334:     }
                   7335: 
                   7336:     return (0,$currentphase+1);
                   7337: }
                   7338: 
1.423     albertel 7339: 
1.157     albertel 7340: sub scantron_get_correction {
1.691     raeburn  7341:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7342:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7343: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7344: #to show both the current line and the previous one and allow skipping
                   7345: #the previous one or the current one
                   7346: 
1.333     albertel 7347:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7348:         $r->print(
                   7349:             '<p class="LC_warning">'
                   7350:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7351:                 "<b>$error</b>",
                   7352:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7353:            ."</p> \n");
1.157     albertel 7354:     } else {
1.658     bisitz   7355:         $r->print(
                   7356:             '<p class="LC_warning">'
                   7357:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7358:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7359:            ."</p> \n");
                   7360:     }
                   7361:     my $message =
                   7362:         '<p>'
                   7363:        .&mt('The ID on the form is [_1]',
                   7364:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7365:        .'<br />'
1.665     raeburn  7366:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7367:             $$scan_record{'scantron.LastName'},
                   7368:             $$scan_record{'scantron.FirstName'})
                   7369:        .'</p>';
1.242     albertel 7370: 
1.157     albertel 7371:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7372:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7373:                            # Array populated for doublebubble or
                   7374:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7375:                            # to validate radio button checking   
                   7376: 
1.157     albertel 7377:     if ($error =~ /ID$/) {
1.186     albertel 7378: 	if ($error eq 'incorrectID') {
1.658     bisitz   7379:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7380: 		      "</p>\n");
1.157     albertel 7381: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7382:             $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 7383: 	}
1.242     albertel 7384: 	$r->print($message);
1.492     albertel 7385: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7386: 	$r->print("\n<ul><li> ");
                   7387: 	#FIXME it would be nice if this sent back the user ID and
                   7388: 	#could do partial userID matches
                   7389: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7390: 				       'scantron_username','scantron_domain'));
                   7391: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7392: 	$r->print("\n:\n".
1.257     albertel 7393: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7394: 
                   7395: 	$r->print('</li>');
1.186     albertel 7396:     } elsif ($error =~ /CODE$/) {
                   7397: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7398: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7399: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7400: 	    $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 7401: 	}
1.658     bisitz   7402: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7403: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7404:                  ."</p>\n");
1.242     albertel 7405: 	$r->print($message);
1.658     bisitz   7406: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7407: 	$r->print("\n<br /> ");
1.194     albertel 7408: 	my $i=0;
1.273     albertel 7409: 	if ($error eq 'incorrectCODE' 
                   7410: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7411: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7412: 	    if ($closest > 0) {
                   7413: 		foreach my $testcode (@{$closest}) {
                   7414: 		    my $checked='';
1.569     bisitz   7415: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7416: 		    $r->print("
                   7417:    <label>
1.569     bisitz   7418:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7419:        ".&mt("Use the similar CODE [_1] instead.",
                   7420: 	    "<b><tt>".$testcode."</tt></b>")."
                   7421:     </label>
                   7422:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7423: 		    $r->print("\n<br />");
                   7424: 		    $i++;
                   7425: 		}
1.194     albertel 7426: 	    }
                   7427: 	}
1.273     albertel 7428: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7429: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7430: 	    $r->print("
                   7431:     <label>
1.569     bisitz   7432:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7433:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7434: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7435:     </label>");
1.273     albertel 7436: 	    $r->print("\n<br />");
                   7437: 	}
1.194     albertel 7438: 
1.597     wenzelju 7439: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7440: function change_radio(field) {
1.190     albertel 7441:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7442:     var i;
                   7443:     for (i=0;i<slct.length;i++) {
                   7444:         if (slct[i].value==field) { slct[i].checked=true; }
                   7445:     }
                   7446: }
                   7447: ENDSCRIPT
1.187     albertel 7448: 	my $href="/adm/pickcode?".
1.359     www      7449: 	   "form=".&escape("scantronupload").
                   7450: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7451: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7452: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7453: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7454: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7455: 	    $r->print("
                   7456:     <label>
                   7457:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7458:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7459: 	     "<a target='_blank' href='$href'>","</a>")."
                   7460:     </label> 
1.558     bisitz   7461:     ".&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 7462: 	    $r->print("\n<br />");
                   7463: 	}
1.492     albertel 7464: 	$r->print("
                   7465:     <label>
                   7466:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7467:        ".&mt("Use [_1] as the CODE.",
                   7468: 	     "</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 7469: 	$r->print("\n<br /><br />");
1.157     albertel 7470:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7471: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7472: 
                   7473: 	# The form field scantron_questions is acutally a list of line numbers.
                   7474: 	# represented by this form so:
                   7475: 
1.691     raeburn  7476: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7477:                                                 $respnumlookup,$startline);
1.497     foxr     7478: 
1.157     albertel 7479: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7480: 		  $line_list.'" />');
1.242     albertel 7481: 	$r->print($message);
1.492     albertel 7482: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7483: 	foreach my $question (@{$arg}) {
1.503     raeburn  7484: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7485:                                                    $scan_record, $error,
                   7486:                                                    $randomorder,$randompick,
                   7487:                                                    $respnumlookup,$startline);
1.524     raeburn  7488:             push(@lines_to_correct,@linenums);
1.157     albertel 7489: 	}
1.503     raeburn  7490:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7491:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7492: 	$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 7493: 	$r->print($message);
1.492     albertel 7494: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7495: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7496: 
1.503     raeburn  7497: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7498: 	# a list of question numbers. Therefore:
                   7499: 	#
1.691     raeburn  7500: 
                   7501: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7502:                                                 $respnumlookup,$startline);
1.497     foxr     7503: 
1.157     albertel 7504: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7505: 		  $line_list.'" />');
1.157     albertel 7506: 	foreach my $question (@{$arg}) {
1.503     raeburn  7507: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7508:                                                    $scan_record, $error,
                   7509:                                                    $randomorder,$randompick,
                   7510:                                                    $respnumlookup,$startline);
1.524     raeburn  7511:             push(@lines_to_correct,@linenums);
1.157     albertel 7512: 	}
1.503     raeburn  7513:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7514:     } else {
                   7515: 	$r->print("\n<ul>");
                   7516:     }
                   7517:     $r->print("\n</li></ul>");
1.497     foxr     7518: }
                   7519: 
1.503     raeburn  7520: sub verify_bubbles_checked {
                   7521:     my (@ansnums) = @_;
                   7522:     my $ansnumstr = join('","',@ansnums);
                   7523:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7524:     &js_escape(\$warning);
1.597     wenzelju 7525:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7526: function verify_bubble_radio(form) {
                   7527:     var ansnumArray = new Array ("$ansnumstr");
                   7528:     var need_bubble_count = 0;
                   7529:     for (var i=0; i<ansnumArray.length; i++) {
                   7530:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7531:             var bubble_picked = 0; 
                   7532:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7533:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7534:                     bubble_picked = 1;
                   7535:                 }
                   7536:             }
                   7537:             if (bubble_picked == 0) {
                   7538:                 need_bubble_count ++;
                   7539:             }
                   7540:         }
                   7541:     }
                   7542:     if (need_bubble_count) {
                   7543:         alert("$warning");
                   7544:         return;
                   7545:     }
                   7546:     form.submit(); 
                   7547: }
                   7548: ENDSCRIPT
                   7549:     return $output;
                   7550: }
                   7551: 
1.497     foxr     7552: =pod
                   7553: 
                   7554: =item  questions_to_line_list
1.157     albertel 7555: 
1.497     foxr     7556: Converts a list of questions into a string of comma separated
                   7557: line numbers in the answer sheet used by the questions.  This is
                   7558: used to fill in the scantron_questions form field.
                   7559: 
                   7560:   Arguments:
                   7561:      questions    - Reference to an array of questions.
1.691     raeburn  7562:      randomorder  - True if randomorder in use.
                   7563:      randompick   - True if randompick in use.
                   7564:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7565:                      for current line to question number used for same question
                   7566:                      in "Master Seqence" (as seen by Course Coordinator).
                   7567:      startline    - Reference to hash where key is question number (0 is first)
                   7568:                     and key is number of first bubble line for current student
                   7569:                     or code-based randompick and/or randomorder.
1.693     raeburn  7570: 
1.497     foxr     7571: =cut
                   7572: 
                   7573: 
                   7574: sub questions_to_line_list {
1.691     raeburn  7575:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7576:     my @lines;
                   7577: 
1.503     raeburn  7578:     foreach my $item (@{$questions}) {
                   7579:         my $question = $item;
                   7580:         my ($first,$count,$last);
                   7581:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7582:             $question = $1;
                   7583:             my $subquestion = $2;
1.691     raeburn  7584:             my $responsenum = $question-1;
                   7585:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7586:                 $responsenum = $respnumlookup->{$question-1};
                   7587:                 if (ref($startline) eq 'HASH') {
                   7588:                     $first = $startline->{$question-1} + 1;
                   7589:                 }
                   7590:             } else {
                   7591:                 $first = $first_bubble_line{$responsenum} + 1;
                   7592:             }
                   7593:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7594:             my $subcount = 1;
                   7595:             while ($subcount<$subquestion) {
                   7596:                 $first += $subans[$subcount-1];
                   7597:                 $subcount ++;
                   7598:             }
                   7599:             $count = $subans[$subquestion-1];
                   7600:         } else {
1.691     raeburn  7601:             my $responsenum = $question-1;
                   7602:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7603:                 $responsenum = $respnumlookup->{$question-1};
                   7604:                 if (ref($startline) eq 'HASH') {
                   7605:                     $first = $startline->{$question-1} + 1;
                   7606:                 }
                   7607:             } else {
                   7608:                 $first = $first_bubble_line{$responsenum} + 1;
                   7609:             }
                   7610: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7611:         }
1.506     raeburn  7612:         $last = $first+$count-1;
1.503     raeburn  7613:         push(@lines, ($first..$last));
1.497     foxr     7614:     }
                   7615:     return join(',', @lines);
                   7616: }
                   7617: 
                   7618: =pod 
                   7619: 
                   7620: =item prompt_for_corrections
                   7621: 
                   7622: Prompts for a potentially multiline correction to the
                   7623: user's bubbling (factors out common code from scantron_get_correction
                   7624: for multi and missing bubble cases).
                   7625: 
                   7626:  Arguments:
                   7627:    $r           - Apache request object.
                   7628:    $question    - The question number to prompt for.
                   7629:    $scan_config - The scantron file configuration hash.
                   7630:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7631:    $error       - Type of error
1.691     raeburn  7632:    $randomorder - True if randomorder in use.
                   7633:    $randompick  - True if randompick in use.
                   7634:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7635:                     for current line to question number used for same question
                   7636:                     in "Master Seqence" (as seen by Course Coordinator).
                   7637:    $startline   - Reference to hash where key is question number (0 is first)
                   7638:                   and value is number of first bubble line for current student
                   7639:                   or code-based randompick and/or randomorder.
                   7640: 
1.497     foxr     7641: 
                   7642:  Implicit inputs:
                   7643:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7644:                                   Numbered from 0 (but question numbers are from
                   7645:                                   1.
                   7646:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7647:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7648:                                   type problems render as separate sub-questions, 
1.503     raeburn  7649:                                   in exam mode. This hash contains a 
                   7650:                                   comma-separated list of the lines per 
                   7651:                                   sub-question.
1.510     raeburn  7652:    %responsetype_per_response   - essayresponse, formularesponse,
                   7653:                                   stringresponse, imageresponse, reactionresponse,
                   7654:                                   and organicresponse type problem parts can have
1.503     raeburn  7655:                                   multiple lines per response if the weight
                   7656:                                   assigned exceeds 10.  In this case, only
                   7657:                                   one bubble per line is permitted, but more 
                   7658:                                   than one line might contain bubbles, e.g.
                   7659:                                   bubbling of: line 1 - J, line 2 - J, 
                   7660:                                   line 3 - B would assign 22 points.  
1.497     foxr     7661: 
                   7662: =cut
                   7663: 
                   7664: sub prompt_for_corrections {
1.691     raeburn  7665:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7666:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7667:     my ($current_line,$lines);
                   7668:     my @linenums;
                   7669:     my $questionnum = $question;
1.691     raeburn  7670:     my ($first,$responsenum);
1.503     raeburn  7671:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7672:         $question = $1;
                   7673:         my $subquestion = $2;
1.691     raeburn  7674:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7675:             $responsenum = $respnumlookup->{$question-1};
                   7676:             if (ref($startline) eq 'HASH') {
                   7677:                 $first = $startline->{$question-1};
                   7678:             }
                   7679:         } else {
                   7680:             $responsenum = $question-1;
1.714     raeburn  7681:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7682:         }
                   7683:         $current_line = $first + 1 ;
                   7684:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7685:         my $subcount = 1;
                   7686:         while ($subcount<$subquestion) {
                   7687:             $current_line += $subans[$subcount-1];
                   7688:             $subcount ++;
                   7689:         }
                   7690:         $lines = $subans[$subquestion-1];
                   7691:     } else {
1.691     raeburn  7692:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7693:             $responsenum = $respnumlookup->{$question-1};
                   7694:             if (ref($startline) eq 'HASH') { 
                   7695:                 $first = $startline->{$question-1};
                   7696:             }
                   7697:         } else {
                   7698:             $responsenum = $question-1;
                   7699:             $first = $first_bubble_line{$responsenum};
                   7700:         }
                   7701:         $current_line = $first + 1;
                   7702:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7703:     }
1.497     foxr     7704:     if ($lines > 1) {
1.503     raeburn  7705:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7706:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7707:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7708:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7709:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7710:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7711:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7712:             $r->print(
                   7713:                 &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)
                   7714:                .'<br /><br />'
                   7715:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7716:                .'<br />'
                   7717:                .&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.')
                   7718:                .'<br />'
                   7719:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7720:                .'<br /><br />'
                   7721:             );
1.503     raeburn  7722:         } else {
                   7723:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7724:         }
1.497     foxr     7725:     }
                   7726:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7727:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7728: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7729: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7730:         push(@linenums,$current_line);
1.497     foxr     7731: 	$current_line++;
                   7732:     }
                   7733:     if ($lines > 1) {
                   7734: 	$r->print("<hr /><br />");
                   7735:     }
1.503     raeburn  7736:     return @linenums;
1.157     albertel 7737: }
1.423     albertel 7738: 
                   7739: =pod
                   7740: 
                   7741: =item scantron_bubble_selector
                   7742:   
                   7743:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7744:    possibly showing the existing the selected bubbles if known
1.423     albertel 7745: 
                   7746:  Arguments:
                   7747:     $r           - Apache request object
                   7748:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7749:     $line        - Number of the line being displayed.
1.503     raeburn  7750:     $questionnum - Question number (may include subquestion)
                   7751:     $error       - Type of error.
1.497     foxr     7752:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7753: 
                   7754: =cut
                   7755: 
1.157     albertel 7756: sub scantron_bubble_selector {
1.503     raeburn  7757:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7758:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7759: 
                   7760:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7761:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7762:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7763:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7764:             $max=$$scan_config{'BubblesPerRow'};
                   7765:             if (($scmode eq 'number') && ($max > 10)) {
                   7766:                 $max = 10;
                   7767:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7768:                 $max = 26;
                   7769:             }
                   7770:         } else {
                   7771:             $max = 10;
                   7772:         }
                   7773:     }
1.274     albertel 7774: 
1.157     albertel 7775:     my @alphabet=('A'..'Z');
1.503     raeburn  7776:     $r->print(&Apache::loncommon::start_data_table().
                   7777:               &Apache::loncommon::start_data_table_row());
                   7778:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7779:     for (my $i=0;$i<$max+1;$i++) {
                   7780: 	$r->print("\n".'<td align="center">');
                   7781: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7782: 	else { $r->print('&nbsp;'); }
                   7783: 	$r->print('</td>');
                   7784:     }
1.503     raeburn  7785:     $r->print(&Apache::loncommon::end_data_table_row().
                   7786:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7787:     for (my $i=0;$i<$max;$i++) {
                   7788: 	$r->print("\n".
                   7789: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7790: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7791:     }
1.503     raeburn  7792:     my $nobub_checked = ' ';
                   7793:     if ($error eq 'missingbubble') {
                   7794:         $nobub_checked = ' checked = "checked" ';
                   7795:     }
                   7796:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7797: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7798:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7799:               $line.'" value="'.$questionnum.'" /></td>');
                   7800:     $r->print(&Apache::loncommon::end_data_table_row().
                   7801:               &Apache::loncommon::end_data_table());
1.157     albertel 7802: }
                   7803: 
1.423     albertel 7804: =pod
                   7805: 
                   7806: =item num_matches
                   7807: 
1.424     albertel 7808:    Counts the number of characters that are the same between the two arguments.
                   7809: 
                   7810:  Arguments:
                   7811:    $orig - CODE from the scanline
                   7812:    $code - CODE to match against
                   7813: 
                   7814:  Returns:
                   7815:    $count - integer count of the number of same characters between the
                   7816:             two arguments
                   7817: 
1.423     albertel 7818: =cut
                   7819: 
1.194     albertel 7820: sub num_matches {
                   7821:     my ($orig,$code) = @_;
                   7822:     my @code=split(//,$code);
                   7823:     my @orig=split(//,$orig);
                   7824:     my $same=0;
                   7825:     for (my $i=0;$i<scalar(@code);$i++) {
                   7826: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7827:     }
                   7828:     return $same;
                   7829: }
                   7830: 
1.423     albertel 7831: =pod
                   7832: 
                   7833: =item scantron_get_closely_matching_CODEs
                   7834: 
1.424     albertel 7835:    Cycles through all CODEs and finds the set that has the greatest
                   7836:    number of same characters as the provided CODE
                   7837: 
                   7838:  Arguments:
                   7839:    $allcodes - hash ref returned by &get_codes()
                   7840:    $CODE     - CODE from the current scanline
                   7841: 
                   7842:  Returns:
                   7843:    2 element list
                   7844:     - first elements is number of how closely matching the best fit is 
                   7845:       (5 means best set has 5 matching characters)
                   7846:     - second element is an arrary ref containing the set of valid CODEs
                   7847:       that best fit the passed in CODE
                   7848: 
1.423     albertel 7849: =cut
                   7850: 
1.194     albertel 7851: sub scantron_get_closely_matching_CODEs {
                   7852:     my ($allcodes,$CODE)=@_;
                   7853:     my @CODEs;
                   7854:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7855: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7856:     }
                   7857: 
                   7858:     return ($#CODEs,$CODEs[-1]);
                   7859: }
                   7860: 
1.423     albertel 7861: =pod
                   7862: 
                   7863: =item get_codes
                   7864: 
1.424     albertel 7865:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7866:    set of remembered CODEs.
                   7867: 
                   7868:  Arguments:
                   7869:   $old_name - name of the set of remembered CODEs
                   7870:   $cdom     - domain of the course
                   7871:   $cnum     - internal course name
                   7872: 
                   7873:  Returns:
                   7874:   %allcodes - keys are the valid CODEs, values are all 1
                   7875: 
1.423     albertel 7876: =cut
                   7877: 
1.194     albertel 7878: sub get_codes {
1.280     foxr     7879:     my ($old_name, $cdom, $cnum) = @_;
                   7880:     if (!$old_name) {
                   7881: 	$old_name=$env{'form.scantron_CODElist'};
                   7882:     }
                   7883:     if (!$cdom) {
                   7884: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7885:     }
                   7886:     if (!$cnum) {
                   7887: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7888:     }
1.278     albertel 7889:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7890: 				    $cdom,$cnum);
                   7891:     my %allcodes;
                   7892:     if ($result{"type\0$old_name"} eq 'number') {
                   7893: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7894:     } else {
                   7895: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7896:     }
1.194     albertel 7897:     return %allcodes;
                   7898: }
                   7899: 
1.423     albertel 7900: =pod
                   7901: 
                   7902: =item scantron_validate_CODE
                   7903: 
1.424     albertel 7904:    Validates all scanlines in the selected file to not have any
                   7905:    invalid or underspecified CODEs and that none of the codes are
                   7906:    duplicated if this was requested.
                   7907: 
1.423     albertel 7908: =cut
                   7909: 
1.157     albertel 7910: sub scantron_validate_CODE {
                   7911:     my ($r,$currentphase) = @_;
1.257     albertel 7912:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7913:     if ($scantron_config{'CODElocation'} &&
                   7914: 	$scantron_config{'CODEstart'} &&
                   7915: 	$scantron_config{'CODElength'}) {
1.257     albertel 7916: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7917: 	    &FIXME_blow_up()
                   7918: 	}
                   7919:     } else {
                   7920: 	return (0,$currentphase+1);
                   7921:     }
                   7922:     
                   7923:     my %usedCODEs;
                   7924: 
1.194     albertel 7925:     my %allcodes=&get_codes();
1.186     albertel 7926: 
1.582     raeburn  7927:     my $nav_error;
1.649     raeburn  7928:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7929:     if ($nav_error) {
                   7930:         $r->print(&navmap_errormsg());
                   7931:         return(1,$currentphase);
                   7932:     }
1.447     foxr     7933: 
1.186     albertel 7934:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7935:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7936: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7937: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7938: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7939: 						 $scan_data);
                   7940: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7941: 	my $error=0;
1.224     albertel 7942: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7943: 	    &scantron_get_correction($r,$i,$scan_record,
                   7944: 				     \%scantron_config,
                   7945: 				     $line,'incorrectCODE',\%allcodes);
                   7946: 	    return(1,$currentphase);
                   7947: 	}
1.221     albertel 7948: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7949: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7950: 	    &scantron_get_correction($r,$i,$scan_record,
                   7951: 				     \%scantron_config,
1.194     albertel 7952: 				     $line,'incorrectCODE',\%allcodes);
                   7953: 	    return(1,$currentphase);
1.186     albertel 7954: 	}
1.214     albertel 7955: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7956: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7957: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7958: 	    &scantron_get_correction($r,$i,$scan_record,
                   7959: 				     \%scantron_config,
1.194     albertel 7960: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7961: 	    return(1,$currentphase);
1.186     albertel 7962: 	}
1.524     raeburn  7963: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7964:     }
1.157     albertel 7965:     return (0,$currentphase+1);
                   7966: }
                   7967: 
1.423     albertel 7968: =pod
                   7969: 
                   7970: =item scantron_validate_doublebubble
                   7971: 
1.424     albertel 7972:    Validates all scanlines in the selected file to not have any
                   7973:    bubble lines with multiple bubbles marked.
                   7974: 
1.423     albertel 7975: =cut
                   7976: 
1.157     albertel 7977: sub scantron_validate_doublebubble {
                   7978:     my ($r,$currentphase) = @_;
                   7979:     #get student info
                   7980:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7981:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7982:     my (undef,undef,$sequence)=
                   7983:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7984: 
                   7985:     #get scantron line setup
1.257     albertel 7986:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7987:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7988: 
                   7989:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7990:     unless (ref($navmap)) {
                   7991:         $r->print(&navmap_errormsg());
                   7992:         return(1,$currentphase);
                   7993:     }
                   7994:     my $map=$navmap->getResourceByUrl($sequence);
                   7995:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7996:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7997:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7998:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7999: 
1.583     raeburn  8000:     my $nav_error;
1.691     raeburn  8001:     if (ref($map)) {
                   8002:         $randomorder = $map->randomorder();
                   8003:         $randompick = $map->randompick();
                   8004:         if ($randomorder || $randompick) {
                   8005:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8006:             if ($nav_error) {
                   8007:                 $r->print(&navmap_errormsg());
                   8008:                 return(1,$currentphase);
                   8009:             }
                   8010:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8011:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8012:         }
                   8013:     } else {
                   8014:         $r->print(&navmap_errormsg());
                   8015:         return(1,$currentphase);
                   8016:     }
                   8017: 
1.649     raeburn  8018:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8019:     if ($nav_error) {
                   8020:         $r->print(&navmap_errormsg());
                   8021:         return(1,$currentphase);
                   8022:     }
1.447     foxr     8023: 
1.157     albertel 8024:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8025: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8026: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8027: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8028: 						 $scan_data,undef,\%idmap,$randomorder,
                   8029:                                                  $randompick,$sequence,\@master_seq,
                   8030:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8031:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8032: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8033: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8034: 				 'doublebubble',
1.691     raeburn  8035: 				 $$scan_record{'scantron.doubleerror'},
                   8036:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8037:     	return (1,$currentphase);
                   8038:     }
                   8039:     return (0,$currentphase+1);
                   8040: }
                   8041: 
1.423     albertel 8042: 
1.503     raeburn  8043: sub scantron_get_maxbubble {
1.649     raeburn  8044:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8045:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8046: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8047: 	&restore_bubble_lines();
1.257     albertel 8048: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8049:     }
1.330     albertel 8050: 
1.447     foxr     8051:     my (undef, undef, $sequence) =
1.257     albertel 8052: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8053: 
1.447     foxr     8054:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8055:     unless (ref($navmap)) {
                   8056:         if (ref($nav_error)) {
                   8057:             $$nav_error = 1;
                   8058:         }
1.591     raeburn  8059:         return;
1.582     raeburn  8060:     }
1.191     albertel 8061:     my $map=$navmap->getResourceByUrl($sequence);
                   8062:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8063:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8064: 
                   8065:     &Apache::lonxml::clear_problem_counter();
                   8066: 
1.557     raeburn  8067:     my $uname       = $env{'user.name'};
                   8068:     my $udom        = $env{'user.domain'};
1.435     foxr     8069:     my $cid         = $env{'request.course.id'};
                   8070:     my $total_lines = 0;
                   8071:     %bubble_lines_per_response = ();
1.447     foxr     8072:     %first_bubble_line         = ();
1.503     raeburn  8073:     %subdivided_bubble_lines   = ();
                   8074:     %responsetype_per_response = ();
1.691     raeburn  8075:     %masterseq_id_responsenum  = ();
1.554     raeburn  8076: 
1.447     foxr     8077:     my $response_number = 0;
                   8078:     my $bubble_line     = 0;
1.191     albertel 8079:     foreach my $resource (@resources) {
1.691     raeburn  8080:         my $resid = $resource->id(); 
1.672     raeburn  8081:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8082:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8083:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8084: 	    foreach my $part_id (@{$parts}) {
                   8085:                 my $lines;
                   8086: 
                   8087: 	        # TODO - make this a persistent hash not an array.
                   8088: 
                   8089:                 # optionresponse, matchresponse and rankresponse type items 
                   8090:                 # render as separate sub-questions in exam mode.
                   8091:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8092:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8093:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8094:                     my ($numbub,$numshown);
                   8095:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8096:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8097:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8098:                         }
                   8099:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8100:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8101:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8102:                         }
                   8103:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8104:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8105:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8106:                         }
                   8107:                     }
                   8108:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8109:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8110:                     }
1.649     raeburn  8111:                     my $bubbles_per_row =
                   8112:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8113:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8114:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8115:                         $inner_bubble_lines++;
                   8116:                     }
                   8117:                     for (my $i=0; $i<$numshown; $i++) {
                   8118:                         $subdivided_bubble_lines{$response_number} .= 
                   8119:                             $inner_bubble_lines.',';
                   8120:                     }
                   8121:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8122:                     $lines = $numshown * $inner_bubble_lines;
                   8123:                 } else {
                   8124:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8125:                 }
1.542     raeburn  8126: 
                   8127:                 $first_bubble_line{$response_number} = $bubble_line;
                   8128: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8129:                 $responsetype_per_response{$response_number} = 
                   8130:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8131:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8132: 	        $response_number++;
                   8133: 
                   8134: 	        $bubble_line +=  $lines;
                   8135: 	        $total_lines +=  $lines;
                   8136: 	    }
                   8137:         }
                   8138:     }
1.552     raeburn  8139:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8140: 
                   8141:     &save_bubble_lines();
                   8142:     $env{'form.scantron_maxbubble'} =
                   8143: 	$total_lines;
                   8144:     return $env{'form.scantron_maxbubble'};
                   8145: }
1.523     raeburn  8146: 
1.649     raeburn  8147: sub bubblesheet_bubbles_per_row {
                   8148:     my ($scantron_config) = @_;
                   8149:     my $bubbles_per_row;
                   8150:     if (ref($scantron_config) eq 'HASH') {
                   8151:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8152:     }
                   8153:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8154:         $bubbles_per_row = 10;
                   8155:     }
                   8156:     return $bubbles_per_row;
                   8157: }
                   8158: 
1.157     albertel 8159: sub scantron_validate_missingbubbles {
                   8160:     my ($r,$currentphase) = @_;
                   8161:     #get student info
                   8162:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8163:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8164:     my (undef,undef,$sequence)=
                   8165:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8166: 
                   8167:     #get scantron line setup
1.257     albertel 8168:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8169:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8170: 
                   8171:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8172:     unless (ref($navmap)) {
                   8173:         $r->print(&navmap_errormsg());
                   8174:         return(1,$currentphase);
                   8175:     }
                   8176: 
                   8177:     my $map=$navmap->getResourceByUrl($sequence);
                   8178:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8179:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8180:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8181:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8182: 
1.582     raeburn  8183:     my $nav_error;
1.691     raeburn  8184:     if (ref($map)) {
                   8185:         $randomorder = $map->randomorder();
                   8186:         $randompick = $map->randompick();
                   8187:         if ($randomorder || $randompick) {
                   8188:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8189:             if ($nav_error) {
                   8190:                 $r->print(&navmap_errormsg());
                   8191:                 return(1,$currentphase);
                   8192:             }
                   8193:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8194:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8195:         }
                   8196:     } else {
                   8197:         $r->print(&navmap_errormsg());
                   8198:         return(1,$currentphase);
                   8199:     }
                   8200: 
                   8201: 
1.649     raeburn  8202:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8203:     if ($nav_error) {
1.691     raeburn  8204:         $r->print(&navmap_errormsg());
1.693     raeburn  8205:         return(1,$currentphase);
1.582     raeburn  8206:     }
1.691     raeburn  8207: 
1.157     albertel 8208:     if (!$max_bubble) { $max_bubble=2**31; }
                   8209:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8210: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8211: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8212: 	my $scan_record =
                   8213:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8214: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8215:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8216:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8217: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8218: 	my @to_correct;
1.470     foxr     8219: 	
                   8220: 	# Probably here's where the error is...
                   8221: 
1.157     albertel 8222: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8223:             my $lastbubble;
                   8224:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8225:                my $question = $1;
                   8226:                my $subquestion = $2;
1.691     raeburn  8227:                my ($first,$responsenum);
                   8228:                if ($randomorder || $randompick) {
                   8229:                    $responsenum = $respnumlookup{$question-1};
                   8230:                    $first = $startline{$question-1};
                   8231:                } else {
                   8232:                    $responsenum = $question-1; 
                   8233:                    $first = $first_bubble_line{$responsenum};
                   8234:                }
                   8235:                if (!defined($first)) { next; }
                   8236:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8237:                my $subcount = 1;
                   8238:                while ($subcount<$subquestion) {
                   8239:                    $first += $subans[$subcount-1];
                   8240:                    $subcount ++;
                   8241:                }
                   8242:                my $count = $subans[$subquestion-1];
                   8243:                $lastbubble = $first + $count;
                   8244:             } else {
1.691     raeburn  8245:                my ($first,$responsenum);
                   8246:                if ($randomorder || $randompick) {
                   8247:                    $responsenum = $respnumlookup{$missing-1};
                   8248:                    $first = $startline{$missing-1};
                   8249:                } else {
                   8250:                    $responsenum = $missing-1;
                   8251:                    $first = $first_bubble_line{$responsenum};
                   8252:                }
                   8253:                if (!defined($first)) { next; }
                   8254:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8255:             }
                   8256:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8257: 	    push(@to_correct,$missing);
                   8258: 	}
                   8259: 	if (@to_correct) {
                   8260: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8261: 				     $line,'missingbubble',\@to_correct,
                   8262:                                      $randomorder,$randompick,\%respnumlookup,
                   8263:                                      \%startline);
1.157     albertel 8264: 	    return (1,$currentphase);
                   8265: 	}
                   8266: 
                   8267:     }
                   8268:     return (0,$currentphase+1);
                   8269: }
                   8270: 
1.663     raeburn  8271: sub hand_bubble_option {
                   8272:     my (undef, undef, $sequence) =
                   8273:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8274:     return if ($sequence eq '');
                   8275:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8276:     unless (ref($navmap)) {
                   8277:         return;
                   8278:     }
                   8279:     my $needs_hand_bubbles;
                   8280:     my $map=$navmap->getResourceByUrl($sequence);
                   8281:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8282:     foreach my $res (@resources) {
                   8283:         if (ref($res)) {
                   8284:             if ($res->is_problem()) {
                   8285:                 my $partlist = $res->parts();
                   8286:                 foreach my $part (@{ $partlist }) {
                   8287:                     my @types = $res->responseType($part);
                   8288:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8289:                         $needs_hand_bubbles = 1;
                   8290:                         last;
                   8291:                     }
                   8292:                 }
                   8293:             }
                   8294:         }
                   8295:     }
                   8296:     if ($needs_hand_bubbles) {
                   8297:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8298:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8299:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8300:                &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 />').
                   8301:                '<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  8302:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8303:     }
                   8304:     return;
                   8305: }
1.423     albertel 8306: 
1.82      albertel 8307: sub scantron_process_students {
1.608     www      8308:     my ($r,$symb) = @_;
1.513     foxr     8309: 
1.257     albertel 8310:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8311:     if (!$symb) {
                   8312: 	return '';
                   8313:     }
1.324     albertel 8314:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8315: 
1.257     albertel 8316:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8317:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8318:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8319:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8320:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8321:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8322:     unless (ref($navmap)) {
                   8323:         $r->print(&navmap_errormsg());
                   8324:         return '';
1.691     raeburn  8325:     }
1.83      albertel 8326:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8327:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8328:         %grader_randomlists_by_symb);
1.677     raeburn  8329:     if (ref($map)) {
                   8330:         $randomorder = $map->randomorder();
1.689     raeburn  8331:         $randompick = $map->randompick();
1.691     raeburn  8332:     } else {
                   8333:         $r->print(&navmap_errormsg());
                   8334:         return '';
1.677     raeburn  8335:     }
1.691     raeburn  8336:     my $nav_error;
1.83      albertel 8337:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8338:     if ($randomorder || $randompick) {
                   8339:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8340:         if ($nav_error) {
                   8341:             $r->print(&navmap_errormsg());
                   8342:             return '';
                   8343:         }
                   8344:     }
1.557     raeburn  8345:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8346:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8347: 
1.554     raeburn  8348:     my ($uname,$udom);
1.82      albertel 8349:     my $result= <<SCANTRONFORM;
1.81      albertel 8350: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8351:   <input type="hidden" name="command" value="scantron_configphase" />
                   8352:   $default_form_data
                   8353: SCANTRONFORM
1.82      albertel 8354:     $r->print($result);
                   8355: 
                   8356:     my @delayqueue;
1.542     raeburn  8357:     my (%completedstudents,%scandata);
1.140     albertel 8358:     
1.520     www      8359:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8360:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8361:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8362:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8363:     $r->print('<br />');
1.140     albertel 8364:     my $start=&Time::HiRes::time();
1.158     albertel 8365:     my $i=-1;
1.542     raeburn  8366:     my $started;
1.447     foxr     8367: 
1.649     raeburn  8368:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8369:     if ($nav_error) {
                   8370:         $r->print(&navmap_errormsg());
                   8371:         return '';
                   8372:     }
                   8373: 
1.513     foxr     8374:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8375:     # the user and return.
                   8376: 
                   8377:     if ($ssi_error) {
                   8378: 	$r->print("</form>");
                   8379: 	&ssi_print_error($r);
1.520     www      8380:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8381: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8382:     }
1.447     foxr     8383: 
1.542     raeburn  8384:     my %lettdig = &letter_to_digits();
                   8385:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8386:     my %orderedforcode;
1.542     raeburn  8387: 
1.157     albertel 8388:     while ($i<$scanlines->{'count'}) {
                   8389:  	($uname,$udom)=('','');
                   8390:  	$i++;
1.200     albertel 8391:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8392:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8393: 	if ($started) {
1.667     www      8394: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8395: 	}
                   8396: 	$started=1;
1.691     raeburn  8397:         my %respnumlookup = ();
                   8398:         my %startline = ();
                   8399:         my $total;
1.157     albertel 8400:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8401:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8402:                                                  $randompick,$sequence,\@master_seq,
                   8403:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8404:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8405:                                                  \$total);
1.157     albertel 8406:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8407:  					      \%idmap,$i)) {
                   8408:   	    &scantron_add_delay(\@delayqueue,$line,
                   8409:  				'Unable to find a student that matches',1);
                   8410:  	    next;
                   8411:   	}
                   8412:  	if (exists $completedstudents{$uname}) {
                   8413:  	    &scantron_add_delay(\@delayqueue,$line,
                   8414:  				'Student '.$uname.' has multiple sheets',2);
                   8415:  	    next;
                   8416:  	}
1.677     raeburn  8417:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8418:         my $user = $uname.':'.$usec;
1.157     albertel 8419:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8420: 
1.677     raeburn  8421:         my $scancode;
                   8422:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8423:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8424:             $scancode = $scan_record->{'scantron.CODE'};
                   8425:         } else {
                   8426:             $scancode = '';
                   8427:         }
                   8428: 
                   8429:         my @mapresources = @resources;
1.689     raeburn  8430:         if ($randomorder || $randompick) {
1.678     raeburn  8431:             @mapresources = 
1.691     raeburn  8432:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8433:                              \%orderedforcode);
1.677     raeburn  8434:         }
1.586     raeburn  8435:         my (%partids_by_symb,$res_error);
1.677     raeburn  8436:         foreach my $resource (@mapresources) {
1.586     raeburn  8437:             my $ressymb;
                   8438:             if (ref($resource)) {
                   8439:                 $ressymb = $resource->symb();
                   8440:             } else {
                   8441:                 $res_error = 1;
                   8442:                 last;
                   8443:             }
1.557     raeburn  8444:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8445:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8446:                 my ($analysis,$parts) =
1.672     raeburn  8447:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8448:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8449:                 $partids_by_symb{$ressymb} = $parts;
                   8450:             } else {
                   8451:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8452:             }
1.554     raeburn  8453:         }
                   8454: 
1.586     raeburn  8455:         if ($res_error) {
                   8456:             &scantron_add_delay(\@delayqueue,$line,
                   8457:                                 'An error occurred while grading student '.$uname,2);
                   8458:             next;
                   8459:         }
                   8460: 
1.330     albertel 8461: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8462:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8463: 
                   8464: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8465: 	    &scantron_putfile($scanlines,$scan_data);
                   8466: 	}
1.161     albertel 8467: 	
1.542     raeburn  8468:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8469:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8470:                                    $bubbles_per_row,$randomorder,$randompick,
                   8471:                                    \%respnumlookup,\%startline) 
                   8472:             eq 'ssi_error') {
1.542     raeburn  8473:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8474:             $r->print("</form>");
                   8475:             &ssi_print_error($r);
                   8476:             &Apache::lonnet::remove_lock($lock);
                   8477:             return '';      # Why return ''?  Beats me.
                   8478:         }
1.513     foxr     8479: 
1.692     raeburn  8480:         if (($scancode) && ($randomorder || $randompick)) {
                   8481:             my $parmresult =
                   8482:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8483:                                                        '0_examcode',2,$scancode,
                   8484:                                                        'string_examcode',$uname,
                   8485:                                                        $udom);
                   8486:         }
1.140     albertel 8487: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8488:         if ($env{'form.verifyrecord'}) {
                   8489:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8490:             if ($randompick) {
                   8491:                 if ($total) {
                   8492:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8493:                 }
                   8494:             }
                   8495: 
1.542     raeburn  8496:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8497:             chomp($studentdata);
                   8498:             $studentdata =~ s/\r$//;
                   8499:             my $studentrecord = '';
                   8500:             my $counter = -1;
1.677     raeburn  8501:             foreach my $resource (@mapresources) {
1.554     raeburn  8502:                 my $ressymb = $resource->symb();
1.542     raeburn  8503:                 ($counter,my $recording) =
                   8504:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8505:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8506:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8507:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8508:                 $studentrecord .= $recording;
                   8509:             }
                   8510:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8511:                 &Apache::lonxml::clear_problem_counter();
                   8512:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8513:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8514:                                            $bubbles_per_row,$randomorder,$randompick,
                   8515:                                            \%respnumlookup,\%startline) 
                   8516:                     eq 'ssi_error') {
1.554     raeburn  8517:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8518:                     $r->print("</form>");
                   8519:                     &ssi_print_error($r);
                   8520:                     &Apache::lonnet::remove_lock($lock);
                   8521:                     delete($completedstudents{$uname});
                   8522:                     return '';
                   8523:                 }
1.542     raeburn  8524:                 $counter = -1;
                   8525:                 $studentrecord = '';
1.677     raeburn  8526:                 foreach my $resource (@mapresources) {
1.554     raeburn  8527:                     my $ressymb = $resource->symb();
1.542     raeburn  8528:                     ($counter,my $recording) =
                   8529:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8530:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8531:                                                  \%scantron_config,\%lettdig,$numletts,
                   8532:                                                  $randomorder,$randompick,\%respnumlookup,
                   8533:                                                  \%startline);
1.542     raeburn  8534:                     $studentrecord .= $recording;
                   8535:                 }
                   8536:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8537:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8538:                     if ($scancode eq '') {
1.658     bisitz   8539:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8540:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8541:                     } else {
1.658     bisitz   8542:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8543:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8544:                     }
                   8545:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8546:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8547:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8548:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8549:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8550:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8551:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8552:                               &Apache::loncommon::end_data_table_row().
                   8553:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8554:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8555:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8556:                               &Apache::loncommon::end_data_table_row().
                   8557:                               &Apache::loncommon::end_data_table().'</p>');
                   8558:                 } else {
                   8559:                     $r->print('<br /><span class="LC_warning">'.
                   8560:                              &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 />'.
                   8561:                              &mt("As a consequence, this user's submission history records two tries.").
                   8562:                                  '</span><br />');
                   8563:                 }
                   8564:             }
                   8565:         }
1.543     raeburn  8566:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8567:     } continue {
1.330     albertel 8568: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8569: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8570:     }
1.140     albertel 8571:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8572:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8573: #    my $lasttime = &Time::HiRes::time()-$start;
                   8574: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8575: 
1.200     albertel 8576:     $r->print("</form>");
1.157     albertel 8577:     return '';
1.75      albertel 8578: }
1.157     albertel 8579: 
1.557     raeburn  8580: sub graders_resources_pass {
1.649     raeburn  8581:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8582:         $bubbles_per_row) = @_;
1.557     raeburn  8583:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8584:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8585:         foreach my $resource (@{$resources}) {
                   8586:             my $ressymb = $resource->symb();
                   8587:             my ($analysis,$parts) =
                   8588:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8589:                                           $env{'user.name'},$env{'user.domain'},
                   8590:                                           1,$bubbles_per_row);
1.557     raeburn  8591:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8592:             if (ref($analysis) eq 'HASH') {
                   8593:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8594:                     $grader_randomlists_by_symb->{$ressymb} =
                   8595:                         $analysis->{'parts_withrandomlist'};
                   8596:                 }
                   8597:             }
                   8598:         }
                   8599:     }
                   8600:     return;
                   8601: }
                   8602: 
1.678     raeburn  8603: =pod
                   8604: 
                   8605: =item users_order
                   8606: 
                   8607:   Returns array of resources in current map, ordered based on either CODE,
                   8608:   if this is a CODEd exam, or based on student's identity if this is a 
                   8609:   "NAMEd" exam.
                   8610: 
1.691     raeburn  8611:   Should be used when randomorder and/or randompick applied when the 
                   8612:   corresponding exam was printed, prior to students completing bubblesheets 
                   8613:   for the version of the exam the student received.
1.678     raeburn  8614: 
                   8615: =cut
                   8616: 
                   8617: sub users_order  {
1.691     raeburn  8618:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8619:     my @mapresources;
1.691     raeburn  8620:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8621:         return @mapresources;
1.691     raeburn  8622:     }
                   8623:     if ($scancode) {
                   8624:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8625:             @mapresources = @{$orderedforcode->{$scancode}};
                   8626:         } else {
                   8627:             $env{'form.CODE'} = $scancode;
                   8628:             my $actual_seq =
                   8629:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8630:                                                                $master_seq,
                   8631:                                                                $user,$scancode,1);
                   8632:             if (ref($actual_seq) eq 'ARRAY') {
                   8633:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8634:                 if (ref($orderedforcode) eq 'HASH') {
                   8635:                     if (@mapresources > 0) { 
                   8636:                         $orderedforcode->{$scancode} = \@mapresources;
                   8637:                     }
                   8638:                 }
                   8639:             }
                   8640:             delete($env{'form.CODE'});
1.678     raeburn  8641:         }
                   8642:     } else {
                   8643:         my $actual_seq =
                   8644:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8645:                                                            $master_seq,
1.688     raeburn  8646:                                                            $user,undef,1);
1.678     raeburn  8647:         if (ref($actual_seq) eq 'ARRAY') {
                   8648:             @mapresources = 
                   8649:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8650:         }
1.691     raeburn  8651:     }
                   8652:     return @mapresources;
1.678     raeburn  8653: }
                   8654: 
1.542     raeburn  8655: sub grade_student_bubbles {
1.691     raeburn  8656:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8657:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8658:     my $uselookup = 0;
                   8659:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8660:         (ref($startline) eq 'HASH')) {
                   8661:         $uselookup = 1;
                   8662:     }
                   8663: 
1.554     raeburn  8664:     if (ref($resources) eq 'ARRAY') {
                   8665:         my $count = 0;
                   8666:         foreach my $resource (@{$resources}) {
                   8667:             my $ressymb = $resource->symb();
                   8668:             my %form = ('submitted'      => 'scantron',
                   8669:                         'grade_target'   => 'grade',
                   8670:                         'grade_username' => $uname,
                   8671:                         'grade_domain'   => $udom,
                   8672:                         'grade_courseid' => $env{'request.course.id'},
                   8673:                         'grade_symb'     => $ressymb,
                   8674:                         'CODE'           => $scancode
                   8675:                        );
1.649     raeburn  8676:             if ($bubbles_per_row ne '') {
                   8677:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8678:             }
1.663     raeburn  8679:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8680:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8681:             }
1.554     raeburn  8682:             if (ref($parts) eq 'HASH') {
                   8683:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8684:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8685:                         if ($uselookup) {
                   8686:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8687:                         } else {
                   8688:                             $form{'scantron_questnum_start.'.$part} =
                   8689:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8690:                         }
1.554     raeburn  8691:                         $count++;
                   8692:                     }
                   8693:                 }
                   8694:             }
                   8695:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8696:             return 'ssi_error' if ($ssi_error);
                   8697:             last if (&Apache::loncommon::connection_aborted($r));
                   8698:         }
1.542     raeburn  8699:     }
                   8700:     return;
                   8701: }
                   8702: 
1.157     albertel 8703: sub scantron_upload_scantron_data {
1.608     www      8704:     my ($r,$symb)=@_;
1.565     raeburn  8705:     my $dom = $env{'request.role.domain'};
                   8706:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8707:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8708:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8709: 							  'domainid',
1.565     raeburn  8710: 							  'coursename',$dom);
                   8711:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8712:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8713:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8714:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  8715:     &js_escape(\$nofile_alert);
1.579     raeburn  8716:     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.736     damieng  8717:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 8718:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8719:     function checkUpload(formname) {
                   8720: 	if (formname.upfile.value == "") {
1.579     raeburn  8721: 	    alert("'.$nofile_alert.'");
1.157     albertel 8722: 	    return false;
                   8723: 	}
1.565     raeburn  8724:         if (formname.courseid.value == "") {
1.579     raeburn  8725:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8726:             return false;
                   8727:         }
1.157     albertel 8728: 	formname.submit();
                   8729:     }
1.565     raeburn  8730: 
                   8731:     function ToSyllabus() {
                   8732:         var cdom = '."'$dom'".';
                   8733:         var cnum = document.rules.courseid.value;
                   8734:         if (cdom == "" || cdom == null) {
                   8735:             return;
                   8736:         }
                   8737:         if (cnum == "" || cnum == null) {
                   8738:            return;
                   8739:         }
                   8740:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8741:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8742:         return;
                   8743:     }
                   8744: 
1.597     wenzelju 8745: '));
                   8746:     $r->print('
1.648     bisitz   8747: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8748: 
1.492     albertel 8749: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8750: '.$default_form_data.
                   8751:   &Apache::lonhtmlcommon::start_pick_box().
                   8752:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8753:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8754:   &Apache::lonhtmlcommon::row_closure().
                   8755:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8756:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8757:   &Apache::lonhtmlcommon::row_closure().
                   8758:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8759:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8760:   &Apache::lonhtmlcommon::row_closure().
                   8761:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8762:   '<input type="file" name="upfile" size="50" />'.
                   8763:   &Apache::lonhtmlcommon::row_closure(1).
                   8764:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8765: 
1.492     albertel 8766: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8767: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8768: </form>
1.492     albertel 8769: ');
1.157     albertel 8770:     return '';
                   8771: }
                   8772: 
1.423     albertel 8773: 
1.157     albertel 8774: sub scantron_upload_scantron_data_save {
1.608     www      8775:     my($r,$symb)=@_;
1.182     albertel 8776:     my $doanotherupload=
                   8777: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8778: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8779: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8780: 	'</form>'."\n";
1.257     albertel 8781:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8782: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8783: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8784: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8785: 	unless ($symb) {
1.182     albertel 8786: 	    $r->print($doanotherupload);
                   8787: 	}
1.162     albertel 8788: 	return '';
                   8789:     }
1.257     albertel 8790:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8791:     my $uploadedfile;
1.710     bisitz   8792:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8793:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8794:         $r->print(
                   8795:             &Apache::lonhtmlcommon::confirm_success(
                   8796:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8797:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8798:     } else {
1.568     raeburn  8799:         my $result = 
                   8800:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8801:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8802:         if ($result =~ m{^/uploaded/}) {
                   8803:             $r->print(
                   8804:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8805:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8806:                         (length($env{'form.upfile'})-1),
                   8807:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8808:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8809:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8810:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8811:         } else {
                   8812:             $r->print(
                   8813:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8814:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8815:                           $result,
1.568     raeburn  8816: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8817: 	}
                   8818:     }
1.174     albertel 8819:     if ($symb) {
1.612     www      8820: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8821:     } else {
1.182     albertel 8822: 	$r->print($doanotherupload);
1.174     albertel 8823:     }
1.157     albertel 8824:     return '';
                   8825: }
                   8826: 
1.567     raeburn  8827: sub validate_uploaded_scantron_file {
                   8828:     my ($cdom,$cname,$fname) = @_;
                   8829:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8830:     my @lines;
                   8831:     if ($scanlines ne '-1') {
                   8832:         @lines=split("\n",$scanlines,-1);
                   8833:     }
                   8834:     my $output;
                   8835:     if (@lines) {
                   8836:         my (%counts,$max_match_format);
1.710     bisitz   8837:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8838:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8839:         my %idmap = &username_to_idmap($classlist);
                   8840:         foreach my $key (keys(%idmap)) {
                   8841:             my $lckey = lc($key);
                   8842:             $idmap{$lckey} = $idmap{$key};
                   8843:         }
                   8844:         my %unique_formats;
                   8845:         my @formatlines = &get_scantronformat_file();
                   8846:         foreach my $line (@formatlines) {
                   8847:             chomp($line);
                   8848:             my @config = split(/:/,$line);
                   8849:             my $idstart = $config[5];
                   8850:             my $idlength = $config[6];
                   8851:             if (($idstart ne '') && ($idlength > 0)) {
                   8852:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8853:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8854:                 } else {
                   8855:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8856:                 }
                   8857:             }
                   8858:         }
                   8859:         foreach my $key (keys(%unique_formats)) {
                   8860:             my ($idstart,$idlength) = split(':',$key);
                   8861:             %{$counts{$key}} = (
                   8862:                                'found'   => 0,
                   8863:                                'total'   => 0,
                   8864:                               );
                   8865:             foreach my $line (@lines) {
                   8866:                 next if ($line =~ /^#/);
                   8867:                 next if ($line =~ /^[\s\cz]*$/);
                   8868:                 my $id = substr($line,$idstart-1,$idlength);
                   8869:                 $id = lc($id);
                   8870:                 if (exists($idmap{$id})) {
                   8871:                     $counts{$key}{'found'} ++;
                   8872:                 }
                   8873:                 $counts{$key}{'total'} ++;
                   8874:             }
                   8875:             if ($counts{$key}{'total'}) {
                   8876:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8877:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8878:                     $max_match_pct = $percent_match;
                   8879:                     $max_match_format = $key;
1.710     bisitz   8880:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8881:                     $max_match_count = $counts{$key}{'total'};
                   8882:                 }
                   8883:             }
                   8884:         }
                   8885:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8886:             my $format_descs;
                   8887:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8888:             for (my $i=0; $i<$numwithformat; $i++) {
                   8889:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8890:                 if ($i<$numwithformat-2) {
                   8891:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8892:                 } elsif ($i==$numwithformat-2) {
                   8893:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8894:                 } elsif ($i==$numwithformat-1) {
                   8895:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8896:                 }
                   8897:             }
                   8898:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8899:             $output .= '<br />';
                   8900:             if ($found_match_count == $max_match_count) {
                   8901:                 # 100% matching entries
                   8902:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8903:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8904:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8905:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8906:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8907:                     ' in the file (for the format defined for [_3]).',
                   8908:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8909:             } else {
                   8910:                 # Not all entries matching? -> Show warning and additional info
                   8911:                 $output .=
                   8912:                     &Apache::lonhtmlcommon::confirm_success(
                   8913:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8914:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8915:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8916:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8917:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8918:                         ' in the file (for the format defined for [_3]).',
                   8919:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8920:                     '<p class="LC_info">'.
                   8921:                     &mt('A low percentage of matches results from one of the following:').
                   8922:                     '</p><ul>'.
                   8923:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8924:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8925:                                '<i>'.$cdom.'</i>').'</li>'.
                   8926:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8927:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8928:                     '</ul>';
                   8929:             }
1.567     raeburn  8930:         }
                   8931:     } else {
1.710     bisitz   8932:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8933:     }
                   8934:     return $output;
                   8935: }
                   8936: 
1.202     albertel 8937: sub valid_file {
                   8938:     my ($requested_file)=@_;
                   8939:     foreach my $filename (sort(&scantron_filenames())) {
                   8940: 	if ($requested_file eq $filename) { return 1; }
                   8941:     }
                   8942:     return 0;
                   8943: }
                   8944: 
                   8945: sub scantron_download_scantron_data {
1.608     www      8946:     my ($r,$symb)=@_;
                   8947:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8948:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8949:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8950:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8951:     if (! &valid_file($file)) {
1.492     albertel 8952: 	$r->print('
1.202     albertel 8953: 	<p>
1.686     bisitz   8954: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8955:         </p>
1.492     albertel 8956: ');
1.202     albertel 8957: 	return;
                   8958:     }
                   8959:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8960:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8961:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8962:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8963:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8964:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8965:     $r->print('
1.202     albertel 8966:     <p>
1.723     raeburn  8967: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 8968: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8969:     </p>
                   8970:     <p>
1.492     albertel 8971: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8972: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8973:     </p>
                   8974:     <p>
1.492     albertel 8975: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8976: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8977:     </p>
1.492     albertel 8978: ');
1.202     albertel 8979:     return '';
                   8980: }
1.157     albertel 8981: 
1.523     raeburn  8982: sub checkscantron_results {
1.608     www      8983:     my ($r,$symb) = @_;
1.523     raeburn  8984:     if (!$symb) {return '';}
                   8985:     my $cid = $env{'request.course.id'};
1.542     raeburn  8986:     my %lettdig = &letter_to_digits();
1.523     raeburn  8987:     my $numletts = scalar(keys(%lettdig));
                   8988:     my $cnum = $env{'course.'.$cid.'.num'};
                   8989:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8990:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8991:     my %record;
                   8992:     my %scantron_config =
                   8993:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8994:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8995:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8996:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8997:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8998:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8999:     unless (ref($navmap)) {
                   9000:         $r->print(&navmap_errormsg());
                   9001:         return '';
                   9002:     }
1.523     raeburn  9003:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9004:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9005:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9006:     if (ref($map)) { 
                   9007:         $randomorder=$map->randomorder();
1.689     raeburn  9008:         $randompick=$map->randompick();
1.677     raeburn  9009:     }
1.557     raeburn  9010:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9011:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9012:     if ($nav_error) {
                   9013:         $r->print(&navmap_errormsg());
                   9014:         return '';
1.678     raeburn  9015:     }
1.673     raeburn  9016:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9017:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9018:     my ($uname,$udom);
1.523     raeburn  9019:     my (%scandata,%lastname,%bylast);
                   9020:     $r->print('
                   9021: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9022: 
                   9023:     my @delayqueue;
                   9024:     my %completedstudents;
                   9025: 
1.691     raeburn  9026:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9027:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9028:     my ($username,$domain,$started);
1.649     raeburn  9029:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9030:     if ($nav_error) {
                   9031:         $r->print(&navmap_errormsg());
                   9032:         return '';
                   9033:     }
1.523     raeburn  9034: 
1.667     www      9035:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9036:     my $start=&Time::HiRes::time();
                   9037:     my $i=-1;
                   9038: 
                   9039:     while ($i<$scanlines->{'count'}) {
                   9040:         ($username,$domain,$uname)=('','','');
                   9041:         $i++;
                   9042:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9043:         if ($line=~/^[\s\cz]*$/) { next; }
                   9044:         if ($started) {
1.667     www      9045:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9046:         }
                   9047:         $started=1;
                   9048:         my $scan_record=
                   9049:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9050:                                                      $scan_data);
1.693     raeburn  9051:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9052:                                               \%idmap,$i)) {
1.523     raeburn  9053:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9054:                                 'Unable to find a student that matches',1);
                   9055:             next;
                   9056:         }
                   9057:         if (exists $completedstudents{$uname}) {
                   9058:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9059:                                 'Student '.$uname.' has multiple sheets',2);
                   9060:             next;
                   9061:         }
                   9062:         my $pid = $scan_record->{'scantron.ID'};
                   9063:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9064:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9065:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9066:         my $user = $uname.':'.$usec;
1.523     raeburn  9067:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9068: 
1.678     raeburn  9069:         my $scancode;
1.677     raeburn  9070:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9071:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9072:             $scancode = $scan_record->{'scantron.CODE'};
                   9073:         } else {
                   9074:             $scancode = '';
                   9075:         }
                   9076: 
                   9077:         my @mapresources = @resources;
1.691     raeburn  9078:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9079:         my %respnumlookup=();
                   9080:         my %startline=();
1.689     raeburn  9081:         if ($randomorder || $randompick) {
1.678     raeburn  9082:             @mapresources =
1.691     raeburn  9083:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9084:                              \%orderedforcode);
                   9085:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9086:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9087:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9088:                                              \%respnumlookup,\%startline);
                   9089:             if ($randompick && $total) {
                   9090:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9091:             }
1.677     raeburn  9092:         }
1.691     raeburn  9093:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9094:         chomp($scandata{$pid});
                   9095:         $scandata{$pid} =~ s/\r$//;
                   9096: 
1.523     raeburn  9097:         my $counter = -1;
1.677     raeburn  9098:         foreach my $resource (@mapresources) {
1.557     raeburn  9099:             my $parts;
1.554     raeburn  9100:             my $ressymb = $resource->symb();
1.557     raeburn  9101:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9102:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9103:                 (my $analysis,$parts) =
1.672     raeburn  9104:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9105:                                               $username,$domain,undef,
                   9106:                                               $bubbles_per_row);
1.557     raeburn  9107:             } else {
                   9108:                 $parts = $grader_partids_by_symb{$ressymb};
                   9109:             }
1.542     raeburn  9110:             ($counter,my $recording) =
                   9111:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9112:                                          $scandata{$pid},$parts,
1.691     raeburn  9113:                                          \%scantron_config,\%lettdig,$numletts,
                   9114:                                          $randomorder,$randompick,
                   9115:                                          \%respnumlookup,\%startline);
1.542     raeburn  9116:             $record{$pid} .= $recording;
1.523     raeburn  9117:         }
                   9118:     }
                   9119:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9120:     $r->print('<br />');
                   9121:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9122:     $passed = 0;
                   9123:     $failed = 0;
                   9124:     $numstudents = 0;
                   9125:     foreach my $last (sort(keys(%bylast))) {
                   9126:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9127:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9128:                 my $showscandata = $scandata{$pid};
                   9129:                 my $showrecord = $record{$pid};
                   9130:                 $showscandata =~ s/\s/&nbsp;/g;
                   9131:                 $showrecord =~ s/\s/&nbsp;/g;
                   9132:                 if ($scandata{$pid} eq $record{$pid}) {
                   9133:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9134:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9135: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9136: '</tr>'."\n".
                   9137: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9138: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9139:                     $passed ++;
                   9140:                 } else {
                   9141:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9142:                     $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  9143: '</tr>'."\n".
                   9144: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9145: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9146: '</tr>'."\n";
                   9147:                     $failed ++;
                   9148:                 }
                   9149:                 $numstudents ++;
                   9150:             }
                   9151:         }
                   9152:     }
1.648     bisitz   9153:     $r->print(
                   9154:         '<p>'
                   9155:        .&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).',
                   9156:             '<b>',
                   9157:             $numstudents,
                   9158:             '</b>',
                   9159:             $env{'form.scantron_maxbubble'})
                   9160:        .'</p>'
                   9161:     );
1.682     raeburn  9162:     $r->print('<p>'
1.683     raeburn  9163:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9164:              .'<br />'
                   9165:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9166:              .'</p>'
                   9167:     );
1.523     raeburn  9168:     if ($passed) {
1.572     www      9169:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9170:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9171:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9172:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9173:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9174:                  $okstudents."\n".
                   9175:                  &Apache::loncommon::end_data_table().'<br />');
                   9176:     }
                   9177:     if ($failed) {
1.572     www      9178:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9179:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9180:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9181:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9182:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9183:                  $badstudents."\n".
                   9184:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9185:                  &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  9186:     }
1.614     www      9187:     $r->print('</form><br />');
1.523     raeburn  9188:     return;
                   9189: }
                   9190: 
1.542     raeburn  9191: sub verify_scantron_grading {
1.554     raeburn  9192:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9193:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9194:         $respnumlookup,$startline) = @_;
1.542     raeburn  9195:     my ($record,%expected,%startpos);
                   9196:     return ($counter,$record) if (!ref($resource));
                   9197:     return ($counter,$record) if (!$resource->is_problem());
                   9198:     my $symb = $resource->symb();
1.554     raeburn  9199:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9200:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9201:         $counter ++;
                   9202:         $expected{$part_id} = 0;
1.691     raeburn  9203:         my $respnum = $counter;
                   9204:         if ($randomorder || $randompick) {
                   9205:             $respnum = $respnumlookup->{$counter};
                   9206:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9207:         } else {
                   9208:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9209:         }
                   9210:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9211:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9212:             foreach my $item (@sub_lines) {
                   9213:                 $expected{$part_id} += $item;
                   9214:             }
                   9215:         } else {
1.691     raeburn  9216:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9217:         }
                   9218:     }
                   9219:     if ($symb) {
                   9220:         my %recorded;
                   9221:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9222:         if ($returnhash{'version'}) {
                   9223:             my %lasthash=();
                   9224:             my $version;
                   9225:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9226:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9227:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9228:                 }
                   9229:             }
                   9230:             foreach my $key (keys(%lasthash)) {
                   9231:                 if ($key =~ /\.scantron$/) {
                   9232:                     my $value = &unescape($lasthash{$key});
                   9233:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9234:                     if ($value eq '') {
                   9235:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9236:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9237:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9238:                             }
                   9239:                         }
                   9240:                     } else {
                   9241:                         my @tocheck;
                   9242:                         my @items = split(//,$value);
                   9243:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9244:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9245:                             if (@items < $expected{$part_id}) {
                   9246:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9247:                                 my @singles = split(//,$fragment);
                   9248:                                 foreach my $pos (@singles) {
                   9249:                                     if ($pos eq ' ') {
                   9250:                                         push(@tocheck,$pos);
                   9251:                                     } else {
                   9252:                                         my $next = shift(@items);
                   9253:                                         push(@tocheck,$next);
                   9254:                                     }
                   9255:                                 }
                   9256:                             } else {
                   9257:                                 @tocheck = @items;
                   9258:                             }
                   9259:                             foreach my $letter (@tocheck) {
                   9260:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9261:                                     if ($letter !~ /^[A-J]$/) {
                   9262:                                         $letter = $scantron_config->{'Qoff'};
                   9263:                                     }
                   9264:                                     $recorded{$part_id} .= $letter;
                   9265:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9266:                                     my $digit;
                   9267:                                     if ($letter !~ /^[A-J]$/) {
                   9268:                                         $digit = $scantron_config->{'Qoff'};
                   9269:                                     } else {
                   9270:                                         $digit = $lettdig->{$letter};
                   9271:                                     }
                   9272:                                     $recorded{$part_id} .= $digit;
                   9273:                                 }
                   9274:                             }
                   9275:                         } else {
                   9276:                             @tocheck = @items;
                   9277:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9278:                                 my $curr_sub = shift(@tocheck);
                   9279:                                 my $digit;
                   9280:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9281:                                     $digit = $lettdig->{$curr_sub}-1;
                   9282:                                 }
                   9283:                                 if ($curr_sub eq 'J') {
                   9284:                                     $digit += scalar($numletts);
                   9285:                                 }
                   9286:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9287:                                     if ($j == $digit) {
                   9288:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9289:                                     } else {
                   9290:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9291:                                     }
                   9292:                                 }
                   9293:                             }
                   9294:                         }
                   9295:                     }
                   9296:                 }
                   9297:             }
                   9298:         }
1.554     raeburn  9299:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9300:             if ($recorded{$part_id} eq '') {
                   9301:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9302:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9303:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9304:                     }
                   9305:                 }
                   9306:             }
                   9307:             $record .= $recorded{$part_id};
                   9308:         }
                   9309:     }
                   9310:     return ($counter,$record);
                   9311: }
                   9312: 
1.691     raeburn  9313: sub letter_to_digits {
1.542     raeburn  9314:     my %lettdig = (
                   9315:                     A => 1,
                   9316:                     B => 2,
                   9317:                     C => 3,
                   9318:                     D => 4,
                   9319:                     E => 5,
                   9320:                     F => 6,
                   9321:                     G => 7,
                   9322:                     H => 8,
                   9323:                     I => 9,
                   9324:                     J => 0,
                   9325:                   );
                   9326:     return %lettdig;
                   9327: }
                   9328: 
1.423     albertel 9329: 
1.75      albertel 9330: #-------- end of section for handling grading scantron forms -------
                   9331: #
                   9332: #-------------------------------------------------------------------
                   9333: 
1.72      ng       9334: #-------------------------- Menu interface -------------------------
                   9335: #
1.614     www      9336: #--- Href with symb and command ---
                   9337: 
                   9338: sub href_symb_cmd {
                   9339:     my ($symb,$cmd)=@_;
1.669     raeburn  9340:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9341: }
                   9342: 
1.443     banghart 9343: sub grading_menu {
1.608     www      9344:     my ($request,$symb) = @_;
1.443     banghart 9345:     if (!$symb) {return '';}
                   9346: 
                   9347:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9348:                   'command'=>'individual');
1.538     schulted 9349:     
1.598     www      9350:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9351: 
                   9352:     $fields{'command'}='ungraded';
                   9353:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9354: 
                   9355:     $fields{'command'}='table';
                   9356:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9357: 
                   9358:     $fields{'command'}='all_for_one';
                   9359:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9360: 
1.621     www      9361:     $fields{'command'}='downloadfilesselect';
                   9362:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9363: 
1.443     banghart 9364:     $fields{'command'} = 'csvform';
1.538     schulted 9365:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9366:     
1.443     banghart 9367:     $fields{'command'} = 'processclicker';
1.538     schulted 9368:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9369:     
1.443     banghart 9370:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9371:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9372: 
                   9373:     $fields{'command'} = 'initialverifyreceipt';
                   9374:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9375:     
1.598     www      9376:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9377:             items =>[
1.598     www      9378:                         {	linktext => 'Select individual students to grade',
                   9379:                     		url => $url1a,
1.538     schulted 9380:                     		permission => 'F',
1.636     wenzelju 9381:                     		icon => 'grade_students.png',
1.598     www      9382:                     		linktitle => 'Grade current resource for a selection of students.'
                   9383:                         }, 
                   9384:                         {       linktext => 'Grade ungraded submissions.',
                   9385:                                 url => $url1b,
                   9386:                                 permission => 'F',
1.636     wenzelju 9387:                                 icon => 'ungrade_sub.png',
1.598     www      9388:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9389:                         },
1.598     www      9390: 
                   9391:                         {       linktext => 'Grading table',
                   9392:                                 url => $url1c,
                   9393:                                 permission => 'F',
1.636     wenzelju 9394:                                 icon => 'grading_table.png',
1.598     www      9395:                                 linktitle => 'Grade current resource for all students.'
                   9396:                         },
1.615     www      9397:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9398:                                 url => $url1d,
                   9399:                                 permission => 'F',
1.636     wenzelju 9400:                                 icon => 'grade_PageFolder.png',
1.598     www      9401:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9402:                         },
                   9403:                         {       linktext => 'Download submissions',
                   9404:                                 url => $url1e,
                   9405:                                 permission => 'F',
1.636     wenzelju 9406:                                 icon => 'download_sub.png',
1.621     www      9407:                                 linktitle => 'Download all students submissions.'
1.598     www      9408:                         }]},
                   9409:                          { categorytitle=>'Automated Grading',
                   9410:                items =>[
                   9411: 
1.538     schulted 9412:                 	    {	linktext => 'Upload Scores',
                   9413:                     		url => $url2,
                   9414:                     		permission => 'F',
                   9415:                     		icon => 'uploadscores.png',
                   9416:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9417:                 	    },
                   9418:                 	    {	linktext => 'Process Clicker',
                   9419:                     		url => $url3,
                   9420:                     		permission => 'F',
                   9421:                     		icon => 'addClickerInfoFile.png',
                   9422:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9423:                 	    },
1.587     raeburn  9424:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9425:                     		url => $url4,
                   9426:                     		permission => 'F',
1.636     wenzelju 9427:                     		icon => 'bubblesheet.png',
1.648     bisitz   9428:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9429:                 	    },
1.616     www      9430:                             {   linktext => 'Verify Receipt Number',
1.602     www      9431:                                 url => $url5,
                   9432:                                 permission => 'F',
1.636     wenzelju 9433:                                 icon => 'receipt_number.png',
1.602     www      9434:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9435:                             }
                   9436: 
1.538     schulted 9437:                     ]
                   9438:             });
                   9439: 
1.443     banghart 9440:     # Create the menu
                   9441:     my $Str;
1.445     banghart 9442:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9443:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9444:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9445: 
1.602     www      9446:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9447:     return $Str;    
                   9448: }
                   9449: 
1.598     www      9450: 
                   9451: sub ungraded {
                   9452:     my ($request)=@_;
                   9453:     &submit_options($request);
                   9454: }
                   9455: 
1.599     www      9456: sub submit_options_sequence {
1.608     www      9457:     my ($request,$symb) = @_;
1.599     www      9458:     if (!$symb) {return '';}
1.600     www      9459:     &commonJSfunctions($request);
                   9460:     my $result;
1.599     www      9461: 
1.600     www      9462:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9463:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9464:     $result.=&selectfield(0).
1.601     www      9465:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9466:             <div>
                   9467:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9468:             </div>
                   9469:         </div>
                   9470:   </form>';
                   9471:     return $result;
                   9472: }
                   9473: 
                   9474: sub submit_options_table {
1.608     www      9475:     my ($request,$symb) = @_;
1.600     www      9476:     if (!$symb) {return '';}
1.599     www      9477:     &commonJSfunctions($request);
                   9478:     my $result;
                   9479: 
                   9480:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9481:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9482: 
1.632     www      9483:     $result.=&selectfield(0).
1.601     www      9484:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9485:             <div>
                   9486:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9487:             </div>
                   9488:         </div>
                   9489:   </form>';
                   9490:     return $result;
                   9491: }
1.443     banghart 9492: 
1.621     www      9493: sub submit_options_download {
                   9494:     my ($request,$symb) = @_;
                   9495:     if (!$symb) {return '';}
                   9496: 
                   9497:     &commonJSfunctions($request);
                   9498: 
                   9499:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9500:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9501:     $result.='
                   9502: <h2>
                   9503:   '.&mt('Select Students for Which to Download Submissions').'
                   9504: </h2>'.&selectfield(1).'
                   9505:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9506:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9507:             </div>
                   9508:           </div>
1.600     www      9509: 
                   9510: 
1.621     www      9511:   </form>';
                   9512:     return $result;
                   9513: }
                   9514: 
1.443     banghart 9515: #--- Displays the submissions first page -------
                   9516: sub submit_options {
1.608     www      9517:     my ($request,$symb) = @_;
1.72      ng       9518:     if (!$symb) {return '';}
                   9519: 
1.118     ng       9520:     &commonJSfunctions($request);
1.473     albertel 9521:     my $result;
1.533     bisitz   9522: 
1.72      ng       9523:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9524: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9525:     $result.=&selectfield(1).'
1.601     www      9526:                 <input type="hidden" name="command" value="submission" /> 
                   9527: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9528:             </div>
                   9529:           </div>
                   9530: 
                   9531: 
                   9532:   </form>';
                   9533:     return $result;
                   9534: }
1.533     bisitz   9535: 
1.601     www      9536: sub selectfield {
                   9537:    my ($full)=@_;
1.635     raeburn  9538:    my %options = 
                   9539:           (&Apache::lonlocal::texthash(
                   9540:              'yes'       => 'with submissions',
                   9541:              'queued'    => 'in grading queue',
                   9542:              'graded'    => 'with ungraded submissions',
                   9543:              'incorrect' => 'with incorrect submissions',
                   9544:              'all'       => 'with any status'),
                   9545:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9546:    my $result='<div class="LC_columnSection">
1.537     harmsja  9547:   
1.533     bisitz   9548:     <fieldset>
                   9549:       <legend>
                   9550:        '.&mt('Sections').'
                   9551:       </legend>
1.601     www      9552:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9553:     </fieldset>
1.537     harmsja  9554:   
1.533     bisitz   9555:     <fieldset>
                   9556:       <legend>
                   9557:         '.&mt('Groups').'
                   9558:       </legend>
                   9559:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9560:     </fieldset>
1.537     harmsja  9561:   
1.533     bisitz   9562:     <fieldset>
                   9563:       <legend>
                   9564:         '.&mt('Access Status').'
                   9565:       </legend>
1.601     www      9566:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9567:     </fieldset>';
                   9568:     if ($full) {
                   9569:        $result.='
1.533     bisitz   9570:     <fieldset>
                   9571:       <legend>
                   9572:         '.&mt('Submission Status').'
1.601     www      9573:       </legend>'.
1.635     raeburn  9574:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9575:    '</fieldset>';
                   9576:     }
                   9577:     $result.='</div><br />';
1.44      ng       9578:     return $result;
1.2       albertel 9579: }
                   9580: 
1.285     albertel 9581: sub reset_perm {
                   9582:     undef(%perm);
                   9583: }
                   9584: 
                   9585: sub init_perm {
                   9586:     &reset_perm();
1.300     albertel 9587:     foreach my $test_perm ('vgr','mgr','opa') {
                   9588: 
                   9589: 	my $scope = $env{'request.course.id'};
                   9590: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9591: 
                   9592: 	    $scope .= '/'.$env{'request.course.sec'};
                   9593: 	    if ( $perm{$test_perm}=
                   9594: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9595: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9596: 	    } else {
                   9597: 		delete($perm{$test_perm});
                   9598: 	    }
1.285     albertel 9599: 	}
                   9600:     }
                   9601: }
                   9602: 
1.674     raeburn  9603: sub init_old_essays {
                   9604:     my ($symb,$apath,$adom,$aname) = @_;
                   9605:     if ($symb ne '') {
                   9606:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9607:         if (keys(%essays) > 0) {
                   9608:             $old_essays{$symb} = \%essays;
                   9609:         }
                   9610:     }
                   9611:     return;
                   9612: }
                   9613: 
                   9614: sub reset_old_essays {
                   9615:     undef(%old_essays);
                   9616: }
                   9617: 
1.400     www      9618: sub gather_clicker_ids {
1.408     albertel 9619:     my %clicker_ids;
1.400     www      9620: 
                   9621:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9622: 
                   9623:     # Set up a couple variables.
1.407     albertel 9624:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9625:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9626:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9627: 
1.407     albertel 9628:     foreach my $student (keys(%$classlist)) {
1.438     www      9629:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9630:         my $username = $classlist->{$student}->[$username_idx];
                   9631:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9632:         my $clickers =
1.408     albertel 9633: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9634:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9635:             $id=~s/^[\#0]+//;
1.421     www      9636:             $id=~s/[\-\:]//g;
1.407     albertel 9637:             if (exists($clicker_ids{$id})) {
1.408     albertel 9638: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9639:             } else {
1.408     albertel 9640: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9641:             }
                   9642:         }
                   9643:     }
1.407     albertel 9644:     return %clicker_ids;
1.400     www      9645: }
                   9646: 
1.402     www      9647: sub gather_adv_clicker_ids {
1.408     albertel 9648:     my %clicker_ids;
1.402     www      9649:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9650:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9651:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9652:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9653:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9654:             my ($puname,$pudom)=split(/\:/,$person);
                   9655:             my $clickers =
1.408     albertel 9656: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9657:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9658: 		$id=~s/^[\#0]+//;
1.421     www      9659:                 $id=~s/[\-\:]//g;
1.408     albertel 9660: 		if (exists($clicker_ids{$id})) {
                   9661: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9662: 		} else {
                   9663: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9664: 		}
1.405     www      9665:             }
1.402     www      9666:         }
                   9667:     }
1.407     albertel 9668:     return %clicker_ids;
1.402     www      9669: }
                   9670: 
1.413     www      9671: sub clicker_grading_parameters {
                   9672:     return ('gradingmechanism' => 'scalar',
                   9673:             'upfiletype' => 'scalar',
                   9674:             'specificid' => 'scalar',
                   9675:             'pcorrect' => 'scalar',
                   9676:             'pincorrect' => 'scalar');
                   9677: }
                   9678: 
1.400     www      9679: sub process_clicker {
1.608     www      9680:     my ($r,$symb)=@_;
1.400     www      9681:     if (!$symb) {return '';}
                   9682:     my $result=&checkforfile_js();
1.632     www      9683:     $result.=&Apache::loncommon::start_data_table().
                   9684:              &Apache::loncommon::start_data_table_header_row().
                   9685:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9686:              &Apache::loncommon::end_data_table_header_row().
                   9687:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9688: # Attempt to restore parameters from last session, set defaults if not present
                   9689:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9690:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9691:                                                  \%Saveable_Parameters);
                   9692:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9693:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9694:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9695:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9696: 
                   9697:     my %checked;
1.521     www      9698:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9699:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9700:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9701:        }
                   9702:     }
                   9703: 
1.632     www      9704:     my $upload=&mt("Evaluate File");
1.400     www      9705:     my $type=&mt("Type");
1.402     www      9706:     my $attendance=&mt("Award points just for participation");
                   9707:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9708:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9709:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9710:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9711:     my $pcorrect=&mt("Percentage points for correct solution");
                   9712:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9713:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9714: 						   {'iclicker' => 'i>clicker',
1.666     www      9715:                                                     'interwrite' => 'interwrite PRS',
                   9716:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9717:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9718:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9719: function sanitycheck() {
                   9720: // Accept only integer percentages
                   9721:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9722:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9723: // Find out grading choice
                   9724:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9725:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9726:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9727:       }
                   9728:    }
                   9729: // By default, new choice equals user selection
                   9730:    newgradingchoice=gradingchoice;
                   9731: // Not good to give more points for false answers than correct ones
                   9732:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9733:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9734:    }
                   9735: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9736:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9737:       document.forms.gradesupload.pcorrect.value=100;
                   9738:       document.forms.gradesupload.pincorrect.value=100;
                   9739:    }
                   9740: // If the values are different, cannot be attendance only
                   9741:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9742:        (gradingchoice=='attendance')) {
                   9743:        newgradingchoice='personnel';
                   9744:    }
                   9745: // Change grading choice to new one
                   9746:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9747:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9748:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9749:       } else {
                   9750:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9751:       }
                   9752:    }
                   9753: // Remember the old state
                   9754:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9755: }
1.597     wenzelju 9756: ENDUPFORM
                   9757:     $result.= <<ENDUPFORM;
1.400     www      9758: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9759: <input type="hidden" name="symb" value="$symb" />
                   9760: <input type="hidden" name="command" value="processclickerfile" />
                   9761: <input type="file" name="upfile" size="50" />
                   9762: <br /><label>$type: $selectform</label>
1.632     www      9763: ENDUPFORM
                   9764:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9765:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9766:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9767: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9768: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9769: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9770: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9771: <br />&nbsp;&nbsp;&nbsp;
                   9772: <input type="text" name="givenanswer" size="50" />
1.413     www      9773: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9774: ENDGRADINGFORM
                   9775:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9776:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9777:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9778: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9779: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9780: </form>'
1.632     www      9781: ENDPERCFORM
                   9782:     $result.='</td>'.
                   9783:              &Apache::loncommon::end_data_table_row().
                   9784:              &Apache::loncommon::end_data_table();
1.400     www      9785:     return $result;
                   9786: }
                   9787: 
                   9788: sub process_clicker_file {
1.608     www      9789:     my ($r,$symb)=@_;
1.400     www      9790:     if (!$symb) {return '';}
1.413     www      9791: 
                   9792:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9793:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9794:                                               \%Saveable_Parameters);
1.598     www      9795:     my $result='';
1.404     www      9796:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9797: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9798: 	return $result;
1.404     www      9799:     }
1.522     www      9800:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9801:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9802:         return $result;
1.521     www      9803:     }
1.522     www      9804:     my $foundgiven=0;
1.521     www      9805:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9806:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9807:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9808:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9809:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9810:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9811:         $foundgiven=$#answers+1;
1.521     www      9812:     }
1.407     albertel 9813:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9814:     my %correct_ids;
1.404     www      9815:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9816: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9817:     }
                   9818:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9819: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9820: 	   $correct_id=~tr/a-z/A-Z/;
                   9821: 	   $correct_id=~s/\s//gs;
                   9822: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9823:            $correct_id=~s/[\-\:]//g;
1.414     www      9824:            if ($correct_id) {
                   9825: 	      $correct_ids{$correct_id}='specified';
                   9826:            }
                   9827:         }
1.400     www      9828:     }
1.404     www      9829:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9830: 	$result.=&mt('Score based on attendance only');
1.521     www      9831:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9832:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9833:     } else {
1.408     albertel 9834: 	my $number=0;
1.411     www      9835: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9836: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9837: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9838: 	    if ($correct_ids{$id} eq 'specified') {
                   9839: 		$result.=&mt('specified');
                   9840: 	    } else {
                   9841: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9842: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9843: 	    }
                   9844: 	    $number++;
                   9845: 	}
1.411     www      9846:         $result.="</p>\n";
1.710     bisitz   9847:         if ($number==0) {
                   9848:             $result .=
                   9849:                  &Apache::lonhtmlcommon::confirm_success(
                   9850:                      &mt('No IDs found to determine correct answer'),1);
                   9851:             return $result;
                   9852:         }
1.404     www      9853:     }
1.405     www      9854:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9855:         $result .=
                   9856:             &Apache::lonhtmlcommon::confirm_success(
                   9857:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9858:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9859:         return $result;
1.405     www      9860:     }
1.410     www      9861: 
                   9862: # Were able to get all the info needed, now analyze the file
                   9863: 
1.411     www      9864:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9865:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9866:     $result.=&Apache::loncommon::start_data_table().
                   9867:              &Apache::loncommon::start_data_table_header_row().
                   9868:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9869:              &Apache::loncommon::end_data_table_header_row().
                   9870:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9871: <td>
1.410     www      9872: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9873: <input type="hidden" name="symb" value="$symb" />
                   9874: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9875: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9876: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9877: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9878: ENDHEADER
1.522     www      9879:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9880:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9881:     } 
1.408     albertel 9882:     my %responses;
                   9883:     my @questiontitles;
1.405     www      9884:     my $errormsg='';
                   9885:     my $number=0;
                   9886:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9887: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9888:     }
1.419     www      9889:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9890:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9891:     }
1.666     www      9892:     if ($env{'form.upfiletype'} eq 'turning') {
                   9893:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9894:     }
1.411     www      9895:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9896:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9897:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9898:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9899:              '<br />';
1.522     www      9900:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9901:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9902:        return $result;
1.522     www      9903:     } 
1.414     www      9904: # Remember Question Titles
                   9905: # FIXME: Possibly need delimiter other than ":"
                   9906:     for (my $i=0;$i<$number;$i++) {
                   9907:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9908:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9909:     }
1.411     www      9910:     my $correct_count=0;
                   9911:     my $student_count=0;
                   9912:     my $unknown_count=0;
1.414     www      9913: # Match answers with usernames
                   9914: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9915:     foreach my $id (keys(%responses)) {
1.410     www      9916:        if ($correct_ids{$id}) {
1.414     www      9917:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9918:           $correct_count++;
1.410     www      9919:        } elsif ($clicker_ids{$id}) {
1.437     www      9920:           if ($clicker_ids{$id}=~/\,/) {
                   9921: # More than one user with the same clicker!
1.632     www      9922:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9923:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9924:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9925:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9926:                            "<select name='multi".$id."'>";
                   9927:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9928:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9929:              }
                   9930:              $result.='</select>';
                   9931:              $unknown_count++;
                   9932:           } else {
                   9933: # Good: found one and only one user with the right clicker
                   9934:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9935:              $student_count++;
                   9936:           }
1.410     www      9937:        } else {
1.632     www      9938:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9939:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9940:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9941:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9942:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9943:                    "\n".&mt("Domain").": ".
                   9944:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9945:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9946:           $unknown_count++;
1.410     www      9947:        }
1.405     www      9948:     }
1.412     www      9949:     $result.='<hr />'.
                   9950:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9951:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9952:        if ($correct_count==0) {
1.696     bisitz   9953:           $errormsg.="Found no correct answers for grading!";
1.412     www      9954:        } elsif ($correct_count>1) {
1.414     www      9955:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9956:        }
                   9957:     }
1.428     www      9958:     if ($number<1) {
                   9959:        $errormsg.="Found no questions.";
                   9960:     }
1.412     www      9961:     if ($errormsg) {
                   9962:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9963:     } else {
                   9964:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9965:     }
1.632     www      9966:     $result.='</form></td>'.
                   9967:              &Apache::loncommon::end_data_table_row().
                   9968:              &Apache::loncommon::end_data_table();
1.614     www      9969:     return $result;
1.400     www      9970: }
                   9971: 
1.405     www      9972: sub iclicker_eval {
1.406     www      9973:     my ($questiontitles,$responses)=@_;
1.405     www      9974:     my $number=0;
                   9975:     my $errormsg='';
                   9976:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9977:         my %components=&Apache::loncommon::record_sep($line);
                   9978:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9979: 	if ($entries[0] eq 'Question') {
                   9980: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9981: 		$$questiontitles[$number]=$entries[$i];
                   9982: 		$number++;
                   9983: 	    }
                   9984: 	}
                   9985: 	if ($entries[0]=~/^\#/) {
                   9986: 	    my $id=$entries[0];
                   9987: 	    my @idresponses;
                   9988: 	    $id=~s/^[\#0]+//;
                   9989: 	    for (my $i=0;$i<$number;$i++) {
                   9990: 		my $idx=3+$i*6;
1.644     www      9991:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9992: 		push(@idresponses,$entries[$idx]);
                   9993: 	    }
                   9994: 	    $$responses{$id}=join(',',@idresponses);
                   9995: 	}
1.405     www      9996:     }
                   9997:     return ($errormsg,$number);
                   9998: }
                   9999: 
1.419     www      10000: sub interwrite_eval {
                   10001:     my ($questiontitles,$responses)=@_;
                   10002:     my $number=0;
                   10003:     my $errormsg='';
1.420     www      10004:     my $skipline=1;
                   10005:     my $questionnumber=0;
                   10006:     my %idresponses=();
1.419     www      10007:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10008:         my %components=&Apache::loncommon::record_sep($line);
                   10009:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10010:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10011:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10012:         next if $skipline;
                   10013:         if ($entries[0]!=$questionnumber) {
                   10014:            $questionnumber=$entries[0];
                   10015:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10016:            $number++;
1.419     www      10017:         }
1.420     www      10018:         my $id=$entries[4];
                   10019:         $id=~s/^[\#0]+//;
1.421     www      10020:         $id=~s/^v\d*\://i;
                   10021:         $id=~s/[\-\:]//g;
1.420     www      10022:         $idresponses{$id}[$number]=$entries[6];
                   10023:     }
1.524     raeburn  10024:     foreach my $id (keys(%idresponses)) {
1.420     www      10025:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10026:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10027:     }
                   10028:     return ($errormsg,$number);
                   10029: }
                   10030: 
1.666     www      10031: sub turning_eval {
                   10032:     my ($questiontitles,$responses)=@_;
                   10033:     my $number=0;
                   10034:     my $errormsg='';
                   10035:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10036:         my %components=&Apache::loncommon::record_sep($line);
                   10037:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10038:         if ($#entries>$number) { $number=$#entries; }
                   10039:         my $id=$entries[0];
                   10040:         my @idresponses;
                   10041:         $id=~s/^[\#0]+//;
                   10042:         unless ($id) { next; }
                   10043:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10044:             $entries[$idx]=~s/\,/\;/g;
                   10045:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10046:             push(@idresponses,$entries[$idx]);
                   10047:         }
                   10048:         $$responses{$id}=join(',',@idresponses);
                   10049:     }
                   10050:     for (my $i=1; $i<=$number; $i++) {
                   10051:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10052:     }
                   10053:     return ($errormsg,$number);
                   10054: }
                   10055: 
                   10056: 
1.414     www      10057: sub assign_clicker_grades {
1.608     www      10058:     my ($r,$symb)=@_;
1.414     www      10059:     if (!$symb) {return '';}
1.416     www      10060: # See which part we are saving to
1.582     raeburn  10061:     my $res_error;
                   10062:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10063:     if ($res_error) {
                   10064:         return &navmap_errormsg();
                   10065:     }
1.416     www      10066: # FIXME: This should probably look for the first handgradeable part
                   10067:     my $part=$$partlist[0];
                   10068: # Start screen output
1.632     www      10069:     my $result=&Apache::loncommon::start_data_table().
                   10070:              &Apache::loncommon::start_data_table_header_row().
                   10071:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10072:              &Apache::loncommon::end_data_table_header_row().
                   10073:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10074: # Get correct result
                   10075: # FIXME: Possibly need delimiter other than ":"
                   10076:     my @correct=();
1.415     www      10077:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10078:     my $number=$env{'form.number'};
                   10079:     if ($gradingmechanism ne 'attendance') {
1.414     www      10080:        foreach my $key (keys(%env)) {
                   10081:           if ($key=~/^form\.correct\:/) {
                   10082:              my @input=split(/\,/,$env{$key});
                   10083:              for (my $i=0;$i<=$#input;$i++) {
                   10084:                  if (($correct[$i]) && ($input[$i]) &&
                   10085:                      ($correct[$i] ne $input[$i])) {
                   10086:                     $result.='<br /><span class="LC_warning">'.
                   10087:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10088:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10089:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10090:                     $correct[$i]=$input[$i];
                   10091:                  }
                   10092:              }
                   10093:           }
                   10094:        }
1.415     www      10095:        for (my $i=0;$i<$number;$i++) {
1.644     www      10096:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10097:              $result.='<br /><span class="LC_error">'.
                   10098:                       &mt('No correct result given for question "[_1]"!',
                   10099:                           $env{'form.question:'.$i}).'</span>';
                   10100:           }
                   10101:        }
1.644     www      10102:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10103:     }
                   10104: # Start grading
1.415     www      10105:     my $pcorrect=$env{'form.pcorrect'};
                   10106:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10107:     my $storecount=0;
1.632     www      10108:     my %users=();
1.415     www      10109:     foreach my $key (keys(%env)) {
1.420     www      10110:        my $user='';
1.415     www      10111:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10112:           $user=$1;
                   10113:        }
                   10114:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10115:           my $id=$1;
                   10116:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10117:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10118:           } elsif ($env{'form.multi'.$id}) {
                   10119:              $user=$env{'form.multi'.$id};
1.420     www      10120:           }
                   10121:        }
1.632     www      10122:        if ($user) {
                   10123:           if ($users{$user}) {
                   10124:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10125:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10126:                       '</span><br />';
                   10127:           }
                   10128:           $users{$user}=1; 
1.415     www      10129:           my @answer=split(/\,/,$env{$key});
                   10130:           my $sum=0;
1.522     www      10131:           my $realnumber=$number;
1.415     www      10132:           for (my $i=0;$i<$number;$i++) {
1.576     www      10133:              if  ($correct[$i] eq '-') {
                   10134:                 $realnumber--;
1.644     www      10135:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10136:                 if ($gradingmechanism eq 'attendance') {
                   10137:                    $sum+=$pcorrect;
1.576     www      10138:                 } elsif ($correct[$i] eq '*') {
1.522     www      10139:                    $sum+=$pcorrect;
1.415     www      10140:                 } else {
1.644     www      10141: # We actually grade if correct or not
                   10142:                    my $increment=$pincorrect;
                   10143: # Special case: numerical answer "0"
                   10144:                    if ($correct[$i] eq '0') {
                   10145:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10146:                          $increment=$pcorrect;
                   10147:                       }
                   10148: # General numerical answer, both evaluate to something non-zero
                   10149:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10150:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10151:                          $increment=$pcorrect;
                   10152:                       }
                   10153: # Must be just alphanumeric
                   10154:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10155:                       $increment=$pcorrect;
1.415     www      10156:                    }
1.644     www      10157:                    $sum+=$increment;
1.415     www      10158:                 }
                   10159:              }
                   10160:           }
1.522     www      10161:           my $ave=$sum/(100*$realnumber);
1.416     www      10162: # Store
                   10163:           my ($username,$domain)=split(/\:/,$user);
                   10164:           my %grades=();
                   10165:           $grades{"resource.$part.solved"}='correct_by_override';
                   10166:           $grades{"resource.$part.awarded"}=$ave;
                   10167:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10168:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10169:                                                  $env{'request.course.id'},
                   10170:                                                  $domain,$username);
                   10171:           if ($returncode ne 'ok') {
                   10172:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10173:           } else {
                   10174:              $storecount++;
                   10175:           }
1.415     www      10176:        }
                   10177:     }
                   10178: # We are done
1.549     hauer    10179:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10180:              '</td>'.
                   10181:              &Apache::loncommon::end_data_table_row().
                   10182:              &Apache::loncommon::end_data_table();
1.614     www      10183:     return $result;
1.414     www      10184: }
                   10185: 
1.582     raeburn  10186: sub navmap_errormsg {
                   10187:     return '<div class="LC_error">'.
                   10188:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10189:            &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  10190:            '</div>';
                   10191: }
1.607     droeschl 10192: 
1.609     www      10193: sub startpage {
1.671     raeburn  10194:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10195:     if ($nomenu) {
                   10196:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10197:     } else {
                   10198:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10199:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10200:                                                  {'bread_crumbs' => $crumbs}));
                   10201:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10202:     }
1.613     www      10203:     unless ($nodisplayflag) {
1.671     raeburn  10204:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10205:     }
1.607     droeschl 10206: }
1.582     raeburn  10207: 
1.622     www      10208: sub select_problem {
                   10209:     my ($r)=@_;
1.632     www      10210:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10211:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10212:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10213:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10214: }
                   10215: 
1.1       albertel 10216: sub handler {
1.41      ng       10217:     my $request=$_[0];
1.434     albertel 10218:     &reset_caches();
1.646     raeburn  10219:     if ($request->header_only) {
                   10220:         &Apache::loncommon::content_type($request,'text/html');
                   10221:         $request->send_http_header;
                   10222:         return OK;
                   10223:     }
                   10224:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10225: 
1.664     raeburn  10226: # see what command we need to execute
                   10227: 
                   10228:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10229:     my $command=$commands[0];
                   10230: 
1.646     raeburn  10231:     &init_perm();
                   10232:     if (!$env{'request.course.id'}) {
1.664     raeburn  10233:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10234:                 ($command =~ /^scantronupload/)) {
                   10235:             # Not in a course.
                   10236:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10237:             return HTTP_NOT_ACCEPTABLE;
                   10238:         }
1.646     raeburn  10239:     } elsif (!%perm) {
                   10240:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10241:         return OK;
1.41      ng       10242:     }
1.646     raeburn  10243:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10244:     $request->send_http_header;
1.646     raeburn  10245: 
1.160     albertel 10246:     if ($#commands > 0) {
                   10247: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10248:     }
1.608     www      10249: 
                   10250: # see what the symb is
                   10251: 
                   10252:     my $symb=$env{'form.symb'};
                   10253:     unless ($symb) {
                   10254:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10255:        $symb=&Apache::lonnet::symbread($url);
                   10256:     }
1.646     raeburn  10257:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10258: 
1.513     foxr     10259:     $ssi_error = 0;
1.637     www      10260:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10261: #
1.637     www      10262: # Not called from a resource, but inside a course
1.601     www      10263: #    
1.622     www      10264:         &startpage($request,undef,[],1,1);
                   10265:         &select_problem($request);
1.41      ng       10266:     } else {
1.104     albertel 10267: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10268:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10269:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10270:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10271:                     &choose_task_version_form($symb,$env{'form.student'},
                   10272:                                               $env{'form.userdom'});
                   10273:             }
                   10274:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10275:             if ($versionform) {
                   10276:                 $request->print($versionform);
                   10277:             }
                   10278:             $request->print('<br clear="all" />');
1.611     www      10279: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10280:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10281:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10282:                 &choose_task_version_form($symb,$env{'form.student'},
                   10283:                                           $env{'form.userdom'},
                   10284:                                           $env{'form.inhibitmenu'});
                   10285:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10286:             if ($versionform) {
                   10287:                 $request->print($versionform);
                   10288:             }
                   10289:             $request->print('<br clear="all" />');
                   10290:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10291: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10292:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10293:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10294: 	    &pickStudentPage($request,$symb);
1.103     albertel 10295: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10296:             &startpage($request,$symb,
                   10297:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10298:                                        {href=>'',text=>'Select student'},
                   10299:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10300: 	    &displayPage($request,$symb);
1.104     albertel 10301: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10302:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10303:                                        {href=>'',text=>'Select student'},
                   10304:                                        {href=>'',text=>'Grade student'},
                   10305:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10306: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10307: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10308:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10309:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10310: 	    &processGroup($request,$symb);
1.104     albertel 10311: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10312:             &startpage($request,$symb);
                   10313: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10314: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10315:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10316: 	    $request->print(&submit_options($request,$symb));
1.598     www      10317:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10318:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10319:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10320:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10321:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10322:             $request->print(&submit_options_table($request,$symb));
1.598     www      10323:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10324:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10325:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10326: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10327:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10328: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10329: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10330:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10331:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10332: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10333: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10334:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10335:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10336:                                                                              text=>"Modify grades"},
                   10337:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10338: 	    $request->print(&editgrades($request,$symb));
1.602     www      10339:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10340:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10341:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10342: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10343:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10344:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10345: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10346:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10347:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10348:             $request->print(&process_clicker($request,$symb));
1.400     www      10349:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10350:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10351:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10352:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10353:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10354:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10355:                                        {href=>'', text=>'Process clicker file'},
                   10356:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10357:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10358: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10359:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10360: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10361: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10362:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10363: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10364: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10365:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10366: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10367: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10368: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10369:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10370: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10371: 	    } else {
1.257     albertel 10372: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10373: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10374: 		} else {
1.257     albertel 10375: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10376: 		}
1.627     www      10377:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10378: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10379: 	    }
1.246     albertel 10380: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10381:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10382: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10383: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10384:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10385: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10386:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10387:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10388:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10389: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10390:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10391: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10392: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10393:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10394: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10395:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10396:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10397: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10398:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10399:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10400:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10401:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10402: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10403:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10404:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10405:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10406: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10407:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10408:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10409:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10410:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10411:             $request->print(&checkscantron_results($request,$symb));
                   10412:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10413:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10414:             $request->print(&submit_options_download($request,$symb));
                   10415:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10416:             &startpage($request,$symb,
                   10417:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10418:     {href=>'', text=>'Download submissions'}]);
                   10419:             &submit_download_link($request,$symb);
1.106     albertel 10420: 	} elsif ($command) {
1.620     www      10421:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10422: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10423: 	}
1.2       albertel 10424:     }
1.513     foxr     10425:     if ($ssi_error) {
                   10426: 	&ssi_print_error($request);
                   10427:     }
1.671     raeburn  10428:     if ($env{'form.inhibitmenu'}) {
                   10429:         $request->print(&Apache::loncommon::end_page());
                   10430:     } else {
                   10431:         &Apache::lonquickgrades::endGradeScreen($request);
                   10432:     }
1.434     albertel 10433:     &reset_caches();
1.646     raeburn  10434:     return OK;
1.44      ng       10435: }
                   10436: 
1.1       albertel 10437: 1;
                   10438: 
1.13      albertel 10439: __END__;
1.531     jms      10440: 
                   10441: 
                   10442: =head1 NAME
                   10443: 
                   10444: Apache::grades
                   10445: 
                   10446: =head1 SYNOPSIS
                   10447: 
                   10448: Handles the viewing of grades.
                   10449: 
                   10450: This is part of the LearningOnline Network with CAPA project
                   10451: described at http://www.lon-capa.org.
                   10452: 
                   10453: =head1 OVERVIEW
                   10454: 
                   10455: Do an ssi with retries:
1.715     bisitz   10456: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10457: 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
                   10458: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10459: 
                   10460: At least the logic that drives this has been pulled out into loncommon.
                   10461: 
                   10462: 
                   10463: 
                   10464: ssi_with_retries - Does the server side include of a resource.
                   10465:                      if the ssi call returns an error we'll retry it up to
                   10466:                      the number of times requested by the caller.
1.715     bisitz   10467:                      If we still have a problem, no text is appended to the
1.531     jms      10468:                      output and we set some global variables.
                   10469:                      to indicate to the caller an SSI error occurred.  
                   10470:                      All of this is supposed to deal with the issues described
1.715     bisitz   10471:                      in LON-CAPA BZ 5631 see:
1.531     jms      10472:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10473:                      by informing the user that this happened.
                   10474: 
                   10475: Parameters:
                   10476:   resource   - The resource to include.  This is passed directly, without
                   10477:                interpretation to lonnet::ssi.
                   10478:   form       - The form hash parameters that guide the interpretation of the resource
                   10479:                
                   10480:   retries    - Number of retries allowed before giving up completely.
                   10481: Returns:
                   10482:   On success, returns the rendered resource identified by the resource parameter.
                   10483: Side Effects:
                   10484:   The following global variables can be set:
                   10485:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10486:                               It is up to the caller to initialize this to false
                   10487:                               if desired.
                   10488:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10489:                               of the resource that could not be rendered by the ssi
                   10490:                               call.
                   10491:    ssi_error_message   - The error string fetched from the ssi response
                   10492:                               in the event of an error.
                   10493: 
                   10494: 
                   10495: =head1 HANDLER SUBROUTINE
                   10496: 
                   10497: ssi_with_retries()
                   10498: 
                   10499: =head1 SUBROUTINES
                   10500: 
                   10501: =over
                   10502: 
1.671     raeburn  10503: =head1 Routines to display previous version of a Task for a specific student
                   10504: 
                   10505: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10506: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10507: requires a proctor to check-in the student, a new version of the Task will
                   10508: be created when the student is checked in to the new opportunity.
                   10509: 
                   10510: If a particular student has tried two or more versions of a particular task,
                   10511: the submission screen provides a user with vgr privileges (e.g., a Course
                   10512: Coordinator) the ability to display a previous version worked on by the
                   10513: student.  By default, the current version is displayed. If a previous version
                   10514: has been selected for display, submission data are only shown that pertain
                   10515: to that particular version, and the interface to submit grades is not shown.
                   10516: 
                   10517: =over 4
                   10518: 
                   10519: =item show_previous_task_version()
                   10520: 
                   10521: Displays a specified version of a student's Task, as the student sees it.
                   10522: 
                   10523: Inputs: 2
                   10524:         request - request object
                   10525:         symb    - unique symb for current instance of resource
                   10526: 
                   10527: Output: None.
                   10528: 
                   10529: Side Effects: calls &show_problem() to print version of Task, with
                   10530:               version contained in form item: $env{'form.previousversion'}
                   10531: 
                   10532: =item choose_task_version_form()
                   10533: 
                   10534: Displays a web form used to select which version of a student's view of a
                   10535: Task should be displayed.  Either launches a pop-up window, or replaces
                   10536: content in existing pop-up, or replaces page in main window.
                   10537: 
                   10538: Inputs: 4
                   10539:         symb    - unique symb for current instance of resource
                   10540:         uname   - username of student
                   10541:         udom    - domain of student
                   10542:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10543:                   breadcrumbs etc., are displayed
                   10544: 
                   10545: Output: 4
                   10546:         current   - student's current version
                   10547:         displayed - student's version being displayed
                   10548:         result    - scalar containing HTML for web form used to switch to
                   10549:                     a different version (or a link to close window, if pop-up).
                   10550:         js        - javascript for processing selection in versions web form
                   10551: 
                   10552: Side Effects: None.
                   10553: 
                   10554: =item previous_display_javascript()
                   10555: 
                   10556: Inputs: 2
                   10557:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10558:                   breadcrumbs etc., are displayed.
                   10559:         current - student's current version number.
                   10560: 
                   10561: Output: 1
                   10562:         js      - javascript for processing selection in versions web form.
                   10563: 
                   10564: Side Effects: None.
                   10565: 
                   10566: =back
                   10567: 
                   10568: =head1 Routines to process bubblesheet data.
                   10569: 
                   10570: =over 4
                   10571: 
1.531     jms      10572: =item scantron_get_correction() : 
                   10573: 
                   10574:    Builds the interface screen to interact with the operator to fix a
                   10575:    specific error condition in a specific scanline
                   10576: 
                   10577:  Arguments:
                   10578:     $r           - Apache request object
                   10579:     $i           - number of the current scanline
                   10580:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10581:     $scan_config - hash ref as returned from &get_scantron_config()
                   10582:     $line        - full contents of the current scanline
                   10583:     $error       - error condition, valid values are
                   10584:                    'incorrectCODE', 'duplicateCODE',
                   10585:                    'doublebubble', 'missingbubble',
                   10586:                    'duplicateID', 'incorrectID'
                   10587:     $arg         - extra information needed
                   10588:        For errors:
                   10589:          - duplicateID   - paper number that this studentID was seen before on
                   10590:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10591:                            seen on before
                   10592:          - incorrectCODE - current incorrect CODE 
                   10593:          - doublebubble  - array ref of the bubble lines that have double
                   10594:                            bubble errors
                   10595:          - missingbubble - array ref of the bubble lines that have missing
                   10596:                            bubble errors
                   10597: 
1.691     raeburn  10598:    $randomorder - True if exam folder has randomorder set
                   10599:    $randompick  - True if exam folder has randompick set
                   10600:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10601:                      for current line to question number used for same question
                   10602:                      in "Master Seqence" (as seen by Course Coordinator).
                   10603:    $startline   - Reference to hash where key is question number (0 is first)
                   10604:                   and value is number of first bubble line for current student
                   10605:                   or code-based randompick and/or randomorder.
                   10606: 
                   10607: 
                   10608: 
1.531     jms      10609: =item  scantron_get_maxbubble() : 
                   10610: 
1.582     raeburn  10611:    Arguments:
                   10612:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10613:                       failure to retrieve a navmap object.
                   10614:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10615:        calling routine should trap the error condition and display the warning
                   10616:        found in &navmap_errormsg().
                   10617: 
1.649     raeburn  10618:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10619: 
1.531     jms      10620:    Returns the maximum number of bubble lines that are expected to
                   10621:    occur. Does this by walking the selected sequence rendering the
                   10622:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10623:    for what the current value of the problem counter is.
                   10624: 
                   10625:    Caches the results to $env{'form.scantron_maxbubble'},
                   10626:    $env{'form.scantron.bubble_lines.n'}, 
                   10627:    $env{'form.scantron.first_bubble_line.n'} and
                   10628:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10629:    which are the total number of bubble lines, the number of bubble
1.531     jms      10630:    lines for response n and number of the first bubble line for response n,
                   10631:    and a comma separated list of numbers of bubble lines for sub-questions
                   10632:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10633: 
                   10634: 
                   10635: =item  scantron_validate_missingbubbles() : 
                   10636: 
                   10637:    Validates all scanlines in the selected file to not have any
                   10638:     answers that don't have bubbles that have not been verified
                   10639:     to be bubble free.
                   10640: 
                   10641: =item  scantron_process_students() : 
                   10642: 
1.659     raeburn  10643:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10644: 
                   10645:    The parsed scanline hash is added to %env 
                   10646: 
                   10647:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10648:    foreach resource , with the form data of
                   10649: 
                   10650: 	'submitted'     =>'scantron' 
                   10651: 	'grade_target'  =>'grade',
                   10652: 	'grade_username'=> username of student
                   10653: 	'grade_domain'  => domain of student
                   10654: 	'grade_courseid'=> of course
                   10655: 	'grade_symb'    => symb of resource to grade
                   10656: 
                   10657:     This triggers a grading pass. The problem grading code takes care
                   10658:     of converting the bubbled letter information (now in %env) into a
                   10659:     valid submission.
                   10660: 
                   10661: =item  scantron_upload_scantron_data() :
                   10662: 
1.659     raeburn  10663:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10664: 
                   10665: =item  scantron_upload_scantron_data_save() : 
                   10666: 
                   10667:    Adds a provided bubble information data file to the course if user
                   10668:    has the correct privileges to do so. 
                   10669: 
                   10670: =item  valid_file() :
                   10671: 
                   10672:    Validates that the requested bubble data file exists in the course.
                   10673: 
                   10674: =item  scantron_download_scantron_data() : 
                   10675: 
                   10676:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10677:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10678:    course.
                   10679: 
                   10680: =item  scantron_validate_ID() : 
                   10681: 
                   10682:    Validates all scanlines in the selected file to not have any
1.556     weissno  10683:    invalid or underspecified student/employee IDs
1.531     jms      10684: 
1.582     raeburn  10685: =item navmap_errormsg() :
                   10686: 
                   10687:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10688:    Should be called whenever the request to instantiate a navmap object fails.
                   10689: 
                   10690: =back
1.582     raeburn  10691: 
1.531     jms      10692: =back
                   10693: 
                   10694: =cut

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