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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.750   ! raeburn     4: # $Id: grades.pm,v 1.749 2017/12/31 14:00:41 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
1.745     raeburn   119:     my $toolsymb;
                    120:     if ($url =~ /ext\.tool$/) {
                    121:         $toolsymb = $symb;
                    122:     }
                    123:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  124: 
1.146     albertel  125:     my @stores;
1.439     albertel  126:     foreach my $part (@{ $partlist }) {
1.146     albertel  127: 	foreach my $key (@metakeys) {
                    128: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    129: 	}
                    130:     }
                    131:     return @stores;
1.2       albertel  132: }
                    133: 
1.129     ng        134: #--- Format fullname, username:domain if different for display
                    135: #--- Use anywhere where the student names are listed
                    136: sub nameUserString {
                    137:     my ($type,$fullname,$uname,$udom) = @_;
                    138:     if ($type eq 'header') {
1.485     albertel  139: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        140:     } else {
1.398     albertel  141: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    142: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        143:     }
                    144: }
                    145: 
1.44      ng        146: #--- Get the partlist and the response type for a given problem. ---
                    147: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       148: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        149: sub response_type {
1.582     raeburn   150:     my ($symb,$response_error) = @_;
1.377     albertel  151: 
                    152:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   153:     unless (ref($navmap)) {
                    154:         if (ref($response_error)) {
                    155:             $$response_error = 1;
                    156:         }
                    157:         return;
                    158:     }
1.377     albertel  159:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   160:     unless (ref($res)) {
                    161:         $$response_error = 1;
                    162:         return;
                    163:     }
1.377     albertel  164:     my $partlist = $res->parts();
1.392     albertel  165:     my %vPart = 
                    166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  167:     my (%response_types,%handgrade);
                    168:     foreach my $part (@{ $partlist }) {
1.392     albertel  169: 	next if (%vPart && !exists($vPart{$part}));
                    170: 
1.377     albertel  171: 	my @types = $res->responseType($part);
                    172: 	my @ids = $res->responseIds($part);
                    173: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    174: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    175: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    176: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    177: 				     '.handgrade',$symb);
1.41      ng        178: 	}
                    179:     }
1.377     albertel  180:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        181: }
                    182: 
1.375     albertel  183: sub flatten_responseType {
                    184:     my ($responseType) = @_;
                    185:     my @part_response_id =
                    186: 	map { 
                    187: 	    my $part = $_;
                    188: 	    map {
                    189: 		[$part,$_]
                    190: 		} sort(keys(%{ $responseType->{$part} }));
                    191: 	} sort(keys(%$responseType));
                    192:     return @part_response_id;
                    193: }
                    194: 
1.207     albertel  195: sub get_display_part {
1.324     albertel  196:     my ($partID,$symb)=@_;
1.207     albertel  197:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    198:     if (defined($display) and $display ne '') {
1.577     bisitz    199:         $display.= ' (<span class="LC_internal_info">'
                    200:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  201:     } else {
                    202: 	$display=$partID;
                    203:     }
                    204:     return $display;
                    205: }
1.269     raeburn   206: 
1.434     albertel  207: sub reset_caches {
                    208:     &reset_analyze_cache();
                    209:     &reset_perm();
1.674     raeburn   210:     &reset_old_essays();
1.434     albertel  211: }
                    212: 
                    213: {
                    214:     my %analyze_cache;
1.557     raeburn   215:     my %analyze_cache_formkeys;
1.148     albertel  216: 
1.434     albertel  217:     sub reset_analyze_cache {
                    218: 	undef(%analyze_cache);
1.557     raeburn   219:         undef(%analyze_cache_formkeys);
1.434     albertel  220:     }
                    221: 
                    222:     sub get_analyze {
1.649     raeburn   223: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  224: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   225:         if ($type eq 'randomizetry') {
                    226:             if ($trial ne '') {
                    227:                 $key .= "\0".$trial;
                    228:             }
                    229:         }
1.557     raeburn   230: 	if (exists($analyze_cache{$key})) {
                    231:             my $getupdate = 0;
                    232:             if (ref($add_to_hash) eq 'HASH') {
                    233:                 foreach my $item (keys(%{$add_to_hash})) {
                    234:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    235:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    236:                             $getupdate = 1;
                    237:                             last;
                    238:                         }
                    239:                     } else {
                    240:                         $getupdate = 1;
                    241:                     }
                    242:                 }
                    243:             }
                    244:             if (!$getupdate) {
                    245:                 return $analyze_cache{$key};
                    246:             }
                    247:         }
1.434     albertel  248: 
                    249: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    250: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   251:         my %form = ('grade_target'      => 'analyze',
                    252:                     'grade_domain'      => $udom,
                    253:                     'grade_symb'        => $symb,
                    254:                     'grade_courseid'    =>  $env{'request.course.id'},
                    255:                     'grade_username'    => $uname,
                    256:                     'grade_noincrement' => $no_increment);
1.649     raeburn   257:         if ($bubbles_per_row ne '') {
                    258:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    259:         }
1.640     raeburn   260:         if ($type eq 'randomizetry') {
                    261:             $form{'grade_questiontype'} = $type;
                    262:             if ($rndseed ne '') {
                    263:                 $form{'grade_rndseed'} = $rndseed;
                    264:             }
                    265:         }
1.557     raeburn   266:         if (ref($add_to_hash)) {
                    267:             %form = (%form,%{$add_to_hash});
1.640     raeburn   268:         }
1.557     raeburn   269: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  270: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    271: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   272:         if (ref($add_to_hash) eq 'HASH') {
                    273:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    274:         } else {
                    275:             $analyze_cache_formkeys{$key} = {};
                    276:         }
1.434     albertel  277: 	return $analyze_cache{$key} = \%analyze;
                    278:     }
                    279: 
                    280:     sub get_order {
1.640     raeburn   281: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    282: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  283: 	return $analyze->{"$partid.$respid.shown"};
                    284:     }
                    285: 
                    286:     sub get_radiobutton_correct_foil {
1.640     raeburn   287: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    288: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    289:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   290:         if (ref($foils) eq 'ARRAY') {
                    291: 	    foreach my $foil (@{$foils}) {
                    292: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    293: 		    return $foil;
                    294: 	        }
1.434     albertel  295: 	    }
                    296: 	}
                    297:     }
1.554     raeburn   298: 
                    299:     sub scantron_partids_tograde {
1.741     raeburn   300:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   301:         my (%analysis,@parts);
                    302:         if (ref($resource)) {
                    303:             my $symb = $resource->symb();
1.557     raeburn   304:             my $add_to_form;
                    305:             if ($check_for_randomlist) {
                    306:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    307:             }
1.741     raeburn   308:             if ($scancode) {
                    309:                 if (ref($add_to_form) eq 'HASH') {
                    310:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    311:                 } else {
                    312:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    313:                 }
                    314:             }
1.649     raeburn   315:             my $analyze = 
                    316:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    317:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   318:             if (ref($analyze) eq 'HASH') {
                    319:                 %analysis = %{$analyze};
                    320:             }
                    321:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    322:                 foreach my $part (@{$analysis{'parts'}}) {
                    323:                     my ($id,$respid) = split(/\./,$part);
                    324:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    325:                         push(@parts,$part);
                    326:                     }
                    327:                 }
                    328:             }
                    329:         }
                    330:         return (\%analysis,\@parts);
                    331:     }
                    332: 
1.148     albertel  333: }
1.434     albertel  334: 
1.118     ng        335: #--- Clean response type for display
1.335     albertel  336: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    337: #        response types only.
1.118     ng        338: sub cleanRecord {
1.336     albertel  339:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   340: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  341:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  342:     if ($response =~ /^(option|rank)$/) {
                    343: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     344:         my @answer = %answer;
                    345:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    347: 	my ($toprow,$bottomrow);
                    348: 	foreach my $foil (@$order) {
                    349: 	    if ($grading{$foil} == 1) {
                    350: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    351: 	    } else {
                    352: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    353: 	    }
1.398     albertel  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  355: 	}
                    356: 	return '<blockquote><table border="1">'.
1.466     albertel  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   359: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  360:     } elsif ($response eq 'match') {
                    361: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     362:         my @answer = %answer;
                    363:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  364: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    365: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    366: 	my ($toprow,$middlerow,$bottomrow);
                    367: 	foreach my $foil (@$order) {
                    368: 	    my $item=shift(@items);
                    369: 	    if ($grading{$foil} == 1) {
                    370: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  371: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  372: 	    } else {
                    373: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  374: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  375: 	    }
1.398     albertel  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        377: 	}
1.126     ng        378: 	return '<blockquote><table border="1">'.
1.466     albertel  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  381: 	    $middlerow.'</tr>'.
1.466     albertel  382: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   383: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  384:     } elsif ($response eq 'radiobutton') {
                    385: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     386:         my @answer = %answer;
                    387:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  388: 	my ($toprow,$bottomrow);
1.434     albertel  389: 	my $correct = 
1.640     raeburn   390: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  391: 	foreach my $foil (@$order) {
1.148     albertel  392: 	    if (exists($answer{$foil})) {
1.434     albertel  393: 		if ($foil eq $correct) {
1.466     albertel  394: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  395: 		} else {
1.466     albertel  396: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  397: 		}
                    398: 	    } else {
1.466     albertel  399: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  400: 	    }
1.398     albertel  401: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  402: 	}
                    403: 	return '<blockquote><table border="1">'.
1.466     albertel  404: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    405: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   406: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  407:     } elsif ($response eq 'essay') {
1.257     albertel  408: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        409: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  410: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    411: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        412: 
1.257     albertel  413: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    414: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    415: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    416: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    417: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    418: 	    $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        419: 	}
1.730     kruse     420: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     421: 
1.268     albertel  422:     } elsif ( $response eq 'organic') {
1.721     bisitz    423:         my $result=&mt('Smile representation: [_1]',
                    424:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  425: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    426: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    427: 	return $result;
1.335     albertel  428:     } elsif ( $response eq 'Task') {
                    429: 	if ( $answer eq 'SUBMITTED') {
                    430: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  431: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  432: 	    return $result;
                    433: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    434: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    435: 			       keys(%{$record}));
                    436: 	    return join('<br />',($version,@matches));
                    437: 			       
                    438: 			       
                    439: 	} else {
                    440: 	    my $result =
                    441: 		'<p>'
                    442: 		.&mt('Overall result: [_1]',
                    443: 		     $record->{$version."resource.$respid.$partid.status"})
                    444: 		.'</p>';
                    445: 	    
                    446: 	    $result .= '<ul>';
                    447: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    448: 			     keys(%{$record}));
                    449: 	    foreach my $grade (sort(@grade)) {
                    450: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    451: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    452: 				     $dim, $record->{$grade}).
                    453: 			  '</li>';
                    454: 	    }
                    455: 	    $result.='</ul>';
                    456: 	    return $result;
                    457: 	}
1.716     bisitz    458:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    459:         # Respect multiple input fields, see Bug #5409
1.440     albertel  460: 	$answer = 
                    461: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    462: 							      $answer);
1.720     kruse     463: 	return $answer;
1.122     ng        464:     }
1.720     kruse     465:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        466: }
                    467: 
                    468: #-- A couple of common js functions
                    469: sub commonJSfunctions {
                    470:     my $request = shift;
1.597     wenzelju  471:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        472:     function radioSelection(radioButton) {
                    473: 	var selection=null;
                    474: 	if (radioButton.length > 1) {
                    475: 	    for (var i=0; i<radioButton.length; i++) {
                    476: 		if (radioButton[i].checked) {
                    477: 		    return radioButton[i].value;
                    478: 		}
                    479: 	    }
                    480: 	} else {
                    481: 	    if (radioButton.checked) return radioButton.value;
                    482: 	}
                    483: 	return selection;
                    484:     }
                    485: 
                    486:     function pullDownSelection(selectOne) {
                    487: 	var selection="";
                    488: 	if (selectOne.length > 1) {
                    489: 	    for (var i=0; i<selectOne.length; i++) {
                    490: 		if (selectOne[i].selected) {
                    491: 		    return selectOne[i].value;
                    492: 		}
                    493: 	    }
                    494: 	} else {
1.138     albertel  495:             // only one value it must be the selected one
                    496: 	    return selectOne.value;
1.118     ng        497: 	}
                    498:     }
                    499: COMMONJSFUNCTIONS
                    500: }
                    501: 
1.44      ng        502: #--- Dumps the class list with usernames,list of sections,
                    503: #--- section, ids and fullnames for each user.
                    504: sub getclasslist {
1.750   ! raeburn   505:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  506:     my @getsec;
1.450     banghart  507:     my @getgroup;
1.442     banghart  508:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  509:     if (!ref($getsec)) {
                    510: 	if ($getsec ne '' && $getsec ne 'all') {
                    511: 	    @getsec=($getsec);
                    512: 	}
                    513:     } else {
                    514: 	@getsec=@{$getsec};
                    515:     }
                    516:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  517:     if (!ref($getgroup)) {
                    518: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    519: 	    @getgroup=($getgroup);
                    520: 	}
                    521:     } else {
                    522: 	@getgroup=@{$getgroup};
                    523:     }
                    524:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  525: 
1.449     banghart  526:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  527:     # Bail out if we were unable to get the classlist
1.56      matthew   528:     return if (! defined($classlist));
1.449     banghart  529:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   530:     #
                    531:     my %sections;
                    532:     my %fullnames;
1.750   ! raeburn   533:     my ($cdom,$cnum,$partlist);
        !           534:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
        !           535:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
        !           536:         $cnum = $env{"course.$env{'request.course.id'}.num"};
        !           537:         my $res_error;
        !           538:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
        !           539:     }
1.205     matthew   540:     foreach my $student (keys(%$classlist)) {
                    541:         my $end      = 
                    542:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    543:         my $start    = 
                    544:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    545:         my $id       = 
                    546:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    547:         my $section  = 
                    548:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    549:         my $fullname = 
                    550:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    551:         my $status   = 
                    552:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  553:         my $group   = 
                    554:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        555: 	# filter students according to status selected
1.750   ! raeburn   556: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  557: 	    if (!($stu_status =~ $status)) {
1.450     banghart  558: 		delete($classlist->{$student});
1.76      ng        559: 		next;
                    560: 	    }
                    561: 	}
1.450     banghart  562: 	# filter students according to groups selected
1.453     banghart  563: 	my @stu_groups = split(/,/,$group);
1.450     banghart  564: 	if (@getgroup) {
                    565: 	    my $exclude = 1;
1.454     banghart  566: 	    foreach my $grp (@getgroup) {
                    567: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  568: 	            if ($stu_group eq $grp) {
                    569: 	                $exclude = 0;
                    570:     	            } 
1.450     banghart  571: 	        }
1.453     banghart  572:     	        if (($grp eq 'none') && !$group) {
1.750   ! raeburn   573:         	    $exclude = 0;
1.453     banghart  574:         	}
1.450     banghart  575: 	    }
                    576: 	    if ($exclude) {
                    577: 	        delete($classlist->{$student});
1.750   ! raeburn   578: 		next;
1.450     banghart  579: 	    }
                    580: 	}
1.750   ! raeburn   581:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
        !           582:             my $udom =
        !           583:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
        !           584:             my $uname =
        !           585:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
        !           586:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
        !           587:                 if ($submitonly eq 'queued') {
        !           588:                     my %queue_status =
        !           589:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
        !           590:                                                                 $udom,$uname);
        !           591:                     if (!defined($queue_status{'gradingqueue'})) {
        !           592:                         delete($classlist->{$student});
        !           593:                         next;
        !           594:                     }
        !           595:                 } else {
        !           596:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
        !           597:                     my $submitted = 0;
        !           598:                     my $graded = 0;
        !           599:                     my $incorrect = 0;
        !           600:                     foreach (keys(%status)) {
        !           601:                         $submitted = 1 if ($status{$_} ne 'nothing');
        !           602:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
        !           603:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
        !           604: 
        !           605:                         my ($foo,$partid,$foo1) = split(/\./,$_);
        !           606:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
        !           607:                             $submitted = 0;
        !           608:                         }
        !           609:                     }
        !           610:                     if (!$submitted && ($submitonly eq 'yes' ||
        !           611:                                         $submitonly eq 'incorrect' ||
        !           612:                                         $submitonly eq 'graded')) {
        !           613:                         delete($classlist->{$student});
        !           614:                         next;
        !           615:                     } elsif (!$graded && ($submitonly eq 'graded')) {
        !           616:                         delete($classlist->{$student});
        !           617:                         next;
        !           618:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
        !           619:                         delete($classlist->{$student});
        !           620:                         next;
        !           621:                     }
        !           622:                 }
        !           623:             }
        !           624:         }
1.205     matthew   625: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  626: 	if (&canview($section)) {
1.291     albertel  627: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  628: 		$sections{$section}++;
1.450     banghart  629: 		if ($classlist->{$student}) {
                    630: 		    $fullnames{$student}=$fullname;
                    631: 		}
1.103     albertel  632: 	    } else {
1.205     matthew   633: 		delete($classlist->{$student});
1.103     albertel  634: 	    }
                    635: 	} else {
1.205     matthew   636: 	    delete($classlist->{$student});
1.103     albertel  637: 	}
1.44      ng        638:     }
1.56      matthew   639:     my @sections = sort(keys(%sections));
                    640:     return ($classlist,\@sections,\%fullnames);
1.44      ng        641: }
                    642: 
1.103     albertel  643: sub canmodify {
                    644:     my ($sec)=@_;
                    645:     if ($perm{'mgr'}) {
                    646: 	if (!defined($perm{'mgr_section'})) {
                    647: 	    # can modify whole class
                    648: 	    return 1;
                    649: 	} else {
                    650: 	    if ($sec eq $perm{'mgr_section'}) {
                    651: 		#can modify the requested section
                    652: 		return 1;
                    653: 	    } else {
                    654: 		# can't modify the request section
                    655: 		return 0;
                    656: 	    }
                    657: 	}
                    658:     }
                    659:     #can't modify
                    660:     return 0;
                    661: }
                    662: 
                    663: sub canview {
                    664:     my ($sec)=@_;
                    665:     if ($perm{'vgr'}) {
                    666: 	if (!defined($perm{'vgr_section'})) {
                    667: 	    # can modify whole class
                    668: 	    return 1;
                    669: 	} else {
                    670: 	    if ($sec eq $perm{'vgr_section'}) {
                    671: 		#can modify the requested section
                    672: 		return 1;
                    673: 	    } else {
                    674: 		# can't modify the request section
                    675: 		return 0;
                    676: 	    }
                    677: 	}
                    678:     }
                    679:     #can't modify
                    680:     return 0;
                    681: }
                    682: 
1.44      ng        683: #--- Retrieve the grade status of a student for all the parts
                    684: sub student_gradeStatus {
1.324     albertel  685:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  686:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        687:     my %partstatus = ();
                    688:     foreach (@$partlist) {
1.128     ng        689: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        690: 	$status              = 'nothing' if ($status eq '');
                    691: 	$partstatus{$_}      = $status;
                    692: 	my $subkey           = "resource.$_.submitted_by";
                    693: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    694:     }
                    695:     return %partstatus;
                    696: }
                    697: 
1.45      ng        698: # hidden form and javascript that calls the form
                    699: # Use by verifyscript and viewgrades
                    700: # Shows a student's view of problem and submission
                    701: sub jscriptNform {
1.324     albertel  702:     my ($symb) = @_;
1.442     banghart  703:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  704:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        705: 	'    function viewOneStudent(user,domain) {'."\n".
                    706: 	'	document.onestudent.student.value = user;'."\n".
                    707: 	'	document.onestudent.userdom.value = domain;'."\n".
                    708: 	'	document.onestudent.submit();'."\n".
                    709: 	'    }'."\n".
1.597     wenzelju  710: 	"\n");
1.45      ng        711:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  712: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  713: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        714: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    715: 	'<input type="hidden" name="student" value="" />'."\n".
                    716: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    717: 	'</form>'."\n";
                    718:     return $jscript;
                    719: }
1.39      ng        720: 
1.447     foxr      721: 
                    722: 
1.315     bowersj2  723: # Given the score (as a number [0-1] and the weight) what is the final
                    724: # point value? This function will round to the nearest tenth, third,
                    725: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  726: sub compute_points {
1.315     bowersj2  727:     my ($score, $weight) = @_;
                    728:     
                    729:     my $tolerance = .00001;
                    730:     my $points = $score * $weight;
                    731: 
                    732:     # Check for nearness to 1/x.
                    733:     my $check_for_nearness = sub {
                    734:         my ($factor) = @_;
                    735:         my $num = ($points * $factor) + $tolerance;
                    736:         my $floored_num = floor($num);
1.316     albertel  737:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  738:             return $floored_num / $factor;
                    739:         }
                    740:         return $points;
                    741:     };
                    742: 
                    743:     $points = $check_for_nearness->(10);
                    744:     $points = $check_for_nearness->(3);
                    745:     $points = $check_for_nearness->(4);
                    746:     
                    747:     return $points;
                    748: }
                    749: 
1.44      ng        750: #------------------ End of general use routines --------------------
1.87      www       751: 
                    752: #
                    753: # Find most similar essay
                    754: #
                    755: 
                    756: sub most_similar {
1.674     raeburn   757:     my ($uname,$udom,$symb,$uessay)=@_;
                    758: 
                    759:     unless ($symb) { return ''; }
                    760: 
                    761:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       762: 
                    763: # ignore spaces and punctuation
                    764: 
                    765:     $uessay=~s/\W+/ /gs;
                    766: 
1.282     www       767: # ignore empty submissions (occuring when only files are sent)
                    768: 
1.598     www       769:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       770: 
1.87      www       771: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       772:     my $limit=0.6;
1.87      www       773:     my $sname='';
                    774:     my $sdom='';
                    775:     my $scrsid='';
                    776:     my $sessay='';
                    777: # go through all essays ...
1.674     raeburn   778:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  779: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       780: # ... except the same student
1.426     albertel  781:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   782: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  783: 	$tessay=~s/\W+/ /gs;
1.87      www       784: # String similarity gives up if not even limit
1.426     albertel  785: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       786: # Found one
1.426     albertel  787: 	if ($tsimilar>$limit) {
                    788: 	    $limit=$tsimilar;
                    789: 	    $sname=$tname;
                    790: 	    $sdom=$tdom;
                    791: 	    $scrsid=$tcrsid;
1.674     raeburn   792: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  793: 	}
1.87      www       794:     }
1.88      www       795:     if ($limit>0.6) {
1.87      www       796:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    797:     } else {
                    798:        return ('','','','',0);
                    799:     }
                    800: }
                    801: 
1.44      ng        802: #-------------------------------------------------------------------
                    803: 
                    804: #------------------------------------ Receipt Verification Routines
1.45      ng        805: #
1.602     www       806: 
                    807: sub initialverifyreceipt {
1.608     www       808:    my ($request,$symb) = @_;
1.602     www       809:    &commonJSfunctions($request);
1.694     bisitz    810:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       811:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    812:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       813:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    814:         '<input type="hidden" name="command" value="verify" />'.
                    815:         "</form>\n";
1.602     www       816: }
                    817: 
1.44      ng        818: #--- Check whether a receipt number is valid.---
                    819: sub verifyreceipt {
1.608     www       820:     my ($request,$symb)  = @_;
1.44      ng        821: 
1.257     albertel  822:     my $courseid = $env{'request.course.id'};
1.184     www       823:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  824: 	$env{'form.receipt'};
1.44      ng        825:     $receipt     =~ s/[^\-\d]//g;
                    826: 
1.487     albertel  827:     my $title.=
                    828: 	'<h3><span class="LC_info">'.
1.605     www       829: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    830: 	'</span></h3>'."\n";
1.44      ng        831: 
                    832:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   833:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  834:     
                    835:     my $receiptparts=0;
1.390     albertel  836:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    837: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  838:     my $parts=['0'];
1.582     raeburn   839:     if ($receiptparts) {
                    840:         my $res_error; 
                    841:         ($parts)=&response_type($symb,\$res_error);
                    842:         if ($res_error) {
                    843:             return &navmap_errormsg();
                    844:         } 
                    845:     }
1.486     albertel  846:     
                    847:     my $header = 
                    848: 	&Apache::loncommon::start_data_table().
                    849: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  850: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    851: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    852: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  853:     if ($receiptparts) {
1.487     albertel  854: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  855:     }
                    856:     $header.=
                    857: 	&Apache::loncommon::end_data_table_header_row();
                    858: 
1.294     albertel  859:     foreach (sort 
                    860: 	     {
                    861: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    862: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    863: 		 }
                    864: 		 return $a cmp $b;
                    865: 	     } (keys(%$fullname))) {
1.44      ng        866: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  867: 	foreach my $part (@$parts) {
                    868: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  869: 		$contents.=
                    870: 		    &Apache::loncommon::start_data_table_row().
                    871: 		    '<td>&nbsp;'."\n".
1.177     albertel  872: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  873: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  874: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    875: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    876: 		if ($receiptparts) {
                    877: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    878: 		}
1.486     albertel  879: 		$contents.= 
                    880: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  881: 		
                    882: 		$matches++;
                    883: 	    }
1.44      ng        884: 	}
                    885:     }
                    886:     if ($matches == 0) {
1.584     bisitz    887:         $string = $title
                    888:                  .'<p class="LC_warning">'
                    889:                  .&mt('No match found for the above receipt number.')
                    890:                  .'</p>';
1.44      ng        891:     } else {
1.324     albertel  892: 	$string = &jscriptNform($symb).$title.
1.487     albertel  893: 	    '<p>'.
1.584     bisitz    894: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  895: 	    '</p>'.
1.486     albertel  896: 	    $header.
                    897: 	    $contents.
                    898: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        899:     }
1.614     www       900:     return $string;
1.44      ng        901: }
                    902: 
                    903: #--- This is called by a number of programs.
                    904: #--- Called from the Grading Menu - View/Grade an individual student
                    905: #--- Also called directly when one clicks on the subm button 
                    906: #    on the problem page.
1.30      ng        907: sub listStudents {
1.617     www       908:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  909: 
1.747     raeburn   910:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel  911:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    912:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    913:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  914:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       915:     unless ($submitonly) {
                    916:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    917:     }
1.49      albertel  918: 
1.632     www       919:     my $result='';
1.623     www       920:     my $res_error;
                    921:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  922: 
1.736     damieng   923:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   924: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    925: 		'single'   => 'Please select the student before clicking on the Next button.',
                    926: 	     );
1.736     damieng   927:     &js_escape(\%js_lt);
1.597     wenzelju  928:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        929:     function checkSelect(checkBox) {
                    930: 	var ctr=0;
                    931: 	var sense="";
                    932: 	if (checkBox.length > 1) {
                    933: 	    for (var i=0; i<checkBox.length; i++) {
                    934: 		if (checkBox[i].checked) {
                    935: 		    ctr++;
                    936: 		}
                    937: 	    }
1.736     damieng   938: 	    sense = '$js_lt{'multiple'}';
1.110     ng        939: 	} else {
                    940: 	    if (checkBox.checked) {
                    941: 		ctr = 1;
                    942: 	    }
1.736     damieng   943: 	    sense = '$js_lt{'single'}';
1.110     ng        944: 	}
                    945: 	if (ctr == 0) {
1.485     albertel  946: 	    alert(sense);
1.110     ng        947: 	    return false;
                    948: 	}
                    949: 	document.gradesub.submit();
                    950:     }
                    951: 
                    952:     function reLoadList(formname) {
1.112     ng        953: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        954: 	formname.command.value = 'submission';
                    955: 	formname.submit();
                    956:     }
1.45      ng        957: LISTJAVASCRIPT
                    958: 
1.118     ng        959:     &commonJSfunctions($request);
1.41      ng        960:     $request->print($result);
1.39      ng        961: 
1.154     albertel  962:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       963: 	"\n";
1.485     albertel  964: 	
1.561     bisitz    965:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn   966:     unless ($is_tool) {
                    967:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    968:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    969:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    970:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    971:                       .&Apache::lonhtmlcommon::row_closure();
                    972:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    973:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    974:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    975:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    976:                       .&Apache::lonhtmlcommon::row_closure();
                    977:     }
1.485     albertel  978: 
                    979:     my $submission_options;
1.442     banghart  980:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    981:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  982:     $env{'form.Status'} = $saveStatus;
1.745     raeburn   983:     my %optiontext;
                    984:     if ($is_tool) {
                    985:         %optiontext = &Apache::lonlocal::texthash (
                    986:                           lastonly => 'last transaction',
                    987:                           last     => 'last transaction with details',
                    988:                           datesub  => 'all transactions',
                    989:                           all      => 'all transactions with details',
                    990:                       );
                    991:     } else {
                    992:         %optiontext = &Apache::lonlocal::texthash (
                    993:                           lastonly => 'last submission',
                    994:                           last     => 'last submission with details',
                    995:                           datesub  => 'all submissions',
                    996:                           all      => 'all submissions with details',
                    997:                       );
                    998:     }
1.485     albertel  999:     $submission_options.=
1.592     bisitz   1000:         '<span class="LC_nobreak">'.
1.624     www      1001:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1002:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1003:         '<span class="LC_nobreak">'.
                   1004:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1005:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1006:         '<span class="LC_nobreak">'.
1.628     www      1007:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1008:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1009:         '<span class="LC_nobreak">'.
                   1010:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1011:         $optiontext{'all'}.'</label></span>';
                   1012:     my $viewtitle;
                   1013:     if ($is_tool) {
                   1014:         $viewtitle = &mt('View Transactions');
                   1015:     } else {
                   1016:         $viewtitle = &mt('View Submissions');
                   1017:     }
                   1018:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1019:                   .$submission_options
                   1020:                   .&Apache::lonhtmlcommon::row_closure();
                   1021: 
1.745     raeburn  1022:     my $closure;
                   1023:     if (($is_tool) && (exists($env{'form.Status'}))) {
                   1024:         $closure = 1;
                   1025:     }
1.561     bisitz   1026:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1027:                   .'<select name="increment">'
                   1028:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1029:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1030:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1031:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1032:                   .'</select>'
1.745     raeburn  1033:                   .&Apache::lonhtmlcommon::row_closure($closure);
1.485     albertel 1034: 
                   1035:     $gradeTable .= 
1.432     banghart 1036:         &build_section_inputs().
1.45      ng       1037: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1038: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1039: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1040: 
1.618     www      1041:     if (exists($env{'form.Status'})) {
1.561     bisitz   1042: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1043:     } else {
1.745     raeburn  1044:         if ($is_tool) {
                   1045:             $closure = 1;
                   1046:         }
1.561     bisitz   1047:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1048:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1049:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1.745     raeburn  1050:                       .&Apache::lonhtmlcommon::row_closure($closure);
1.124     ng       1051:     }
1.112     ng       1052: 
1.745     raeburn  1053:     unless ($is_tool) {
                   1054:         $closure = 1;
                   1055:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1056:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1057:                       .&Apache::lonhtmlcommon::row_closure($closure);
                   1058:     }
                   1059:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
                   1060:     my $regrademsg;
                   1061:     if ($is_tool) {
                   1062:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   1063:     } else {
                   1064:         $regrademsg = &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.");
                   1065:     }
1.561     bisitz   1066:     $gradeTable .= '<p>'
1.745     raeburn  1067:                   .$regrademsg."\n"
1.561     bisitz   1068:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1069:                   .'</p>';
1.249     albertel 1070: 
                   1071: # checkall buttons
                   1072:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1073:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1074:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1075:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1076:     $gradeTable.=&check_buttons();
1.450     banghart 1077:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1078:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1079: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1080:     my $loop = 0;
                   1081:     while ($loop < 2) {
1.485     albertel 1082: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1083: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1084: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1085: 	    foreach my $part (sort(@$partlist)) {
                   1086: 		my $display_part=
                   1087: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1088: 		$gradeTable.=
                   1089: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1090: 	    }
1.301     albertel 1091: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1092: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1093: 	}
                   1094: 	$loop++;
1.126     ng       1095: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1096:     }
1.474     albertel 1097:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1098: 
1.45      ng       1099:     my $ctr = 0;
1.294     albertel 1100:     foreach my $student (sort 
                   1101: 			 {
                   1102: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1103: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1104: 			     }
                   1105: 			     return $a cmp $b;
                   1106: 			 }
                   1107: 			 (keys(%$fullname))) {
1.41      ng       1108: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1109: 
1.110     ng       1110: 	my %status = ();
1.301     albertel 1111: 
                   1112: 	if ($submitonly eq 'queued') {
                   1113: 	    my %queue_status = 
                   1114: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1115: 							$udom,$uname);
                   1116: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1117: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1118: 	}
                   1119: 
1.618     www      1120: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1121: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1122: 	    my $submitted = 0;
1.164     albertel 1123: 	    my $graded = 0;
1.248     albertel 1124: 	    my $incorrect = 0;
1.110     ng       1125: 	    foreach (keys(%status)) {
1.145     albertel 1126: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1127: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1128: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1129: 		
1.110     ng       1130: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1131: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1132: 		    $submitted = 0;
1.150     albertel 1133: 		    my ($part)=split(/\./,$partid);
1.110     ng       1134: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1135: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1136: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1137: 		}
1.41      ng       1138: 	    }
1.248     albertel 1139: 	    
1.156     albertel 1140: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1141: 				     $submitonly eq 'incorrect' ||
                   1142: 				     $submitonly eq 'graded'));
1.248     albertel 1143: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1144: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1145: 	}
1.34      ng       1146: 
1.45      ng       1147: 	$ctr++;
1.249     albertel 1148: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1149:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1150: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1151: 	    if ($ctr%2 ==1) {
                   1152: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1153: 	    }
1.126     ng       1154: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1155:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1156:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1157: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1158: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1159: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1160: 
1.618     www      1161: 	    if ($submitonly ne 'all') {
1.524     raeburn  1162: 		foreach (sort(keys(%status))) {
1.485     albertel 1163: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1164: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1165: 		}
1.41      ng       1166: 	    }
1.126     ng       1167: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1168: 	    if ($ctr%2 ==0) {
                   1169: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1170: 	    }
1.41      ng       1171: 	}
                   1172:     }
1.110     ng       1173:     if ($ctr%2 ==1) {
1.126     ng       1174: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1175: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1176: 		foreach (@$partlist) {
                   1177: 		    $gradeTable.='<td>&nbsp;</td>';
                   1178: 		}
1.301     albertel 1179: 	    } elsif ($submitonly eq 'queued') {
                   1180: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1181: 	    }
1.474     albertel 1182: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1183:     }
                   1184: 
1.474     albertel 1185:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1186:         '<input type="button" '.
                   1187:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1188:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1189:     if ($ctr == 0) {
1.96      albertel 1190: 	my $num_students=(scalar(keys(%$fullname)));
                   1191: 	if ($num_students eq 0) {
1.485     albertel 1192: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1193: 	} else {
1.171     albertel 1194: 	    my $submissions='submissions';
                   1195: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1196: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1197: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1198: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1199: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1200: 		    $num_students).
                   1201: 		'</span><br />';
1.96      albertel 1202: 	}
1.46      ng       1203:     } elsif ($ctr == 1) {
1.474     albertel 1204: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1205:     }
                   1206:     $request->print($gradeTable);
1.44      ng       1207:     return '';
1.10      ng       1208: }
                   1209: 
1.44      ng       1210: #---- Called from the listStudents routine
1.249     albertel 1211: 
                   1212: sub check_script {
                   1213:     my ($form, $type)=@_;
1.597     wenzelju 1214:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1215:     function checkall() {
                   1216:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1217:             ele = document.forms.'.$form.'.elements[i];
                   1218:             if (ele.name == "'.$type.'") {
                   1219:             document.forms.'.$form.'.elements[i].checked=true;
                   1220:                                        }
                   1221:         }
                   1222:     }
                   1223: 
                   1224:     function checksec() {
                   1225:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1226:             ele = document.forms.'.$form.'.elements[i];
                   1227:            string = document.forms.'.$form.'.chksec.value;
                   1228:            if
                   1229:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1230:               document.forms.'.$form.'.elements[i].checked=true;
                   1231:             }
                   1232:         }
                   1233:     }
                   1234: 
                   1235: 
                   1236:     function uncheckall() {
                   1237:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1238:             ele = document.forms.'.$form.'.elements[i];
                   1239:             if (ele.name == "'.$type.'") {
                   1240:             document.forms.'.$form.'.elements[i].checked=false;
                   1241:                                        }
                   1242:         }
                   1243:     }
                   1244: 
1.597     wenzelju 1245: '."\n");
1.249     albertel 1246:     return $chkallscript;
                   1247: }
                   1248: 
                   1249: sub check_buttons {
1.485     albertel 1250:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1251:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1252:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1253:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1254:     return $buttons;
                   1255: }
                   1256: 
1.44      ng       1257: #     Displays the submissions for one student or a group of students
1.34      ng       1258: sub processGroup {
1.619     www      1259:     my ($request,$symb)  = @_;
1.41      ng       1260:     my $ctr        = 0;
1.155     albertel 1261:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1262:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1263: 
1.396     banghart 1264:     foreach my $student (@stuchecked) {
                   1265: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1266: 	$env{'form.student'}        = $uname;
                   1267: 	$env{'form.userdom'}        = $udom;
                   1268: 	$env{'form.fullname'}       = $fullname;
1.619     www      1269: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1270: 	$ctr++;
                   1271:     }
                   1272:     return '';
1.35      ng       1273: }
1.34      ng       1274: 
1.44      ng       1275: #------------------------------------------------------------------------------------
                   1276: #
                   1277: #-------------------------- Next few routines handles grading by student, essentially
                   1278: #                           handles essay response type problem/part
                   1279: #
                   1280: #--- Javascript to handle the submission page functionality ---
                   1281: sub sub_page_js {
                   1282:     my $request = shift;
1.736     damieng  1283:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1284:     &js_escape(\$alertmsg);
1.597     wenzelju 1285:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1286:     function updateRadio(formname,id,weight) {
1.125     ng       1287: 	var gradeBox = formname["GD_BOX"+id];
                   1288: 	var radioButton = formname["RADVAL"+id];
                   1289: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1290: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1291: 	gradeBox.value = pts;
                   1292: 	var resetbox = false;
                   1293: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1294: 	    alert("$alertmsg"+pts);
1.71      ng       1295: 	    for (var i=0; i<radioButton.length; i++) {
                   1296: 		if (radioButton[i].checked) {
                   1297: 		    gradeBox.value = i;
                   1298: 		    resetbox = true;
                   1299: 		}
                   1300: 	    }
                   1301: 	    if (!resetbox) {
                   1302: 		formtextbox.value = "";
                   1303: 	    }
                   1304: 	    return;
1.44      ng       1305: 	}
1.71      ng       1306: 
                   1307: 	if (pts > weight) {
                   1308: 	    var resp = confirm("You entered a value ("+pts+
                   1309: 			       ") greater than the weight for the part. Accept?");
                   1310: 	    if (resp == false) {
1.125     ng       1311: 		gradeBox.value = oldpts;
1.71      ng       1312: 		return;
                   1313: 	    }
1.44      ng       1314: 	}
1.13      albertel 1315: 
1.71      ng       1316: 	for (var i=0; i<radioButton.length; i++) {
                   1317: 	    radioButton[i].checked=false;
                   1318: 	    if (pts == i && pts != "") {
                   1319: 		radioButton[i].checked=true;
                   1320: 	    }
                   1321: 	}
                   1322: 	updateSelect(formname,id);
1.125     ng       1323: 	formname["stores"+id].value = "0";
1.41      ng       1324:     }
1.5       albertel 1325: 
1.72      ng       1326:     function writeBox(formname,id,pts) {
1.125     ng       1327: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1328: 	if (checkSolved(formname,id) == 'update') {
                   1329: 	    gradeBox.value = pts;
                   1330: 	} else {
1.125     ng       1331: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1332: 	    gradeBox.value = oldpts;
1.125     ng       1333: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1334: 	    for (var i=0; i<radioButton.length; i++) {
                   1335: 		radioButton[i].checked=false;
1.72      ng       1336: 		if (i == oldpts) {
1.71      ng       1337: 		    radioButton[i].checked=true;
                   1338: 		}
                   1339: 	    }
1.41      ng       1340: 	}
1.125     ng       1341: 	formname["stores"+id].value = "0";
1.71      ng       1342: 	updateSelect(formname,id);
                   1343: 	return;
1.41      ng       1344:     }
1.44      ng       1345: 
1.71      ng       1346:     function clearRadBox(formname,id) {
                   1347: 	if (checkSolved(formname,id) == 'noupdate') {
                   1348: 	    updateSelect(formname,id);
                   1349: 	    return;
                   1350: 	}
1.125     ng       1351: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1352: 	for (var i=0; i<gradeSelect.length; i++) {
                   1353: 	    if (gradeSelect[i].selected) {
                   1354: 		var selectx=i;
                   1355: 	    }
                   1356: 	}
1.125     ng       1357: 	var stores = formname["stores"+id];
1.71      ng       1358: 	if (selectx == stores.value) { return };
1.125     ng       1359: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1360: 	gradeBox.value = "";
1.125     ng       1361: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1362: 	for (var i=0; i<radioButton.length; i++) {
                   1363: 	    radioButton[i].checked=false;
                   1364: 	}
                   1365: 	stores.value = selectx;
                   1366:     }
1.5       albertel 1367: 
1.71      ng       1368:     function checkSolved(formname,id) {
1.125     ng       1369: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1370: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1371: 	    if (!reply) {return "noupdate";}
1.120     ng       1372: 	    formname.overRideScore.value = 'yes';
1.41      ng       1373: 	}
1.71      ng       1374: 	return "update";
1.13      albertel 1375:     }
1.71      ng       1376: 
                   1377:     function updateSelect(formname,id) {
1.125     ng       1378: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1379: 	return;
1.41      ng       1380:     }
1.33      ng       1381: 
1.121     ng       1382: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1383:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1384: 	formname.gradeOpt.value = val;
1.71      ng       1385: 	if (val == "Save & Next") {
                   1386: 	    for (i=0;i<=total;i++) {
                   1387: 		for (j=0;j<parttot;j++) {
1.125     ng       1388: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1389: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1390: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1391: 			if (points == "") {
1.125     ng       1392: 			    var name = formname["name"+i].value;
1.129     ng       1393: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1394: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1395: 					       ", part "+partid+". Continue?");
1.71      ng       1396: 			    if (resp == false) {
1.125     ng       1397: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1398: 				return false;
                   1399: 			    }
                   1400: 			}
                   1401: 		    }
                   1402: 		}
                   1403: 	    }
                   1404: 	}
1.120     ng       1405: 	formname.submit();
                   1406:     }
                   1407: 
1.71      ng       1408: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1409:     function checkSubmitPage(formname,total) {
                   1410: 	noscore = new Array(100);
                   1411: 	var ptr = 0;
                   1412: 	for (i=1;i<total;i++) {
1.125     ng       1413: 	    var partid = formname["q_"+i].value;
1.127     ng       1414: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1415: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1416: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1417: 		if (points == "" && status != "correct_by_student") {
                   1418: 		    noscore[ptr] = i;
                   1419: 		    ptr++;
                   1420: 		}
                   1421: 	    }
                   1422: 	}
                   1423: 	if (ptr != 0) {
                   1424: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1425: 	    var prolist = "";
                   1426: 	    if (ptr == 1) {
                   1427: 		prolist = noscore[0];
                   1428: 	    } else {
                   1429: 		var i = 0;
                   1430: 		while (i < ptr-1) {
                   1431: 		    prolist += noscore[i]+", ";
                   1432: 		    i++;
                   1433: 		}
                   1434: 		prolist += "and "+noscore[i];
                   1435: 	    }
                   1436: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1437: 	    if (resp == false) {
                   1438: 		return false;
                   1439: 	    }
                   1440: 	}
1.45      ng       1441: 
1.71      ng       1442: 	formname.submit();
                   1443:     }
                   1444: SUBJAVASCRIPT
                   1445: }
1.45      ng       1446: 
1.71      ng       1447: #--- javascript for essay type problem --
                   1448: sub sub_page_kw_js {
                   1449:     my $request = shift;
1.80      ng       1450:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1451:     &commonJSfunctions($request);
1.350     albertel 1452: 
1.629     www      1453:     my $inner_js_msg_central= (<<INNERJS);
                   1454: <script type="text/javascript">
1.350     albertel 1455:     function checkInput() {
                   1456:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1457:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1458:       var usrctr = document.msgcenter.usrctr.value;
                   1459:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1460:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1461: 
                   1462:       var msgchk = "";
                   1463:       if (document.msgcenter.subchk.checked) {
                   1464:          msgchk = "msgsub,";
                   1465:       }
                   1466:       var includemsg = 0;
                   1467:       for (var i=1; i<=nmsg; i++) {
                   1468:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1469:           var frmmsg = document.msgcenter["msg"+i];
                   1470:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1471:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1472:           showflg.value = "1";
                   1473:           var chkbox = document.msgcenter["msgn"+i];
                   1474:           if (chkbox.checked) {
                   1475:              msgchk += "savemsg"+i+",";
                   1476:              includemsg = 1;
                   1477:           }
                   1478:       }
                   1479:       if (document.msgcenter.newmsgchk.checked) {
                   1480:          msgchk += "newmsg"+usrctr;
                   1481:          includemsg = 1;
                   1482:       }
                   1483:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1484:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1485:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1486:       includemsg.value = msgchk;
                   1487: 
                   1488:       self.close()
                   1489: 
                   1490:     }
1.629     www      1491: </script>
1.350     albertel 1492: INNERJS
                   1493: 
1.629     www      1494:     my $inner_js_highlight_central= (<<INNERJS);
                   1495: <script type="text/javascript">
1.351     albertel 1496:     function updateChoice(flag) {
                   1497:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1498:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1499:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1500:       opener.document.SCORE.refresh.value = "on";
                   1501:       if (opener.document.SCORE.keywords.value!=""){
                   1502:          opener.document.SCORE.submit();
                   1503:       }
                   1504:       self.close()
                   1505:     }
1.629     www      1506: </script>
1.351     albertel 1507: INNERJS
                   1508: 
                   1509:     my $start_page_msg_central = 
                   1510:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1511: 				       {'js_ready'  => 1,
                   1512: 					'only_body' => 1,
                   1513: 					'bgcolor'   =>'#FFFFFF',});
                   1514:     my $end_page_msg_central = 
                   1515: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1516: 
                   1517: 
                   1518:     my $start_page_highlight_central = 
                   1519:         &Apache::loncommon::start_page('Highlight Central',
                   1520: 				       $inner_js_highlight_central,
1.350     albertel 1521: 				       {'js_ready'  => 1,
                   1522: 					'only_body' => 1,
                   1523: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1524:     my $end_page_highlight_central = 
1.350     albertel 1525: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1526: 
1.219     www      1527:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1528:     $docopen=~s/^document\.//;
1.736     damieng  1529:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1530:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1531:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1532:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1533:                 col1 => 'red',
                   1534:                 col2 => 'green',
                   1535:                 col3 => 'blue',
                   1536:                 siz1 => 'normal',
                   1537:                 siz2 => '+1',
                   1538:                 siz3 => '+2',
                   1539:                 sty1 => 'normal',
                   1540:                 sty2 => 'italic',
                   1541:                 sty3 => 'bold',
                   1542:              );
                   1543:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1544:                 comp => 'Compose Message for: ',
                   1545:                 incl => 'Include',
1.656     raeburn  1546:                 type => 'Type',
1.652     raeburn  1547:                 subj => 'Subject',
                   1548:                 mesa => 'Message',
                   1549:                 new  => 'New',
                   1550:                 save => 'Save',
                   1551:                 canc => 'Cancel',
                   1552:                 kehi => 'Keyword Highlight Options',
                   1553:                 txtc => 'Text Color',
                   1554:                 font => 'Font Size',
1.656     raeburn  1555:                 fnst => 'Font Style',
1.652     raeburn  1556:              );
1.736     damieng  1557:     &js_escape(\%js_lt);
                   1558:     &html_escape(\%html_js_lt);
                   1559:     &js_escape(\%html_js_lt);
1.597     wenzelju 1560:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1561: 
1.44      ng       1562: //===================== Show list of keywords ====================
1.122     ng       1563:   function keywords(formname) {
1.736     damieng  1564:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1565:     if (nret==null) return;
1.122     ng       1566:     formname.keywords.value = nret;
1.44      ng       1567: 
1.122     ng       1568:     if (formname.keywords.value != "") {
1.128     ng       1569: 	formname.refresh.value = "on";
1.122     ng       1570: 	formname.submit();
1.44      ng       1571:     }
                   1572:     return;
                   1573:   }
                   1574: 
                   1575: //===================== Script to view submitted by ==================
                   1576:   function viewSubmitter(submitter) {
                   1577:     document.SCORE.refresh.value = "on";
                   1578:     document.SCORE.NCT.value = "1";
                   1579:     document.SCORE.unamedom0.value = submitter;
                   1580:     document.SCORE.submit();
                   1581:     return;
                   1582:   }
                   1583: 
                   1584: //===================== Script to add keyword(s) ==================
                   1585:   function getSel() {
                   1586:     if (document.getSelection) txt = document.getSelection();
                   1587:     else if (document.selection) txt = document.selection.createRange().text;
                   1588:     else return;
                   1589:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1590:     if (cleantxt=="") {
1.736     damieng  1591: 	alert("$js_lt{'plse'}");
1.44      ng       1592: 	return;
                   1593:     }
1.736     damieng  1594:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1595:     if (nret==null) return;
1.127     ng       1596:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1597:     if (document.SCORE.keywords.value != "") {
1.127     ng       1598: 	document.SCORE.refresh.value = "on";
1.44      ng       1599: 	document.SCORE.submit();
                   1600:     }
                   1601:     return;
                   1602:   }
                   1603: 
                   1604: //====================== Script for composing message ==============
1.80      ng       1605:    // preload images
                   1606:    img1 = new Image();
                   1607:    img1.src = "$iconpath/mailbkgrd.gif";
                   1608:    img2 = new Image();
                   1609:    img2.src = "$iconpath/mailto.gif";
                   1610: 
1.44      ng       1611:   function msgCenter(msgform,usrctr,fullname) {
                   1612:     var Nmsg  = msgform.savemsgN.value;
                   1613:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1614:     var subject = msgform.msgsub.value;
1.127     ng       1615:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1616:     re = /msgsub/;
                   1617:     var shwsel = "";
                   1618:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1619:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1620:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1621:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1622: 	var testmsg = "savemsg"+i+",";
                   1623: 	re = new RegExp(testmsg,"g");
1.44      ng       1624: 	shwsel = "";
                   1625: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1626: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1627: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1628: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1629: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1630:     }
1.125     ng       1631:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1632:     shwsel = "";
                   1633:     re = /newmsg/;
                   1634:     if (re.test(msgchk)) { shwsel = "checked" }
                   1635:     newMsg(newmsg,shwsel);
                   1636:     msgTail(); 
                   1637:     return;
                   1638:   }
                   1639: 
1.123     ng       1640:   function checkEntities(strx) {
                   1641:     if (strx.length == 0) return strx;
                   1642:     var orgStr = ["&", "<", ">", '"']; 
                   1643:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1644:     var counter = 0;
                   1645:     while (counter < 4) {
                   1646: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1647: 	counter++;
                   1648:     }
                   1649:     return strx;
                   1650:   }
                   1651: 
                   1652:   function strReplace(strx, orgStr, newStr) {
                   1653:     return strx.split(orgStr).join(newStr);
                   1654:   }
                   1655: 
1.44      ng       1656:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1657:     var height = 70*Nmsg+250;
1.44      ng       1658:     if (height > 600) {
                   1659: 	height = 600;
                   1660:     }
1.118     ng       1661:     var xpos = (screen.width-600)/2;
                   1662:     xpos = (xpos < 0) ? '0' : xpos;
                   1663:     var ypos = (screen.height-height)/2-30;
                   1664:     ypos = (ypos < 0) ? '0' : ypos;
                   1665: 
1.668     www      1666:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1667:     pWin.focus();
                   1668:     pDoc = pWin.document;
1.219     www      1669:     pDoc.$docopen;
1.351     albertel 1670:     pDoc.write('$start_page_msg_central');
1.76      ng       1671: 
                   1672:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1673:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1674:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1675: 
1.676     golterma 1676:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1677:     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       1678: }
                   1679:     function displaySubject(msg,shwsel) {
1.76      ng       1680:     pDoc = pWin.document;
1.676     golterma 1681:     pDoc.write("<tr>");
                   1682:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1683:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1684:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1685: }
                   1686: 
1.72      ng       1687:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1688:     pDoc = pWin.document;
1.676     golterma 1689:     pDoc.write("<tr>");
                   1690:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1691:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1692:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1693: }
                   1694: 
                   1695:   function newMsg(newmsg,shwsel) {
1.76      ng       1696:     pDoc = pWin.document;
1.676     golterma 1697:     pDoc.write("<tr>");
                   1698:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1699:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1700:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1701: }
                   1702: 
                   1703:   function msgTail() {
1.76      ng       1704:     pDoc = pWin.document;
1.676     golterma 1705:     //pDoc.write("<\\/table>");
1.465     albertel 1706:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1707:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1708:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1709:     pDoc.write("<\\/form>");
1.351     albertel 1710:     pDoc.write('$end_page_msg_central');
1.128     ng       1711:     pDoc.close();
1.44      ng       1712: }
                   1713: 
                   1714: //====================== Script for keyword highlight options ==============
                   1715:   function kwhighlight() {
                   1716:     var kwclr    = document.SCORE.kwclr.value;
                   1717:     var kwsize   = document.SCORE.kwsize.value;
                   1718:     var kwstyle  = document.SCORE.kwstyle.value;
                   1719:     var redsel = "";
                   1720:     var grnsel = "";
                   1721:     var blusel = "";
1.736     damieng  1722:     var txtcol1 = "$js_lt{'col1'}";
                   1723:     var txtcol2 = "$js_lt{'col2'}";
                   1724:     var txtcol3 = "$js_lt{'col3'}";
                   1725:     var txtsiz1 = "$js_lt{'siz1'}";
                   1726:     var txtsiz2 = "$js_lt{'siz2'}";
                   1727:     var txtsiz3 = "$js_lt{'siz3'}";
                   1728:     var txtsty1 = "$js_lt{'sty1'}";
                   1729:     var txtsty2 = "$js_lt{'sty2'}";
                   1730:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1731:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1732:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1733:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1734:     var sznsel = "";
                   1735:     var sz1sel = "";
                   1736:     var sz2sel = "";
1.718     bisitz   1737:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1738:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1739:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1740:     var synsel = "";
                   1741:     var syisel = "";
                   1742:     var sybsel = "";
1.718     bisitz   1743:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1744:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1745:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1746:     highlightCentral();
1.718     bisitz   1747:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1748:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1749:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1750:     highlightend();
                   1751:     return;
                   1752:   }
                   1753: 
                   1754:   function highlightCentral() {
1.76      ng       1755: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1756:     var xpos = (screen.width-400)/2;
                   1757:     xpos = (xpos < 0) ? '0' : xpos;
                   1758:     var ypos = (screen.height-330)/2-30;
                   1759:     ypos = (ypos < 0) ? '0' : ypos;
                   1760: 
1.206     albertel 1761:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1762:     hwdWin.focus();
                   1763:     var hDoc = hwdWin.document;
1.219     www      1764:     hDoc.$docopen;
1.351     albertel 1765:     hDoc.write('$start_page_highlight_central');
1.76      ng       1766:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1767:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1768: 
1.718     bisitz   1769:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1770:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1771:   }
                   1772: 
                   1773:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1774:     var hDoc = hwdWin.document;
1.718     bisitz   1775:     hDoc.write("<tr>");
1.76      ng       1776:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1777:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1778:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1779:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1780:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1781:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1782:     hDoc.write("<\\/tr>");
1.44      ng       1783:   }
                   1784: 
                   1785:   function highlightend() { 
1.76      ng       1786:     var hDoc = hwdWin.document;
1.718     bisitz   1787:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1788:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1789:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1790:     hDoc.write("<\\/form>");
1.351     albertel 1791:     hDoc.write('$end_page_highlight_central');
1.128     ng       1792:     hDoc.close();
1.44      ng       1793:   }
                   1794: 
                   1795: SUBJAVASCRIPT
                   1796: }
                   1797: 
1.349     albertel 1798: sub get_increment {
1.348     bowersj2 1799:     my $increment = $env{'form.increment'};
                   1800:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1801:         $increment != .1) {
                   1802:         $increment = 1;
                   1803:     }
                   1804:     return $increment;
                   1805: }
                   1806: 
1.585     bisitz   1807: sub gradeBox_start {
                   1808:     return (
                   1809:         &Apache::loncommon::start_data_table()
                   1810:        .&Apache::loncommon::start_data_table_header_row()
                   1811:        .'<th>'.&mt('Part').'</th>'
                   1812:        .'<th>'.&mt('Points').'</th>'
                   1813:        .'<th>&nbsp;</th>'
                   1814:        .'<th>'.&mt('Assign Grade').'</th>'
                   1815:        .'<th>'.&mt('Weight').'</th>'
                   1816:        .'<th>'.&mt('Grade Status').'</th>'
                   1817:        .&Apache::loncommon::end_data_table_header_row()
                   1818:     );
                   1819: }
                   1820: 
                   1821: sub gradeBox_end {
                   1822:     return (
                   1823:         &Apache::loncommon::end_data_table()
                   1824:     );
                   1825: }
1.71      ng       1826: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1827: sub gradeBox {
1.322     albertel 1828:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1829:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1830: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1831:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1832:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1833:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1834:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1835:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1836: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1837:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1838:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1839:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1840: 				       [$partid]);
                   1841:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1842:     if ($last_resets{$partid}) {
                   1843:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1844:     }
1.695     bisitz   1845:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1846:     my $ctr = 0;
1.348     bowersj2 1847:     my $thisweight = 0;
1.349     albertel 1848:     my $increment = &get_increment();
1.485     albertel 1849: 
                   1850:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1851:     while ($thisweight<=$wgt) {
1.532     bisitz   1852: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1853:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1854: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1855: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1856: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1857:         $thisweight += $increment;
1.71      ng       1858: 	$ctr++;
                   1859:     }
1.485     albertel 1860:     $radio.='</tr></table>';
                   1861: 
                   1862:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1863: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1864: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1865: 	$wgt.')" /></td>'."\n";
1.485     albertel 1866:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1867: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1868: 	' </td>'."\n";
                   1869:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1870: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1871:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1872: 	$line.='<option></option>'.
                   1873: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1874:     } else {
1.485     albertel 1875: 	$line.='<option selected="selected"></option>'.
                   1876: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1877:     }
1.485     albertel 1878:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1879: 
                   1880: 
                   1881:     $result .= 
1.695     bisitz   1882: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1883:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1884:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1885:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1886: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1887: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1888: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1889:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1890:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1891:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1892:         $aggtries.'" />'."\n";
1.582     raeburn  1893:     my $res_error;
                   1894:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1895:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1896:     if ($res_error) {
                   1897:         return &navmap_errormsg();
                   1898:     }
1.318     banghart 1899:     return $result;
                   1900: }
1.322     albertel 1901: 
                   1902: sub handback_box {
1.623     www      1903:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1904:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1905:     my (@respids);
1.652     raeburn  1906:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1907:     foreach my $part_response_id (@part_response_id) {
                   1908:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1909:         if ($part eq $partid) {
1.375     albertel 1910:             push(@respids,$resp);
1.323     banghart 1911:         }
                   1912:     }
1.318     banghart 1913:     my $result;
1.323     banghart 1914:     foreach my $respid (@respids) {
1.322     albertel 1915: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1916: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1917: 	next if (!@$files);
1.654     raeburn  1918: 	my $file_counter = 0;
1.313     banghart 1919: 	foreach my $file (@$files) {
1.368     banghart 1920: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1921:                 $file_counter++;
1.368     banghart 1922:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1923:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1924:     	        $file_disp = "$name.$ext";
                   1925:     	        $file = $file_path.$file_disp;
                   1926:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1927:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1928:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1929:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1930: 	    }
1.322     albertel 1931: 	}
1.654     raeburn  1932:         if ($file_counter) {
                   1933:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1934:                        '<span class="LC_info">'.
                   1935:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1936:         }
1.313     banghart 1937:     }
1.318     banghart 1938:     return $result;    
1.71      ng       1939: }
1.44      ng       1940: 
1.58      albertel 1941: sub show_problem {
1.382     albertel 1942:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1943:     my $rendered;
1.382     albertel 1944:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1945:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1946:     if ($mode eq 'both' or $mode eq 'text') {
                   1947: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1948: 						       $env{'request.course.id'},
                   1949: 						       undef,\%form);
1.144     albertel 1950:     }
1.58      albertel 1951:     if ($removeform) {
                   1952: 	$rendered=~s|<form(.*?)>||g;
                   1953: 	$rendered=~s|</form>||g;
1.374     albertel 1954: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1955:     }
1.144     albertel 1956:     my $companswer;
                   1957:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1958: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1959: 	$companswer=
                   1960: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1961: 						    $env{'request.course.id'},
                   1962: 						    %form);
1.144     albertel 1963:     }
1.58      albertel 1964:     if ($removeform) {
                   1965: 	$companswer=~s|<form(.*?)>||g;
                   1966: 	$companswer=~s|</form>||g;
1.144     albertel 1967: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1968:     }
1.671     raeburn  1969:     my $renderheading = &mt('View of the problem');
                   1970:     my $answerheading = &mt('Correct answer');
                   1971:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1972:         my $stu_fullname = $env{'form.fullname'};
                   1973:         if ($stu_fullname eq '') {
                   1974:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1975:         }
                   1976:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1977:         if ($forwhom ne '') {
                   1978:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1979:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1980:         }
                   1981:     }
1.468     albertel 1982:     $rendered=
1.588     bisitz   1983:         '<div class="LC_Box">'
1.671     raeburn  1984:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1985:        .$rendered
                   1986:        .'</div>';
1.468     albertel 1987:     $companswer=
1.588     bisitz   1988:         '<div class="LC_Box">'
1.671     raeburn  1989:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1990:        .$companswer
                   1991:        .'</div>';
1.468     albertel 1992:     my $result;
1.144     albertel 1993:     if ($mode eq 'both') {
1.588     bisitz   1994:         $result=$rendered.$companswer;
1.144     albertel 1995:     } elsif ($mode eq 'text') {
1.588     bisitz   1996:         $result=$rendered;
1.144     albertel 1997:     } elsif ($mode eq 'answer') {
1.588     bisitz   1998:         $result=$companswer;
1.144     albertel 1999:     }
1.71      ng       2000:     return $result;
1.58      albertel 2001: }
1.397     albertel 2002: 
1.396     banghart 2003: sub files_exist {
                   2004:     my ($r, $symb) = @_;
                   2005:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2006:     foreach my $student (@students) {
                   2007:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2008:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2009: 					      $udom,$uname);
1.396     banghart 2010:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2011:         foreach my $submission (@$string) {
                   2012:             my ($partid,$respid) =
                   2013: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2014:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2015: 					   \%record);
                   2016:             return 1 if (@$files);
1.396     banghart 2017:         }
                   2018:     }
1.397     albertel 2019:     return 0;
1.396     banghart 2020: }
1.397     albertel 2021: 
1.394     banghart 2022: sub download_all_link {
                   2023:     my ($r,$symb) = @_;
1.621     www      2024:     unless (&files_exist($r, $symb)) {
                   2025:        $r->print(&mt('There are currently no submitted documents.'));
                   2026:        return;
                   2027:     }
1.395     albertel 2028:     my $all_students = 
                   2029: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2030: 
                   2031:     my $parts =
                   2032: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2033: 
1.394     banghart 2034:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2035:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2036:                              'cgi.'.$identifier.'.symb' => $symb,
                   2037:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2038:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2039: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2040:     return;
                   2041: }
                   2042: 
                   2043: sub submit_download_link {
                   2044:     my ($request,$symb) = @_;
                   2045:     if (!$symb) { return ''; }
                   2046: #FIXME: Figure out which type of problem this is and provide appropriate download
1.750   ! raeburn  2047:     my $res_error;
        !          2048:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
        !          2049:     if (ref($res_error)) {
        !          2050:         if ($$res_error) {
        !          2051:             $request->print(&mt('An error occurred retrieving response types'));
        !          2052:             return;
        !          2053:         }
        !          2054:     }
        !          2055:     my ($numupload,$numessay) = (0,0);
        !          2056:     if (ref($responseType) eq 'HASH') {
        !          2057:         foreach my $part (sort(keys(%$responseType))) {
        !          2058:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
        !          2059:                 my $responsetype = $responseType->{$part}->{$id};
        !          2060:                 if ($responsetype eq 'essay') {
        !          2061:                     my $uploadedfiletypes =
        !          2062:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
        !          2063:                     if ($uploadedfiletypes) {
        !          2064:                         $numupload++;
        !          2065:                     } else {
        !          2066:                         $numessay++;
        !          2067:                     }
        !          2068:                 }
        !          2069:             }
        !          2070:         }
        !          2071:     }
        !          2072:     if (($numupload) || ($numessay)) {
        !          2073:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
        !          2074:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
        !          2075:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
        !          2076:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
        !          2077:         if (ref($fullname) eq 'HASH') {
        !          2078:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
        !          2079:             if (@students) {
        !          2080:                 @{$env{'form.stuinfo'}} = @students;
        !          2081:                 if ($numupload) {
        !          2082:                     &download_all_link($request,$symb);
        !          2083:                 }
        !          2084: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
        !          2085: # Needs to omit user's identity if resource instance is for an anonymous survey.
        !          2086:             } else {
        !          2087:                 $request->print(&mt('No students match the criteria you selected'));
        !          2088:             }
        !          2089:         } else {
        !          2090:             $request->print(&mt('Could not retrieve student information'));
        !          2091:         }
        !          2092:     } else {
        !          2093:         $request->print(&mt('No essayresponse items found'));
        !          2094:     }
        !          2095:     return;
1.394     banghart 2096: }
1.395     albertel 2097: 
1.432     banghart 2098: sub build_section_inputs {
                   2099:     my $section_inputs;
                   2100:     if ($env{'form.section'} eq '') {
                   2101:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2102:     } else {
                   2103:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2104:         foreach my $section (@sections) {
1.432     banghart 2105:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2106:         }
                   2107:     }
                   2108:     return $section_inputs;
                   2109: }
                   2110: 
1.44      ng       2111: # --------------------------- show submissions of a student, option to grade 
                   2112: sub submission {
1.608     www      2113:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2114:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2115:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2116:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2117:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2118: 
1.605     www      2119:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2120:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2121:     my $is_tool = ($symb =~ /ext\.tool$/);
1.104     albertel 2122: 
                   2123:     if (!&canview($usec)) {
1.712     bisitz   2124:         $request->print(
                   2125:             '<span class="LC_warning">'.
1.713     bisitz   2126:             &mt('Unable to view requested student.').
1.712     bisitz   2127:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2128:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2129:             '</span>');
1.104     albertel 2130: 	return;
                   2131:     }
                   2132: 
1.257     albertel 2133:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2134:     unless ($is_tool) { 
                   2135:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2136:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2137:     }
1.257     albertel 2138:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2139:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2140: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2141: 	'/check.gif" height="16" border="0" />';
1.41      ng       2142: 
                   2143:     # header info
                   2144:     if ($counter == 0) {
                   2145: 	&sub_page_js($request);
1.621     www      2146: 	&sub_page_kw_js($request);
1.118     ng       2147: 
1.44      ng       2148: 	# option to display problem, only once else it cause problems 
                   2149:         # with the form later since the problem has a form.
1.257     albertel 2150: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2151: 	    my $mode;
1.257     albertel 2152: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2153: 		$mode='both';
1.257     albertel 2154: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2155: 		$mode='text';
1.257     albertel 2156: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2157: 		$mode='answer';
                   2158: 	    }
1.329     albertel 2159: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2160: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2161: 	}
1.441     www      2162: 
1.704     raeburn  2163: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2164:         # if this subroutine has been called once.
1.41      ng       2165: 	my %keyhash = ();
1.624     www      2166: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2167:         if (1) {
1.41      ng       2168: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2169: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2170: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2171: 
1.257     albertel 2172: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2173: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2174: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2175: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2176: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2177: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2178: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2179: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2180: 	}
1.257     albertel 2181: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2182: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2183: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2184: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2185: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2186: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2187: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2188: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2189: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2190: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2191: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2192: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2193: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2194: 			&build_section_inputs().
1.326     albertel 2195: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2196: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2197: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2198: #	if ($env{'form.handgrade'} eq 'yes') {
                   2199:         if (1) {
1.257     albertel 2200: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2201: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2202: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2203: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2204: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2205: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2206: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2207: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2208: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2209: 	    }
1.123     ng       2210: 	}
1.41      ng       2211: 	
                   2212: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2213: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2214: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2215: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2216: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2217: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2218: 		'" />'."\n".
                   2219: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2220: 	    $cts++;
                   2221: 	}
                   2222: 	$request->print($prnmsg);
1.32      ng       2223: 
1.624     www      2224: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2225:         unless ($is_tool) {
1.652     raeburn  2226: 
                   2227:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2228:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2229:                           keyw => 'Keyword Options',
1.655     raeburn  2230:                           list => 'List',
1.652     raeburn  2231:                           past => 'Paste Selection to List',
1.661     www      2232:                           high => 'Highlight Attribute',
1.652     raeburn  2233:                      );    
1.88      www      2234: #
                   2235: # Print out the keyword options line
                   2236: #
1.718     bisitz   2237: 	    $request->print(
                   2238:                 '<div class="LC_columnSection">'
                   2239:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2240:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2241:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2242:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2243:  class="page">'.$lt{'past'}.'</a>',
                   2244:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2245:                     {legend => $lt{'keyw'}})
                   2246:                .'</fieldset></div>'
                   2247:             );
                   2248: 
1.88      www      2249: #
                   2250: # Load the other essays for similarity check
                   2251: #
1.324     albertel 2252:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2253: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2254: 	    $apath=&escape($apath);
1.88      www      2255: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2256:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2257:         }
                   2258:     }
1.44      ng       2259: 
1.441     www      2260: # This is where output for one specific student would start
1.592     bisitz   2261:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2262:     $request->print(
                   2263:         "\n\n"
                   2264:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2265:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2266:        ."\n"
                   2267:     );
1.441     www      2268: 
1.592     bisitz   2269:     # Show additional functions if allowed
                   2270:     if ($perm{'vgr'}) {
                   2271:         $request->print(
                   2272:             &Apache::loncommon::track_student_link(
1.708     bisitz   2273:                 'View recent activity',
1.592     bisitz   2274:                 $uname,$udom,'check')
                   2275:            .' '
                   2276:         );
                   2277:     }
                   2278:     if ($perm{'opa'}) {
                   2279:         $request->print(
                   2280:             &Apache::loncommon::pprmlink(
                   2281:                 &mt('Set/Change parameters'),
                   2282:                 $uname,$udom,$symb,'check'));
                   2283:     }
                   2284: 
                   2285:     # Show Problem
1.257     albertel 2286:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2287: 	my $mode;
1.257     albertel 2288: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2289: 	    $mode='both';
1.257     albertel 2290: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2291: 	    $mode='text';
1.257     albertel 2292: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2293: 	    $mode='answer';
                   2294: 	}
1.329     albertel 2295: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2296: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2297:     }
1.144     albertel 2298: 
1.257     albertel 2299:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2300:     my $res_error;
                   2301:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2302:     if ($res_error) {
                   2303:         $request->print(&navmap_errormsg());
                   2304:         return;
                   2305:     }
1.41      ng       2306: 
1.44      ng       2307:     # Display student info
1.41      ng       2308:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2309: 
1.745     raeburn  2310:     my $boxtitle = &mt('Submissions');
                   2311:     if ($is_tool) {
                   2312:         $boxtitle = &mt('Transactions')
                   2313:     }
1.590     bisitz   2314:     my $result='<div class="LC_Box">'
1.745     raeburn  2315:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2316:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2317:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2318: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2319:     unless ($is_tool) {
1.588     bisitz   2320:         $result.='<p class="LC_info">'
                   2321:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2322:                 ."</p>\n";
1.469     albertel 2323:     }
                   2324: 
1.118     ng       2325:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2326:     my $fullname;
                   2327:     my $col_fullnames = [];
1.624     www      2328: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2329:     unless ($is_tool) {
1.464     albertel 2330: 	(my $sub_result,$fullname,$col_fullnames)=
                   2331: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2332: 				 $counter);
                   2333: 	$result.=$sub_result;
1.41      ng       2334:     }
1.44      ng       2335:     $request->print($result."\n");
1.702     kruse    2336:     
1.44      ng       2337:     # print student answer/submission
1.588     bisitz   2338:     # Options are (1) Handgraded submission only
1.44      ng       2339:     #             (2) Last submission, includes submission that is not handgraded 
                   2340:     #                  (for multi-response type part)
                   2341:     #             (3) Last submission plus the parts info
                   2342:     #             (4) The whole record for this student
1.702     kruse    2343:     
1.745     raeburn  2344:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2345: 	
1.702     kruse    2346:     my $lastsubonly;
1.468     albertel 2347: 
1.702     kruse    2348:     if ($$timestamp eq '') {
                   2349:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2350:     } elsif ($is_tool) {
                   2351:         $lastsubonly =
                   2352:             '<div class="LC_grade_submissions_body">'
                   2353:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2354:     } else {
                   2355:         $lastsubonly =
                   2356:             '<div class="LC_grade_submissions_body">'
                   2357:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2358: 
                   2359: 	my %seenparts;
                   2360: 	my @part_response_id = &flatten_responseType($responseType);
                   2361: 	foreach my $part (@part_response_id) {
                   2362: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2363: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2364: 
1.702     kruse    2365: 	    my ($partid,$respid) = @{ $part };
                   2366: 	    my $display_part=&get_display_part($partid,$symb);
                   2367: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2368: 		if (exists($seenparts{$partid})) { next; }
                   2369: 		$seenparts{$partid}=1;
                   2370:                 $request->print(
                   2371:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2372:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2373:                                '<a href="javascript:viewSubmitter(\''.
                   2374:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2375:                                '\');" target="_self">'.
                   2376:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2377:                     '<br />');
                   2378: 		next;
                   2379: 		}
                   2380: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2381: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2382:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2383:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2384:                     ' <span class="LC_internal_info">'.
                   2385:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2386:                     '</span>&nbsp; &nbsp;'.
                   2387: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2388: 		next;
                   2389: 	    }
                   2390: 	    foreach my $submission (@$string) {
                   2391: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2392: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2393: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2394: 		# Similarity check
                   2395:                 my $similar='';
                   2396:                 my ($type,$trial,$rndseed);
                   2397:                 if ($hide eq 'rand') {
                   2398:                     $type = 'randomizetry';
                   2399:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2400:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2401:                 }
                   2402: 	        if ($env{'form.checkPlag'}) {
                   2403:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2404: 		        &most_similar($uname,$udom,$symb,$subval);
                   2405: 		    if ($osim) {
                   2406: 			$osim=int($osim*100.0);
                   2407: 			my %old_course_desc = 
                   2408: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2409: 							{'one_time' => 1});
                   2410: 
                   2411:                         if ($hide eq 'anon') {
                   2412:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2413:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2414:                         } else {
                   2415: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2416: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2417: 				    $osim,
                   2418: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2419: 				        $old_course_desc{'description'},
                   2420: 				        $old_course_desc{'num'},
                   2421: 				        $old_course_desc{'domain'}).
                   2422: 				    '</span></h3><blockquote><i>'.
                   2423: 				    &keywords_highlight($oessay).
                   2424: 				    '</i></blockquote><hr />';
1.702     kruse    2425:                         }
                   2426: 	            }
                   2427: 		}
                   2428: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2429:                                      undef,$type,$trial,$rndseed);
                   2430:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2431: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2432: 		    my $display_part=&get_display_part($partid,$symb);
                   2433:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2434:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2435:                         ' <span class="LC_internal_info">'.
                   2436:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2437:                         '</span>&nbsp; &nbsp;';
                   2438: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2439:                         
                   2440: 		    if (@$files) {
                   2441:                         if ($hide eq 'anon') {
                   2442:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2443:                         } else {
                   2444:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2445:                                         .'<br /><span class="LC_warning">';
                   2446:                             if(@$files == 1) {
                   2447:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2448:                             } else {
1.702     kruse    2449:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2450:                             }
                   2451:                             $lastsubonly .= '</span>';                         
                   2452:                             foreach my $file (@$files) {
                   2453:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2454:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2455:                             }
                   2456:                         }
1.702     kruse    2457: 			$lastsubonly.='<br />';
                   2458:                     }
                   2459:                     if ($hide eq 'anon') {
                   2460:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2461:                     } else {
1.724     raeburn  2462:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2463:                         if ($draft) {
                   2464:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2465:                         }
                   2466:                         $subval =
1.702     kruse    2467: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2468: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2469:                         if ($responsetype eq 'essay') {
                   2470:                             $subval =~ s{\n}{<br />}g;
                   2471:                         }
                   2472:                         $lastsubonly.=$subval."\n";
1.702     kruse    2473:                     }
                   2474: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2475: 		    $lastsubonly.='</div>';
1.41      ng       2476: 		}
1.702     kruse    2477:             }
1.151     albertel 2478: 	}
1.702     kruse    2479: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2480:     }
                   2481:     $request->print($lastsubonly);
                   2482:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2483:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2484: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2485:   
1.702     kruse    2486:     } 
                   2487:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2488:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2489:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2490: 								 $env{'request.course.id'},
1.44      ng       2491: 								 $last,'.submission',
1.726     raeburn  2492: 								 'Apache::grades::keywords_highlight',
                   2493:                                                                  $usec,$identifier));
1.41      ng       2494:     }
1.121     ng       2495:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2496: 	.$udom.'" />'."\n");
1.44      ng       2497:     # return if view submission with no grading option
1.618     www      2498:     if (!&canmodify($usec)) {
1.633     www      2499: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2500: 	return;
1.180     albertel 2501:     } else {
1.468     albertel 2502: 	$request->print('</div>'."\n");
1.41      ng       2503:     }
1.33      ng       2504: 
1.121     ng       2505:     # essay grading message center
1.624     www      2506: #    if ($env{'form.handgrade'} eq 'yes') {
                   2507:     if (1) {
1.468     albertel 2508: 	my $result='<div class="LC_grade_message_center">';
                   2509:     
                   2510: 	$result.='<div class="LC_grade_message_center_header">'.
                   2511: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2512: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2513: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2514: 	if (scalar(@$col_fullnames) > 0) {
                   2515: 	    my $lastone = pop(@$col_fullnames);
                   2516: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2517: 	}
                   2518: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2519: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2520: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2521: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2522: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2523: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2524: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2525: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2526: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2527: 	    '<br />&nbsp;('.
1.468     albertel 2528: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2529: 	$result.='</div></div>';
1.121     ng       2530: 	$request->print($result);
1.118     ng       2531:     }
1.41      ng       2532: 
                   2533:     my %seen = ();
                   2534:     my @partlist;
1.129     ng       2535:     my @gradePartRespid;
1.745     raeburn  2536:     my @part_response_id;
                   2537:     if ($is_tool) {
                   2538:         @part_response_id = ([0,'']);
                   2539:     } else {
                   2540:         @part_response_id = &flatten_responseType($responseType);
                   2541:     }
1.585     bisitz   2542:     $request->print(
1.588     bisitz   2543:         '<div class="LC_Box">'
                   2544:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2545:     );
1.592     bisitz   2546:     $request->print(&gradeBox_start());
1.375     albertel 2547:     foreach my $part_response_id (@part_response_id) {
                   2548:     	my ($partid,$respid) = @{ $part_response_id };
                   2549: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2550: 	next if ($seen{$partid} > 0);
1.41      ng       2551: 	$seen{$partid}++;
1.393     albertel 2552: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2553: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2554: 	push(@partlist,$partid);
                   2555: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2556: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2557:     }
1.585     bisitz   2558:     $request->print(&gradeBox_end()); # </div>
                   2559:     $request->print('</div>');
1.468     albertel 2560: 
                   2561:     $request->print('<div class="LC_grade_info_links">');
                   2562:     $request->print('</div>');
                   2563: 
1.45      ng       2564:     $result='<input type="hidden" name="partlist'.$counter.
                   2565: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2566:     $result.='<input type="hidden" name="gradePartRespid'.
                   2567: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2568:     my $ctr = 0;
                   2569:     while ($ctr < scalar(@partlist)) {
                   2570: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2571: 	    $partlist[$ctr].'" />'."\n";
                   2572: 	$ctr++;
                   2573:     }
1.468     albertel 2574:     $request->print($result.''."\n");
1.41      ng       2575: 
1.441     www      2576: # Done with printing info for one student
                   2577: 
1.468     albertel 2578:     $request->print('</div>');#LC_grade_show_user
1.441     www      2579: 
                   2580: 
1.41      ng       2581:     # print end of form
                   2582:     if ($counter == $total) {
1.592     bisitz   2583:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2584: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2585: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2586: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2587: 	my $ntstu ='<select name="NTSTU">'.
                   2588: 	    '<option>1</option><option>2</option>'.
                   2589: 	    '<option>3</option><option>5</option>'.
                   2590: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2591: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2592: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2593:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2594: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2595: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2596: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2597: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2598:         $endform.='<span class="LC_warning">'.
                   2599:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2600:                   '</span>'."\n" ;
1.349     albertel 2601:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2602:             "' name='increment' />";
1.485     albertel 2603: 	$endform.='</td></tr></table></form>';
1.41      ng       2604: 	$request->print($endform);
                   2605:     }
                   2606:     return '';
1.38      ng       2607: }
                   2608: 
1.464     albertel 2609: sub check_collaborators {
                   2610:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2611:     my ($result,@col_fullnames);
                   2612:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2613:     foreach my $part (keys(%$handgrade)) {
                   2614: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2615: 					'.maxcollaborators',
                   2616: 					$symb,$udom,$uname);
                   2617: 	next if ($ncol <= 0);
                   2618: 	$part =~ s/\_/\./g;
                   2619: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2620: 	my (@good_collaborators, @bad_collaborators);
                   2621: 	foreach my $possible_collaborator
1.630     www      2622: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2623: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2624: 	    next if ($possible_collaborator eq '');
1.631     www      2625: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2626: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2627: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2628: 	    # Doing this grep allows 'fuzzy' specification
                   2629: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2630: 			       keys(%$classlist));
                   2631: 	    if (! scalar(@matches)) {
                   2632: 		push(@bad_collaborators, $possible_collaborator);
                   2633: 	    } else {
                   2634: 		push(@good_collaborators, @matches);
                   2635: 	    }
                   2636: 	}
                   2637: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2638: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2639: 	    foreach my $name (@good_collaborators) {
                   2640: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2641: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2642: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2643: 	    }
1.630     www      2644: 	    $result.='</ol><br />'."\n";
1.466     albertel 2645: 	    my ($part)=split(/\./,$part);
1.464     albertel 2646: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2647: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2648: 		"\n";
                   2649: 	}
                   2650: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2651: 	    $result.='<div class="LC_warning">';
1.464     albertel 2652: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2653: 	    $result .= '</div>';
                   2654: 	}         
                   2655: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2656: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2657: 	    $result .= &mt('This student has submitted too many '.
                   2658: 		'collaborators.  Maximum is [_1].',$ncol);
                   2659: 	    $result .= '</div>';
                   2660: 	}
                   2661:     }
                   2662:     return ($result,$fullname,\@col_fullnames);
                   2663: }
                   2664: 
1.44      ng       2665: #--- Retrieve the last submission for all the parts
1.38      ng       2666: sub get_last_submission {
1.745     raeburn  2667:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2668:     my (@string,$timestamp,%lasthidden);
1.119     ng       2669:     if ($$returnhash{'version'}) {
1.46      ng       2670: 	my %lasthash=();
                   2671: 	my ($version);
1.119     ng       2672: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2673: 	    foreach my $key (sort(split(/\:/,
                   2674: 					$$returnhash{$version.':keys'}))) {
                   2675: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2676: 		$timestamp = 
1.545     raeburn  2677: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2678: 	    }
                   2679: 	}
1.640     raeburn  2680:         my (%typeparts,%randombytry);
1.596     raeburn  2681:         my $showsurv = 
                   2682:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2683:         foreach my $key (sort(keys(%lasthash))) {
                   2684:             if ($key =~ /\.type$/) {
                   2685:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2686:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2687:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2688:                     my ($ign,@parts) = split(/\./,$key);
                   2689:                     pop(@parts);
1.641     raeburn  2690:                     my $id = join('.',@parts);
1.640     raeburn  2691:                     if ($lasthash{$key} eq 'randomizetry') {
                   2692:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2693:                     } else {
                   2694:                         unless ($showsurv) {
                   2695:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2696:                         }
1.596     raeburn  2697:                     }
                   2698:                     delete($lasthash{$key});
                   2699:                 }
                   2700:             }
                   2701:         }
                   2702:         my @hidden = keys(%typeparts);
1.640     raeburn  2703:         my @randomize = keys(%randombytry);
1.397     albertel 2704: 	foreach my $key (keys(%lasthash)) {
                   2705: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2706:             my $hide;
                   2707:             if (@hidden) {
                   2708:                 foreach my $id (@hidden) {
                   2709:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2710:                         $hide = 'anon';
1.596     raeburn  2711:                         last;
                   2712:                     }
                   2713:                 }
                   2714:             }
1.640     raeburn  2715:             unless ($hide) {
                   2716:                 if (@randomize) {
1.732     raeburn  2717:                     foreach my $id (@randomize) {
1.640     raeburn  2718:                         if ($key =~ /^\Q$id\E/) {
                   2719:                             $hide = 'rand';
                   2720:                             last;
                   2721:                         }
                   2722:                     }
                   2723:                 }
                   2724:             }
1.397     albertel 2725: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2726: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2727:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2728:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2729:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2730: 	}
                   2731:     }
1.397     albertel 2732:     if (!@string) {
1.745     raeburn  2733:         my $msg;
                   2734:         if ($is_tool) {
1.747     raeburn  2735:             $msg = &mt('No grade passed back.');
1.745     raeburn  2736:         } else {
                   2737:             $msg = &mt('Nothing submitted - no attempts.');
                   2738:         }
1.397     albertel 2739: 	$string[0] =
1.745     raeburn  2740: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2741:     }
                   2742:     return (\@string,\$timestamp);
1.38      ng       2743: }
1.35      ng       2744: 
1.44      ng       2745: #--- High light keywords, with style choosen by user.
1.38      ng       2746: sub keywords_highlight {
1.44      ng       2747:     my $string    = shift;
1.257     albertel 2748:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2749:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2750:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2751:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2752:     foreach my $keyword (@keylist) {
                   2753: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2754:     }
                   2755:     return $string;
1.38      ng       2756: }
1.36      ng       2757: 
1.671     raeburn  2758: # For Tasks provide a mechanism to display previous version for one specific student
                   2759: 
                   2760: sub show_previous_task_version {
                   2761:     my ($request,$symb) = @_;
                   2762:     if ($symb eq '') {
1.717     bisitz   2763:         $request->print(
                   2764:             '<span class="LC_error">'.
                   2765:             &mt('Unable to handle ambiguous references.').
                   2766:             '</span>');
1.671     raeburn  2767:         return '';
                   2768:     }
                   2769:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2770:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2771:     if (!&canview($usec)) {
1.712     bisitz   2772:         $request->print(
                   2773:             '<span class="LC_warning">'.
1.713     bisitz   2774:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2775:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2776:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2777:             '</span>');
1.671     raeburn  2778:         return;
                   2779:     }
                   2780:     my $mode = 'both';
                   2781:     my $isTask = ($symb =~/\.task$/);
                   2782:     if ($isTask) {
                   2783:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2784:             if ($env{'form.fullname'} eq '') {
                   2785:                 $env{'form.fullname'} =
                   2786:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2787:             }
                   2788:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2789:             $request->print("\n\n".
                   2790:                             '<div class="LC_grade_show_user">'.
                   2791:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2792:                             '</h2>'."\n");
                   2793:             &Apache::lonxml::clear_problem_counter();
                   2794:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2795:                             {'previousversion' => $env{'form.previousversion'} }));
                   2796:             $request->print("\n</div>");
                   2797:         }
                   2798:     }
                   2799:     return;
                   2800: }
                   2801: 
                   2802: sub choose_task_version_form {
                   2803:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2804:     my $isTask = ($symb =~/\.task$/);
                   2805:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2806:     if ($isTask) {
                   2807:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2808:                                               $udom,$uname);
                   2809:         if (($record{'resource.0.version'} eq '') ||
                   2810:             ($record{'resource.0.version'} < 2)) {
                   2811:             return ($record{'resource.0.version'},
                   2812:                     $record{'resource.0.version'},$result,$js);
                   2813:         } else {
                   2814:             $current = $record{'resource.0.version'};
                   2815:         }
                   2816:         if ($env{'form.previousversion'}) {
                   2817:             $displayed = $env{'form.previousversion'};
                   2818:             $rowtitle = &mt('Choose another version:')
                   2819:         } else {
                   2820:             $displayed = $current;
                   2821:             $rowtitle = &mt('Show earlier version:');
                   2822:         }
                   2823:         $result = '<div class="LC_left_float">';
                   2824:         my $list;
                   2825:         my $numversions = 0;
                   2826:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2827:             if ($i == $current) {
                   2828:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2829:                     next;
                   2830:                 } else {
                   2831:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2832:                     $numversions ++;
                   2833:                 }
                   2834:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2835:                 unless ($i == $env{'form.previousversion'}) {
                   2836:                     $numversions ++;
                   2837:                 }
                   2838:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2839:             }
                   2840:         }
                   2841:         if ($numversions) {
                   2842:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2843:             $result .=
                   2844:                 '<form name="getprev" method="post" action=""'.
                   2845:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2846:                 &Apache::loncommon::start_data_table().
                   2847:                 &Apache::loncommon::start_data_table_row().
                   2848:                 '<th align="left">'.$rowtitle.'</th>'.
                   2849:                 '<td><select name="version">'.
                   2850:                 '<option>'.&mt('Select').'</option>'.
                   2851:                 $list.
                   2852:                 '</select></td>'.
                   2853:                 &Apache::loncommon::end_data_table_row();
                   2854:             unless ($nomenu) {
                   2855:                 $result .= &Apache::loncommon::start_data_table_row().
                   2856:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2857:                 '<td><span class="LC_nobreak">'.
                   2858:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2859:                 &mt('Yes').'</label>'.
                   2860:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2861:                 '</span></td>'.
                   2862:                 &Apache::loncommon::end_data_table_row();
                   2863:             }
                   2864:             $result .=
                   2865:                 &Apache::loncommon::start_data_table_row().
                   2866:                 '<th align="left">&nbsp;</th>'.
                   2867:                 '<td>'.
                   2868:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2869:                 '</td>'.
                   2870:                 &Apache::loncommon::end_data_table_row().
                   2871:                 &Apache::loncommon::end_data_table().
                   2872:                 '</form>';
                   2873:             $js = &previous_display_javascript($nomenu,$current);
                   2874:         } elsif ($displayed && $nomenu) {
                   2875:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2876:         } else {
                   2877:             $result .= &mt('No previous versions to show for this student');
                   2878:         }
                   2879:         $result .= '</div>';
                   2880:     }
                   2881:     return ($current,$displayed,$result,$js);
                   2882: }
                   2883: 
                   2884: sub previous_display_javascript {
                   2885:     my ($nomenu,$current) = @_;
                   2886:     my $js = <<"JSONE";
                   2887: <script type="text/javascript">
                   2888: // <![CDATA[
                   2889: function previousVersion(uname,udom,symb) {
                   2890:     var current = '$current';
                   2891:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2892:     var prevstr = new RegExp("^\\\\d+\$");
                   2893:     if (!prevstr.test(version)) {
                   2894:         return false;
                   2895:     }
                   2896:     var url = '';
                   2897:     if (version == current) {
                   2898:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2899:     } else {
                   2900:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2901:     }
                   2902: JSONE
                   2903:     if ($nomenu) {
                   2904:         $js .= <<"JSTWO";
                   2905:     document.location.href = url;
                   2906: JSTWO
                   2907:     } else {
                   2908:         $js .= <<"JSTHREE";
                   2909:     var newwin = 0;
                   2910:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2911:         if (document.getprev.prevwin[i].checked == true) {
                   2912:             newwin = document.getprev.prevwin[i].value;
                   2913:         }
                   2914:     }
                   2915:     if (newwin == 1) {
                   2916:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2917:         url = url+'&inhibitmenu=yes';
                   2918:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2919:             previousWin = window.open(url,'',options,1);
                   2920:         } else {
                   2921:             previousWin.location.href = url;
                   2922:         }
                   2923:         previousWin.focus();
                   2924:         return false;
                   2925:     } else {
                   2926:         document.location.href = url;
                   2927:         return false;
                   2928:     }
                   2929: JSTHREE
                   2930:     }
                   2931:     $js .= <<"ENDJS";
                   2932:     return false;
                   2933: }
                   2934: // ]]>
                   2935: </script>
                   2936: ENDJS
                   2937: 
                   2938: }
                   2939: 
1.44      ng       2940: #--- Called from submission routine
1.38      ng       2941: sub processHandGrade {
1.608     www      2942:     my ($request,$symb) = @_;
1.324     albertel 2943:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2944:     my $button = $env{'form.gradeOpt'};
                   2945:     my $ngrade = $env{'form.NCT'};
                   2946:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2947:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2948:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2949: 
1.44      ng       2950:     if ($button eq 'Save & Next') {
                   2951: 	my $ctr = 0;
                   2952: 	while ($ctr < $ngrade) {
1.257     albertel 2953: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2954: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2955:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2956: 	    if ($errorflag eq 'no_score') {
                   2957: 		$ctr++;
                   2958: 		next;
                   2959: 	    }
1.104     albertel 2960: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2961: 		$request->print(
                   2962:                     '<span class="LC_error">'
                   2963:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2964:                    .'</span>');
1.104     albertel 2965: 		$ctr++;
                   2966: 		next;
                   2967: 	    }
1.726     raeburn  2968:             if ($numhidden) {
                   2969:                 $request->print(
                   2970:                     '<span class="LC_info">'
                   2971:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2972:                    .'</span><br />');
                   2973:             }
1.257     albertel 2974: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2975: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2976: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2977:             my ($feedurl,$showsymb) =
                   2978: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2979: 	    my $messagetail;
1.62      albertel 2980: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2981: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2982: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2983: 		$subject.=' ['.$restitle.']';
1.44      ng       2984: 		my (@msgnum) = split(/,/,$includemsg);
                   2985: 		foreach (@msgnum) {
1.257     albertel 2986: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2987: 		}
1.80      ng       2988: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2989: 		if ($env{'form.withgrades'.$ctr}) {
                   2990: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2991: 		    $messagetail = " for <a href=\"".
1.605     www      2992: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2993: 		}
                   2994: 		$msgstatus = 
                   2995:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2996: 						     $message.$messagetail,
1.418     albertel 2997:                                                      undef,$feedurl,undef,
1.386     raeburn  2998:                                                      undef,undef,$showsymb,
                   2999:                                                      $restitle);
1.574     bisitz   3000: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3001: 				$msgstatus.'<br />');
1.44      ng       3002: 	    }
1.257     albertel 3003: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3004: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3005: 		foreach my $collabstr (@collabstrs) {
                   3006: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3007: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3008: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3009: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3010: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3011: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3012: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3013: 			    next;
1.418     albertel 3014: 			} elsif ($message ne '') {
                   3015: 			    my ($baseurl,$showsymb) = 
                   3016: 				&get_feedurl_and_symb($symb,$collaborator,
                   3017: 						      $udom);
                   3018: 			    if ($env{'form.withgrades'.$ctr}) {
                   3019: 				$messagetail = " for <a href=\"".
1.605     www      3020:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3021: 			    }
1.418     albertel 3022: 			    $msgstatus = 
                   3023: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3024: 			}
1.44      ng       3025: 		    }
                   3026: 		}
                   3027: 	    }
                   3028: 	    $ctr++;
                   3029: 	}
                   3030:     }
                   3031: 
1.624     www      3032: #    if ($env{'form.handgrade'} eq 'yes') {
                   3033:     if (1) {
1.119     ng       3034: 	# Keywords sorted in alphabatical order
1.257     albertel 3035: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       3036: 	my %keyhash = ();
1.257     albertel 3037: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3038: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3039: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3040: 	$env{'form.keywords'} = join(' ',@keywords);
                   3041: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3042: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3043: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3044: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3045: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       3046: 
                   3047: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3048: 	# New messages are saved in env for the next student.
1.119     ng       3049: 	# All messages are saved in nohist_handgrade.db
                   3050: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3051: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3052: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3053: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3054: 		$idx++;
                   3055: 	    }
                   3056: 	    $ctr++;
1.41      ng       3057: 	}
1.119     ng       3058: 	$ctr = 0;
                   3059: 	while ($ctr < $ngrade) {
1.257     albertel 3060: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3061: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3062: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3063: 		$idx++;
                   3064: 	    }
                   3065: 	    $ctr++;
1.41      ng       3066: 	}
1.257     albertel 3067: 	$env{'form.savemsgN'} = --$idx;
                   3068: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       3069: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3070: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3071:     }
1.44      ng       3072:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3073:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3074:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3075: 	my ($ctr,$total) = (0,0);
                   3076: 	while ($ctr < $ngrade) {
1.257     albertel 3077: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3078: 	    $ctr++;
                   3079: 	}
1.257     albertel 3080: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3081: 	$ctr = 0;
                   3082: 	while ($ctr < $total) {
1.257     albertel 3083: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3084: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3085: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3086: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3087: 	    $ctr++;
                   3088: 	}
                   3089: 	return '';
                   3090:     }
1.36      ng       3091: 
1.44      ng       3092:     # Get the next/previous one or group of students
1.257     albertel 3093:     my $firststu = $env{'form.unamedom0'};
                   3094:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3095:     my $ctr = 2;
1.41      ng       3096:     while ($laststu eq '') {
1.257     albertel 3097: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3098: 	$ctr++;
                   3099: 	$laststu = $firststu if ($ctr > $ngrade);
                   3100:     }
1.44      ng       3101: 
1.41      ng       3102:     my (@parsedlist,@nextlist);
                   3103:     my ($nextflg) = 0;
1.524     raeburn  3104:     foreach my $item (sort 
1.294     albertel 3105: 	     {
                   3106: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3107: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3108: 		 }
                   3109: 		 return $a cmp $b;
                   3110: 	     } (keys(%$fullname))) {
1.605     www      3111: # FIXME: this is fishy, looks like the button label
1.41      ng       3112: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3113: 	    push(@parsedlist,$item);
1.41      ng       3114: 	}
1.524     raeburn  3115: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3116: 	if ($button eq 'Previous') {
1.524     raeburn  3117: 	    last if ($item eq $firststu);
                   3118: 	    push(@parsedlist,$item);
1.41      ng       3119: 	}
                   3120:     }
                   3121:     $ctr = 0;
1.605     www      3122: # FIXME: this is fishy, looks like the button label
1.41      ng       3123:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3124:     my $res_error;
                   3125:     my ($partlist) = &response_type($symb,\$res_error);
                   3126:     if ($res_error) {
                   3127:         $request->print(&navmap_errormsg());
                   3128:         return;
                   3129:     }
1.41      ng       3130:     foreach my $student (@parsedlist) {
1.257     albertel 3131: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3132: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3133: 	
                   3134: 	if ($submitonly eq 'queued') {
                   3135: 	    my %queue_status = 
                   3136: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3137: 							$udom,$uname);
                   3138: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3139: 	}
                   3140: 
1.156     albertel 3141: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3142: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3143: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3144: 	    my $submitted = 0;
1.248     albertel 3145: 	    my $ungraded = 0;
                   3146: 	    my $incorrect = 0;
1.524     raeburn  3147: 	    foreach my $item (keys(%status)) {
                   3148: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3149: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3150: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3151: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3152: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3153: 		    $submitted = 0;
                   3154: 		}
1.41      ng       3155: 	    }
1.156     albertel 3156: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3157: 				     $submitonly eq 'incorrect' ||
                   3158: 				     $submitonly eq 'graded'));
1.248     albertel 3159: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3160: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3161: 	}
1.524     raeburn  3162: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3163: 	last if ($ctr == $ntstu);
1.41      ng       3164: 	$ctr++;
                   3165:     }
1.36      ng       3166: 
1.41      ng       3167:     $ctr = 0;
                   3168:     my $total = scalar(@nextlist)-1;
1.39      ng       3169: 
1.524     raeburn  3170:     foreach (sort(@nextlist)) {
1.41      ng       3171: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3172: 	$env{'form.student'}  = $uname;
                   3173: 	$env{'form.userdom'}  = $udom;
                   3174: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3175: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3176: 	$ctr++;
                   3177:     }
                   3178:     if ($total < 0) {
1.653     raeburn  3179: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3180: 	$request->print($the_end);
                   3181:     }
                   3182:     return '';
1.38      ng       3183: }
1.36      ng       3184: 
1.44      ng       3185: #---- Save the score and award for each student, if changed
1.38      ng       3186: sub saveHandGrade {
1.324     albertel 3187:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3188:     my @version_parts;
1.104     albertel 3189:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3190: 					   $env{'request.course.id'});
1.104     albertel 3191:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3192:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3193:     my @parts_graded;
1.77      ng       3194:     my %newrecord  = ();
1.726     raeburn  3195:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3196:     my %aggregate = ();
                   3197:     my $aggregateflag = 0;
1.726     raeburn  3198:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3199:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3200:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3201:         $totchg += $numchgs;
                   3202:     }
1.301     albertel 3203:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3204:     foreach my $new_part (@parts) {
1.337     banghart 3205: 	#collaborator ($submi may vary for different parts
1.259     banghart 3206: 	if ($submitter && $new_part ne $part) { next; }
                   3207: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3208: 	if ($dropMenu eq 'excused') {
1.259     banghart 3209: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3210: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3211: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3212: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3213: 		}
1.364     banghart 3214: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3215: 	    }
1.125     ng       3216: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3217: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3218: 	    foreach my $key (keys(%record)) {
1.259     banghart 3219: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3220: 	    }
1.259     banghart 3221: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3222: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3223:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3224: 
                   3225:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3226: 					       [$new_part]);
                   3227:             my $aggtries =$totaltries;
1.269     raeburn  3228:             if ($last_resets{$new_part}) {
1.270     albertel 3229:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3230: 					   $new_part);
1.269     raeburn  3231:             }
1.270     albertel 3232: 
                   3233:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3234:             if ($aggtries > 0) {
1.327     albertel 3235:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3236:                 $aggregateflag = 1;
                   3237:             }
1.125     ng       3238: 	} elsif ($dropMenu eq '') {
1.259     banghart 3239: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3240: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3241: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3242: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3243: 		next;
                   3244: 	    }
1.259     banghart 3245: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3246: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3247: 	    my $partial= $pts/$wgt;
1.259     banghart 3248: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3249: 		#do not update score for part if not changed.
1.346     banghart 3250:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3251: 		next;
1.251     banghart 3252: 	    } else {
1.524     raeburn  3253: 	        push(@parts_graded,$new_part);
1.153     albertel 3254: 	    }
1.259     banghart 3255: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3256: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3257: 	    }
1.259     banghart 3258: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3259: 	    if ($partial == 0) {
1.153     albertel 3260: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3261: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3262: 		}
1.41      ng       3263: 	    } else {
1.153     albertel 3264: 		if ($record{$reckey} ne 'correct_by_override') {
                   3265: 		    $newrecord{$reckey} = 'correct_by_override';
                   3266: 		}
                   3267: 	    }	    
                   3268: 	    if ($submitter && 
1.259     banghart 3269: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3270: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3271: 	    }
1.259     banghart 3272: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3273: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3274: 	}
1.259     banghart 3275: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3276: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3277: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3278: 	        $dropMenu eq 'reset status')
                   3279: 	   {
1.524     raeburn  3280: 	    push(@version_parts,$new_part);
1.259     banghart 3281: 	}
1.41      ng       3282:     }
1.301     albertel 3283:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3284:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3285: 
1.344     albertel 3286:     if (%newrecord) {
                   3287:         if (@version_parts) {
1.364     banghart 3288:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3289:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3290: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3291: 	    foreach my $new_part (@version_parts) {
                   3292: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3293: 				$new_part,\%newrecord);
                   3294: 	    }
1.259     banghart 3295:         }
1.44      ng       3296: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3297: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3298: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3299: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3300:     }
1.269     raeburn  3301:     if ($aggregateflag) {
                   3302:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3303: 			      $cdom,$cnum);
1.269     raeburn  3304:     }
1.726     raeburn  3305:     return ('',$pts,$wgt,$totchg);
                   3306: }
                   3307: 
                   3308: sub makehidden {
1.728     raeburn  3309:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3310:     return unless (ref($record) eq 'HASH');
                   3311:     my %modified;
                   3312:     my $numchanged = 0;
                   3313:     if (exists($record->{$version.':keys'})) {
                   3314:         my $partsregexp = $parts;
                   3315:         $partsregexp =~ s/,/|/g;
                   3316:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3317:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3318:                  my $item = $1;
                   3319:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3320:                      $modified{$key} = $record->{$version.':'.$key};
                   3321:                  }
                   3322:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3323:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3324:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3325:                 $modified{$key} = $record->{$version.':'.$key};
                   3326:             }
                   3327:         }
                   3328:         if (keys(%modified)) {
                   3329:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3330:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3331:                 $numchanged ++;
                   3332:             }
                   3333:         }
                   3334:     }
                   3335:     return $numchanged;
1.36      ng       3336: }
1.322     albertel 3337: 
1.380     albertel 3338: sub check_and_remove_from_queue {
                   3339:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3340:     my @ungraded_parts;
                   3341:     foreach my $part (@{$parts}) {
                   3342: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3343: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3344: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3345: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3346: 		) {
                   3347: 	    push(@ungraded_parts, $part);
                   3348: 	}
                   3349:     }
                   3350:     if ( !@ungraded_parts ) {
                   3351: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3352: 					       $cnum,$domain,$stuname);
                   3353:     }
                   3354: }
                   3355: 
1.337     banghart 3356: sub handback_files {
                   3357:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3358:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3359:     my $res_error;
                   3360:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3361:     if ($res_error) {
                   3362:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3363:         return;
                   3364:     }
1.654     raeburn  3365:     my @handedback;
                   3366:     my $file_msg;
1.375     albertel 3367:     my @part_response_id = &flatten_responseType($responseType);
                   3368:     foreach my $part_response_id (@part_response_id) {
                   3369:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3370: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3371:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3372:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3373:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3374:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3375:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3376:                     my ($directory,$answer_file) = 
1.654     raeburn  3377:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3378:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3379: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3380: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3381:                     my $getpropath = 1;
1.662     raeburn  3382:                     my ($dir_list,$listerror) = 
                   3383:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3384:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3385: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3386:                     # fix filename
1.355     banghart 3387:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3388:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3389:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3390:             	                                $save_file_name);
1.337     banghart 3391:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3392:                         $request->print('<br /><span class="LC_error">'.
                   3393:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3394:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3395:                                         '</span>');
1.356     banghart 3396:                     } else {
1.360     banghart 3397:                         # mark the file as read only
1.654     raeburn  3398:                         push(@handedback,$save_file_name);
1.367     albertel 3399: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3400: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3401: 			}
                   3402:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3403: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3404:                     }
1.686     bisitz   3405:                     $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 3406:                 }
                   3407:             }
                   3408:         }
1.654     raeburn  3409:     }
                   3410:     if (@handedback > 0) {
                   3411:         $request->print('<br />');
                   3412:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3413:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3414:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3415:         my ($subject,$message);
                   3416:         if (scalar(@handedback) == 1) {
                   3417:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3418:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3419:         } else {
                   3420:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3421:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3422:         }
                   3423:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3424:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3425:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3426:         my ($feedurl,$showsymb) =
                   3427:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3428:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3429:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3430:         my $msgstatus =
                   3431:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3432:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3433:                  $restitle);
                   3434:         if ($msgstatus) {
                   3435:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3436:         }
                   3437:     }
1.338     banghart 3438:     return;
1.337     banghart 3439: }
                   3440: 
1.418     albertel 3441: sub get_feedurl_and_symb {
                   3442:     my ($symb,$uname,$udom) = @_;
                   3443:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3444:     $url = &Apache::lonnet::clutter($url);
                   3445:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3446: 					$symb,$udom,$uname);
                   3447:     if ($encrypturl =~ /^yes$/i) {
                   3448: 	&Apache::lonenc::encrypted(\$url,1);
                   3449: 	&Apache::lonenc::encrypted(\$symb,1);
                   3450:     }
                   3451:     return ($url,$symb);
                   3452: }
                   3453: 
1.313     banghart 3454: sub get_submitted_files {
                   3455:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3456:     my @files;
                   3457:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3458:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3459:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3460:     	    push(@files,$file_url.$file);
                   3461:         }
                   3462:     }
                   3463:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3464:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3465:     }
                   3466:     return (\@files);
                   3467: }
1.322     albertel 3468: 
1.269     raeburn  3469: # ----------- Provides number of tries since last reset.
                   3470: sub get_num_tries {
                   3471:     my ($record,$last_reset,$part) = @_;
                   3472:     my $timestamp = '';
                   3473:     my $num_tries = 0;
                   3474:     if ($$record{'version'}) {
                   3475:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3476:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3477:                 $timestamp = $$record{$version.':timestamp'};
                   3478:                 if ($timestamp > $last_reset) {
                   3479:                     $num_tries ++;
                   3480:                 } else {
                   3481:                     last;
                   3482:                 }
                   3483:             }
                   3484:         }
                   3485:     }
                   3486:     return $num_tries;
                   3487: }
                   3488: 
                   3489: # ----------- Determine decrements required in aggregate totals 
                   3490: sub decrement_aggs {
                   3491:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3492:     my %decrement = (
                   3493:                         attempts => 0,
                   3494:                         users => 0,
                   3495:                         correct => 0
                   3496:                     );
                   3497:     $decrement{'attempts'} = $aggtries;
                   3498:     if ($solvedstatus =~ /^correct/) {
                   3499:         $decrement{'correct'} = 1;
                   3500:     }
                   3501:     if ($aggtries == $totaltries) {
                   3502:         $decrement{'users'} = 1;
                   3503:     }
1.524     raeburn  3504:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3505:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3506:     }
                   3507:     return;
                   3508: }
                   3509: 
                   3510: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3511: sub get_last_resets {
1.270     albertel 3512:     my ($symb,$courseid,$partids) =@_;
                   3513:     my %last_resets;
1.269     raeburn  3514:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3515:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3516:     my @keys;
                   3517:     foreach my $part (@{$partids}) {
                   3518: 	push(@keys,"$symb\0$part\0resettime");
                   3519:     }
                   3520:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3521: 				     $cdom,$cname);
                   3522:     foreach my $part (@{$partids}) {
                   3523: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3524:     }
1.270     albertel 3525:     return %last_resets;
1.269     raeburn  3526: }
                   3527: 
1.251     banghart 3528: # ----------- Handles creating versions for portfolio files as answers
                   3529: sub version_portfiles {
1.343     banghart 3530:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3531:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3532:     my @returned_keys;
1.255     banghart 3533:     my $parts = join('|', @$parts_graded);
1.277     albertel 3534:     foreach my $key (keys(%$record)) {
1.259     banghart 3535:         my $new_portfiles;
1.263     banghart 3536:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3537:             my @versioned_portfiles;
1.367     albertel 3538:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3539:             if (@portfiles) {
                   3540:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3541:                                                       \@versioned_portfiles);
1.252     banghart 3542:             }
1.343     banghart 3543:             $$record{$key} = join(',',@versioned_portfiles);
                   3544:             push(@returned_keys,$key);
1.251     banghart 3545:         }
                   3546:     } 
1.343     banghart 3547:     return (@returned_keys);   
1.305     banghart 3548: }
                   3549: 
1.44      ng       3550: #--------------------------------------------------------------------------------------
                   3551: #
                   3552: #-------------------------- Next few routines handles grading by section or whole class
                   3553: #
                   3554: #--- Javascript to handle grading by section or whole class
1.42      ng       3555: sub viewgrades_js {
                   3556:     my ($request) = shift;
                   3557: 
1.539     riegler  3558:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3559:     &js_escape(\$alertmsg);
1.597     wenzelju 3560:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3561:    function writePoint(partid,weight,point) {
1.125     ng       3562: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3563: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3564: 	if (point == "textval") {
1.125     ng       3565: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3566: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3567: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3568: 		var resetbox = false;
                   3569: 		for (var i=0; i<radioButton.length; i++) {
                   3570: 		    if (radioButton[i].checked) {
                   3571: 			textbox.value = i;
                   3572: 			resetbox = true;
                   3573: 		    }
                   3574: 		}
                   3575: 		if (!resetbox) {
                   3576: 		    textbox.value = "";
                   3577: 		}
                   3578: 		return;
                   3579: 	    }
1.109     matthew  3580: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3581: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3582: 				   ") greater than the weight for the part. Accept?");
                   3583: 		if (resp == false) {
                   3584: 		    textbox.value = "";
                   3585: 		    return;
                   3586: 		}
                   3587: 	    }
1.42      ng       3588: 	    for (var i=0; i<radioButton.length; i++) {
                   3589: 		radioButton[i].checked=false;
1.109     matthew  3590: 		if (parseFloat(point) == i) {
1.42      ng       3591: 		    radioButton[i].checked=true;
                   3592: 		}
                   3593: 	    }
1.41      ng       3594: 
1.42      ng       3595: 	} else {
1.125     ng       3596: 	    textbox.value = parseFloat(point);
1.42      ng       3597: 	}
1.41      ng       3598: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3599: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3600: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3601: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3602: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3603: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3604: 	    if (saveval != "correct") {
                   3605: 		scorename.value = point;
1.43      ng       3606: 		if (selname[0].selected != true) {
                   3607: 		    selname[0].selected = true;
                   3608: 		}
1.42      ng       3609: 	    }
                   3610: 	}
1.125     ng       3611: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3612:     }
                   3613: 
                   3614:     function writeRadText(partid,weight) {
1.125     ng       3615: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3616: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3617:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3618: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3619: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3620: 	    for (var i=0; i<radioButton.length; i++) {
                   3621: 		radioButton[i].checked=false;
                   3622: 
                   3623: 	    }
                   3624: 	    textbox.value = "";
                   3625: 
                   3626: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3627: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3628: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3629: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3630: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3631: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3632: 		if ((saveval != "correct") || override) {
1.42      ng       3633: 		    scorename.value = "";
1.125     ng       3634: 		    if (selval[1].selected) {
                   3635: 			selname[1].selected = true;
                   3636: 		    } else {
                   3637: 			selname[2].selected = true;
                   3638: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3639: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3640: 		    }
1.42      ng       3641: 		}
                   3642: 	    }
1.43      ng       3643: 	} else {
                   3644: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3645: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3646: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3647: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3648: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3649: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3650: 		if ((saveval != "correct") || override) {
1.125     ng       3651: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3652: 		    selname[0].selected = true;
                   3653: 		}
                   3654: 	    }
                   3655: 	}	    
1.42      ng       3656:     }
                   3657: 
                   3658:     function changeSelect(partid,user) {
1.125     ng       3659: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3660: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3661: 	var point  = textbox.value;
1.125     ng       3662: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3663: 
1.109     matthew  3664: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3665: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3666: 	    textbox.value = "";
                   3667: 	    return;
                   3668: 	}
1.109     matthew  3669: 	if (parseFloat(point) > parseFloat(weight)) {
                   3670: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3671: 			       ") greater than the weight of the part. Accept?");
                   3672: 	    if (resp == false) {
                   3673: 		textbox.value = "";
                   3674: 		return;
                   3675: 	    }
                   3676: 	}
1.42      ng       3677: 	selval[0].selected = true;
                   3678:     }
                   3679: 
                   3680:     function changeOneScore(partid,user) {
1.125     ng       3681: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3682: 	if (selval[1].selected || selval[2].selected) {
                   3683: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3684: 	    if (selval[2].selected) {
                   3685: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3686: 	    }
1.269     raeburn  3687:         }
1.42      ng       3688:     }
                   3689: 
                   3690:     function resetEntry(numpart) {
                   3691: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3692: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3693: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3694: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3695: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3696: 	    for (var i=0; i<radioButton.length; i++) {
                   3697: 		radioButton[i].checked=false;
                   3698: 
                   3699: 	    }
                   3700: 	    textbox.value = "";
                   3701: 	    selval[0].selected = true;
                   3702: 
                   3703: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3704: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3705: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3706: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3707: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3708: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3709: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3710: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3711: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3712: 		if (saveselval == "excused") {
1.43      ng       3713: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3714: 		} else {
1.43      ng       3715: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3716: 		}
                   3717: 	    }
1.41      ng       3718: 	}
1.42      ng       3719:     }
                   3720: 
1.41      ng       3721: VIEWJAVASCRIPT
1.42      ng       3722: }
                   3723: 
1.44      ng       3724: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3725: sub viewgrades {
1.608     www      3726:     my ($request,$symb) = @_;
1.745     raeburn  3727:     my ($is_tool,$toolsymb);
                   3728:     if ($symb =~ /ext\.tool$/) {
                   3729:         $is_tool = 1;
                   3730:         $toolsymb = $symb;
                   3731:     }
1.42      ng       3732:     &viewgrades_js($request);
1.41      ng       3733: 
1.168     albertel 3734:     #need to make sure we have the correct data for later EXT calls, 
                   3735:     #thus invalidate the cache
                   3736:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3737:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3738:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3739:     &Apache::lonnet::clear_EXT_cache_status();
                   3740: 
1.398     albertel 3741:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3742: 
                   3743:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3744:     $result.=&jscriptNform($symb);
1.41      ng       3745: 
1.44      ng       3746:     #beginning of class grading form
1.442     banghart 3747:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3748:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3749: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3750: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3751: 	&build_section_inputs().
1.442     banghart 3752: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3753: 
1.738     raeburn  3754:     #retrieve selected groups
                   3755:     my (@groups,$group_display);
                   3756:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3757:     if (grep(/^all$/,@groups)) {
                   3758:         @groups = ('all');
                   3759:     } elsif (grep(/^none$/,@groups)) {
                   3760:         @groups = ('none');
                   3761:     } elsif (@groups > 0) {
                   3762:         $group_display = join(', ',@groups);
                   3763:     }
                   3764: 
                   3765:     my ($common_header,$specific_header,@sections,$section_display);
                   3766:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3767:     if (grep(/^all$/,@sections)) {
                   3768:         @sections = ('all');
                   3769:         if ($group_display) {
                   3770:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3771:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3772:         } elsif (grep(/^none$/,@groups)) {
                   3773:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3774:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3775:         } else {
                   3776: 	    $common_header = &mt('Assign Common Grade to Class');
                   3777:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3778:         }
                   3779:     } elsif (grep(/^none$/,@sections)) {
                   3780:         @sections = ('none');
                   3781:         if ($group_display) {
                   3782:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3783:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3784:         } elsif (grep(/^none$/,@groups)) {
                   3785:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3786:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3787:         } else {
                   3788:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3789: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3790:         }
                   3791:     } else {
                   3792:         $section_display = join (", ",@sections);
                   3793:         if ($group_display) {
                   3794:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3795:                                  $section_display,$group_display);
                   3796:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3797:                                    $section_display,$group_display);
                   3798:         } elsif (grep(/^none$/,@groups)) {
                   3799:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3800:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3801:         } else {
                   3802:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3803: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3804:         }
                   3805:     }
                   3806:     my %submit_types = &substatus_options();
                   3807:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3808: 
                   3809:     if ($env{'form.submitonly'} eq 'all') {
                   3810:         $result.= '<h3>'.$common_header.'</h3>';
                   3811:     } else {
1.745     raeburn  3812:         my $text;
                   3813:         if ($is_tool) {
                   3814:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3815:         } else {
                   3816:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3817:         }
                   3818:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3819:     }
1.738     raeburn  3820:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3821:     #radio buttons/text box for assigning points for a section or class.
                   3822:     #handles different parts of a problem
1.582     raeburn  3823:     my $res_error;
                   3824:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3825:     if ($res_error) {
                   3826:         return &navmap_errormsg();
                   3827:     }
1.42      ng       3828:     my %weight = ();
                   3829:     my $ctsparts = 0;
1.45      ng       3830:     my %seen = ();
1.745     raeburn  3831:     my @part_response_id;
                   3832:     if ($is_tool) {
                   3833:         @part_response_id = ([0,'']);
                   3834:     } else {
                   3835:         @part_response_id = &flatten_responseType($responseType);
                   3836:     }
1.375     albertel 3837:     foreach my $part_response_id (@part_response_id) {
                   3838:     	my ($partid,$respid) = @{ $part_response_id };
                   3839: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3840: 	next if $seen{$partid};
                   3841: 	$seen{$partid}++;
1.744     raeburn  3842: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3843: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3844: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3845: 
1.324     albertel 3846: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3847: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3848: 	my $ctr = 0;
1.42      ng       3849: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3850: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3851: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3852: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3853: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3854: 	    $ctr++;
                   3855: 	}
1.485     albertel 3856: 	$radio.='</tr></table>';
                   3857: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3858: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3859: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3860: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3861:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3862:             '<select name="SELVAL_'.$partid.'" '.
                   3863:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3864:                 $weight{$partid}.')"> '.
1.401     albertel 3865: 	    '<option selected="selected"> </option>'.
1.485     albertel 3866: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3867: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3868: 	    '</select></td>'.
                   3869:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3870: 	$line.='<input type="hidden" name="partid_'.
                   3871: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3872: 	$line.='<input type="hidden" name="weight_'.
                   3873: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3874: 
                   3875: 	$result.=
                   3876: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3877: 	    '<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 3878: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3879: 	$ctsparts++;
1.41      ng       3880:     }
1.474     albertel 3881:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3882: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3883:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3884: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3885: 
1.44      ng       3886:     #table listing all the students in a section/class
                   3887:     #header of table
1.738     raeburn  3888:     if ($env{'form.submitonly'} eq 'all') {
                   3889:         $result.= '<h3>'.$specific_header.'</h3>';
                   3890:     } else {
1.745     raeburn  3891:         my $text;
                   3892:         if ($is_tool) {
                   3893:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3894:         } else {
                   3895:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3896:         }
                   3897:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3898:     }
                   3899:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3900: 	      &Apache::loncommon::start_data_table_header_row().
                   3901: 	      '<th>'.&mt('No.').'</th>'.
                   3902: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3903:     my $partserror;
                   3904:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3905:     if ($partserror) {
                   3906:         return &navmap_errormsg();
                   3907:     }
1.324     albertel 3908:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3909:     my @partids = ();
1.41      ng       3910:     foreach my $part (@parts) {
1.745     raeburn  3911: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3912:         my $narrowtext = &mt('Tries');
                   3913: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3914: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3915: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3916:         push(@partids,$partid);
1.628     www      3917: #
                   3918: # FIXME: Looks like $display looks at English text
                   3919: #
1.324     albertel 3920: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3921: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3922: 	    $result.='<th>'.
1.697     bisitz   3923: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3924: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3925: 	    next;
1.485     albertel 3926: 	    
1.207     albertel 3927: 	} else {
1.485     albertel 3928: 	    if ($display =~ /Problem Status/) {
                   3929: 		my $grade_status_mt = &mt('Grade Status');
                   3930: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3931: 	    }
                   3932: 	    my $part_mt = &mt('Part:');
                   3933: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3934: 	}
1.485     albertel 3935: 
1.474     albertel 3936: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3937:     }
1.474     albertel 3938:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3939: 
1.270     albertel 3940:     my %last_resets = 
                   3941: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3942: 
1.41      ng       3943:     #get info for each student
1.44      ng       3944:     #list all the students - with points and grade status
1.738     raeburn  3945:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3946:     my $ctr = 0;
1.294     albertel 3947:     foreach (sort 
                   3948: 	     {
                   3949: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3950: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3951: 		 }
                   3952: 		 return $a cmp $b;
                   3953: 	     } (keys(%$fullname))) {
1.324     albertel 3954: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  3955: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       3956:     }
1.474     albertel 3957:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3958:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3959:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3960: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  3961:     if ($ctr == 0) {
1.442     banghart 3962:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  3963:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3964:                 '<span class="LC_warning">';
                   3965:         if ($env{'form.submitonly'} eq 'all') {
                   3966:             if (grep(/^all$/,@sections)) {
                   3967:                 if (grep(/^all$/,@groups)) {
                   3968:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3969:                                    $stu_status);
                   3970:                 } elsif (grep(/^none$/,@groups)) {
                   3971:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3972:                                    $stu_status); 
                   3973:                 } else {
                   3974:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3975:                                    $group_display,$stu_status);
                   3976:                 }
                   3977:             } elsif (grep(/^none$/,@sections)) {
                   3978:                 if (grep(/^all$/,@groups)) {
                   3979:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3980:                                    $stu_status);
                   3981:                 } elsif (grep(/^none$/,@groups)) {
                   3982:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3983:                                    $stu_status);
                   3984:                 } else {
                   3985:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3986:                                    $group_display,$stu_status);
                   3987:                 }
                   3988:             } else {
                   3989:                 if (grep(/^all$/,@groups)) {
                   3990:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3991:                                    $section_display,$stu_status);
                   3992:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  3993:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  3994:                                    $section_display,$stu_status);
                   3995:                 } else {
                   3996:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3997:                                    $section_display,$group_display,$stu_status);
                   3998:                 }
                   3999:             }
                   4000:         } else {
                   4001:             if (grep(/^all$/,@sections)) {
                   4002:                 if (grep(/^all$/,@groups)) {
                   4003:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4004:                                    $stu_status,$submission_status);
                   4005:                 } elsif (grep(/^none$/,@groups)) {
                   4006:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4007:                                    $stu_status,$submission_status);
                   4008:                 } else {
                   4009:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4010:                                    $group_display,$stu_status,$submission_status);
                   4011:                 }
                   4012:             } elsif (grep(/^none$/,@sections)) {
                   4013:                 if (grep(/^all$/,@groups)) {
                   4014:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4015:                                    $stu_status,$submission_status);
                   4016:                 } elsif (grep(/^none$/,@groups)) {
                   4017:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4018:                                    $stu_status,$submission_status);
                   4019:                 } else {
                   4020:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4021:                                    $group_display,$stu_status,$submission_status);
                   4022:                 }
                   4023:             } else {
                   4024:                 if (grep(/^all$/,@groups)) {
                   4025: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4026: 	                           $section_display,$stu_status,$submission_status);
                   4027:                 } elsif (grep(/^none$/,@groups)) {
                   4028:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4029:                                    $section_display,$stu_status,$submission_status);
                   4030:                 } else {
                   4031:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
                   4032:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4033:                 }
                   4034:             }
                   4035:         }
                   4036: 	$result .= '</span><br />';
1.96      albertel 4037:     }
1.41      ng       4038:     return $result;
                   4039: }
                   4040: 
1.738     raeburn  4041: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4042: sub viewstudentgrade {
1.745     raeburn  4043:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4044:     my ($uname,$udom) = split(/:/,$student);
                   4045:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4046:     my $submitonly = $env{'form.submitonly'};
                   4047:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4048:         my %partstatus = ();
                   4049:         if (ref($parts) eq 'ARRAY') {
                   4050:             foreach my $apart (@{$parts}) {
                   4051:                 my ($part,$type) = &split_part_type($apart);
                   4052:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4053:                 $status = 'nothing' if ($status eq '');
                   4054:                 $partstatus{$part}      = $status;
                   4055:                 my $subkey = "resource.$part.submitted_by";
                   4056:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4057:             }
                   4058:             my $submitted = 0;
                   4059:             my $graded = 0;
                   4060:             my $incorrect = 0;
                   4061:             foreach my $key (keys(%partstatus)) {
                   4062:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4063:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4064:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4065: 
                   4066:                 my $partid = (split(/\./,$key))[1];
                   4067:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4068:                     $submitted = 0;
                   4069:                 }
                   4070:             }
                   4071:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4072:                                        $submitonly eq 'incorrect' ||
                   4073:                                        $submitonly eq 'graded'));
                   4074:             return if (!$graded && ($submitonly eq 'graded'));
                   4075:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4076:         }
                   4077:     }
                   4078:     if ($submitonly eq 'queued') {
                   4079:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4080:         my %queue_status =
                   4081:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4082:                                                     $udom,$uname);
                   4083:         return if (!defined($queue_status{'gradingqueue'}));
                   4084:     }
                   4085:     $$ctr++;
                   4086:     my %aggregates = ();
1.474     albertel 4087:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4088: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4089: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4090: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4091: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4092: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4093:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4094:     foreach my $apart (@$parts) {
                   4095: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4096: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4097:         $result.='<td align="center">';
1.269     raeburn  4098:         my ($aggtries,$totaltries);
                   4099:         unless (exists($aggregates{$part})) {
1.270     albertel 4100: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4101: 	    $aggtries = $totaltries;
1.269     raeburn  4102:             if ($$last_resets{$part}) {  
1.270     albertel 4103:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4104: 					   $part);
                   4105:             }
1.269     raeburn  4106:             $result.='<input type="hidden" name="'.
                   4107:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4108:             $result.='<input type="hidden" name="'.
                   4109:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4110:             $aggregates{$part} = 1;
                   4111:         }
1.41      ng       4112: 	if ($type eq 'awarded') {
1.320     albertel 4113: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4114: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4115: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4116: 	    $result.='<input type="text" name="'.
1.89      albertel 4117: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4118:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4119: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4120: 	} elsif ($type eq 'solved') {
                   4121: 	    my ($status,$foo)=split(/_/,$score,2);
                   4122: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4123: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4124: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4125: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4126: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4127:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4128: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4129: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4130: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4131: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4132: 	} else {
                   4133: 	    $result.='<input type="hidden" name="'.
                   4134: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4135: 		    "\n";
1.233     albertel 4136: 	    $result.='<input type="text" name="'.
1.122     ng       4137: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4138: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4139: 	}
                   4140:     }
1.474     albertel 4141:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4142:     return $result;
1.38      ng       4143: }
                   4144: 
1.44      ng       4145: #--- change scores for all the students in a section/class
                   4146: #    record does not get update if unchanged
1.38      ng       4147: sub editgrades {
1.608     www      4148:     my ($request,$symb) = @_;
1.745     raeburn  4149:     my $toolsymb;
                   4150:     if ($symb =~ /ext\.tool$/) {
                   4151:         $toolsymb = $symb;
                   4152:     }
1.41      ng       4153: 
1.433     banghart 4154:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4155:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 4156:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       4157: 
1.477     albertel 4158:     my $result= &Apache::loncommon::start_data_table().
                   4159: 	&Apache::loncommon::start_data_table_header_row().
                   4160: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4161: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4162:     my %scoreptr = (
                   4163: 		    'correct'  =>'correct_by_override',
                   4164: 		    'incorrect'=>'incorrect_by_override',
                   4165: 		    'excused'  =>'excused',
                   4166: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4167:                     'credited' =>'credit_attempted',
1.43      ng       4168: 		    'nothing'  => '',
                   4169: 		    );
1.257     albertel 4170:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4171: 
1.44      ng       4172:     my (@partid);
                   4173:     my %weight = ();
1.54      albertel 4174:     my %columns = ();
1.44      ng       4175:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4176: 
1.582     raeburn  4177:     my $partserror;
                   4178:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4179:     if ($partserror) {
                   4180:         return &navmap_errormsg();
                   4181:     }
1.54      albertel 4182:     my $header;
1.257     albertel 4183:     while ($ctr < $env{'form.totalparts'}) {
                   4184: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4185: 	push(@partid,$partid);
1.257     albertel 4186: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4187: 	$ctr++;
1.54      albertel 4188:     }
1.324     albertel 4189:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4190:     my $totcolspan = 0;
1.54      albertel 4191:     foreach my $partid (@partid) {
1.478     albertel 4192: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4193: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4194: 	$columns{$partid}=2;
                   4195: 	foreach my $stores (@parts) {
                   4196: 	    my ($part,$type) = &split_part_type($stores);
                   4197: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4198: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4199: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4200: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4201:             my $narrowtext = &mt('Tries');
                   4202: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4203: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4204: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4205: 	    $columns{$partid}+=2;
                   4206: 	}
1.748     raeburn  4207:         $totcolspan += $columns{$partid};
1.54      albertel 4208:     }
                   4209:     foreach my $partid (@partid) {
1.324     albertel 4210: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4211: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4212: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4213: 	    '</th>';
1.54      albertel 4214: 
1.44      ng       4215:     }
1.477     albertel 4216:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4217: 	&Apache::loncommon::start_data_table_header_row().
                   4218: 	$header.
                   4219: 	&Apache::loncommon::end_data_table_header_row();
                   4220:     my @noupdate;
1.126     ng       4221:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4222:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4223: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4224: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4225: 	my %newrecord;
                   4226: 	my $updateflag = 0;
1.108     albertel 4227: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4228: 	my $canmodify = &canmodify($usec);
                   4229: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4230: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4231: 	if (!$canmodify) {
1.477     albertel 4232: 	    push(@noupdate,
1.748     raeburn  4233: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4234: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4235: 	    next;
                   4236: 	}
1.269     raeburn  4237:         my %aggregate = ();
                   4238:         my $aggregateflag = 0;
1.281     albertel 4239: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4240: 	foreach (@partid) {
1.257     albertel 4241: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4242: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4243: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4244: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4245: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4246: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4247: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4248: 	    my $score;
                   4249: 	    if ($partial eq '') {
1.257     albertel 4250: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4251: 	    } elsif ($partial > 0) {
                   4252: 		$score = 'correct_by_override';
                   4253: 	    } elsif ($partial == 0) {
                   4254: 		$score = 'incorrect_by_override';
                   4255: 	    }
1.257     albertel 4256: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4257: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4258: 
1.292     albertel 4259: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4260: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4261: 	    if ($dropMenu eq 'reset status' &&
                   4262: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4263: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4264: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4265: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4266: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4267: 		$updateflag = 1;
1.269     raeburn  4268:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4269:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4270:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4271:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4272:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4273:                     $aggregateflag = 1;
                   4274:                 }
1.139     albertel 4275: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4276: 		$updateflag = 1;
                   4277: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4278: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4279: 		$rec_update++;
1.125     ng       4280: 	    }
                   4281: 
1.93      albertel 4282: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4283: 		'<td align="center">'.$awarded.
                   4284: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4285: 
1.54      albertel 4286: 
                   4287: 	    my $partid=$_;
                   4288: 	    foreach my $stores (@parts) {
                   4289: 		my ($part,$type) = &split_part_type($stores);
                   4290: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4291: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4292: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4293: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4294: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4295: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4296: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4297: 		    $updateflag=1;
                   4298: 		}
1.93      albertel 4299: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4300: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4301: 	    }
1.44      ng       4302: 	}
1.477     albertel 4303: 	$line.="\n";
1.301     albertel 4304: 
                   4305: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4306: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4307: 
1.44      ng       4308: 	if ($updateflag) {
                   4309: 	    $count++;
1.257     albertel 4310: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4311: 				    $udom,$uname);
1.301     albertel 4312: 
                   4313: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4314: 					      $cnum,$udom,$uname)) {
                   4315: 		# need to figure out if should be in queue.
                   4316: 		my %record =  
                   4317: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4318: 					     $udom,$uname);
                   4319: 		my $all_graded = 1;
                   4320: 		my $none_graded = 1;
                   4321: 		foreach my $part (@parts) {
                   4322: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4323: 			$all_graded = 0;
                   4324: 		    } else {
                   4325: 			$none_graded = 0;
                   4326: 		    }
                   4327: 		}
                   4328: 
                   4329: 		if ($all_graded || $none_graded) {
                   4330: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4331: 							   $symb,$cdom,$cnum,
                   4332: 							   $udom,$uname);
                   4333: 		}
                   4334: 	    }
                   4335: 
1.477     albertel 4336: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4337: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4338: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4339: 	    $updateCtr++;
1.93      albertel 4340: 	} else {
1.477     albertel 4341: 	    push(@noupdate,
                   4342: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4343: 	    $noupdateCtr++;
1.44      ng       4344: 	}
1.269     raeburn  4345:         if ($aggregateflag) {
                   4346:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4347: 				  $cdom,$cnum);
1.269     raeburn  4348:         }
1.93      albertel 4349:     }
1.477     albertel 4350:     if (@noupdate) {
1.748     raeburn  4351:         my $numcols=$totcolspan+2;
1.477     albertel 4352: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4353: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4354: 	    &mt('No Changes Occurred For the Students Below').
                   4355: 	    '</td>'.
1.477     albertel 4356: 	    &Apache::loncommon::end_data_table_row();
                   4357: 	foreach my $line (@noupdate) {
                   4358: 	    $result.=
                   4359: 		&Apache::loncommon::start_data_table_row().
                   4360: 		$line.
                   4361: 		&Apache::loncommon::end_data_table_row();
                   4362: 	}
1.44      ng       4363:     }
1.614     www      4364:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4365:     my $msg = '<p><b>'.
                   4366: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4367: 	    $rec_update,$count).'</b><br />'.
                   4368: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4369: 	'</b></p>';
1.44      ng       4370:     return $title.$msg.$result;
1.5       albertel 4371: }
1.54      albertel 4372: 
                   4373: sub split_part_type {
                   4374:     my ($partstr) = @_;
                   4375:     my ($temp,@allparts)=split(/_/,$partstr);
                   4376:     my $type=pop(@allparts);
1.439     albertel 4377:     my $part=join('_',@allparts);
1.54      albertel 4378:     return ($part,$type);
                   4379: }
                   4380: 
1.44      ng       4381: #------------- end of section for handling grading by section/class ---------
                   4382: #
                   4383: #----------------------------------------------------------------------------
                   4384: 
1.5       albertel 4385: 
1.44      ng       4386: #----------------------------------------------------------------------------
                   4387: #
                   4388: #-------------------------- Next few routines handles grading by csv upload
                   4389: #
                   4390: #--- Javascript to handle csv upload
1.27      albertel 4391: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4392:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4393:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4394:   &js_escape(\$error1);
                   4395:   &js_escape(\$error2);
1.27      albertel 4396:   return(<<ENDPICK);
                   4397:   function verify(vf) {
                   4398:     var foundsomething=0;
                   4399:     var founduname=0;
1.243     albertel 4400:     var foundID=0;
1.743     raeburn  4401:     var foundclicker=0;
1.27      albertel 4402:     for (i=0;i<=vf.nfields.value;i++) {
                   4403:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4404:       if (i==0 && tw!=0) { foundID=1; }
                   4405:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4406:       if (i==2 && tw!=0) { foundclicker=1; }
                   4407:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4408:     }
1.743     raeburn  4409:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4410: 	alert('$error1');
                   4411: 	return;
1.27      albertel 4412:     }
                   4413:     if (foundsomething==0) {
1.246     albertel 4414: 	alert('$error2');
                   4415: 	return;
1.27      albertel 4416:     }
                   4417:     vf.submit();
                   4418:   }
                   4419:   function flip(vf,tf) {
                   4420:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4421:     var i;
                   4422:     for (i=0;i<=vf.nfields.value;i++) {
                   4423:       //can not pick the same destination field for both name and domain
                   4424:       if (((i ==0)||(i ==1)) && 
                   4425:           ((tf==0)||(tf==1)) && 
                   4426:           (i!=tf) &&
                   4427:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4428:         eval('vf.f'+i+'.selectedIndex=0;')
                   4429:       }
                   4430:     }
                   4431:   }
                   4432: ENDPICK
                   4433: }
                   4434: 
                   4435: sub csvupload_javascript_forward_associate {
1.743     raeburn  4436:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4437:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4438:   &js_escape(\$error1);
                   4439:   &js_escape(\$error2);
1.27      albertel 4440:   return(<<ENDPICK);
                   4441:   function verify(vf) {
                   4442:     var foundsomething=0;
                   4443:     var founduname=0;
1.243     albertel 4444:     var foundID=0;
1.743     raeburn  4445:     var foundclicker=0;
1.27      albertel 4446:     for (i=0;i<=vf.nfields.value;i++) {
                   4447:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4448:       if (tw==1) { foundID=1; }
                   4449:       if (tw==2) { founduname=1; }
1.745     raeburn  4450:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4451:       if (tw>4) { foundsomething=1; }
1.27      albertel 4452:     }
1.743     raeburn  4453:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4454: 	alert('$error1');
                   4455: 	return;
1.27      albertel 4456:     }
                   4457:     if (foundsomething==0) {
1.246     albertel 4458: 	alert('$error2');
                   4459: 	return;
1.27      albertel 4460:     }
                   4461:     vf.submit();
                   4462:   }
                   4463:   function flip(vf,tf) {
                   4464:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4465:     var i;
                   4466:     //can not pick the same destination field twice
                   4467:     for (i=0;i<=vf.nfields.value;i++) {
                   4468:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4469:         eval('vf.f'+i+'.selectedIndex=0;')
                   4470:       }
                   4471:     }
                   4472:   }
                   4473: ENDPICK
                   4474: }
                   4475: 
1.26      albertel 4476: sub csvuploadmap_header {
1.324     albertel 4477:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4478:     my $javascript;
1.257     albertel 4479:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4480: 	$javascript=&csvupload_javascript_reverse_associate();
                   4481:     } else {
                   4482: 	$javascript=&csvupload_javascript_forward_associate();
                   4483:     }
1.45      ng       4484: 
1.418     albertel 4485:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4486:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4487:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4488:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4489:     my $reverse=&mt("Reverse Association");
1.41      ng       4490:     $request->print(<<ENDPICK);
1.632     www      4491: <br />
                   4492: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4493: <input type="hidden" name="associate"  value="" />
                   4494: <input type="hidden" name="phase"      value="three" />
                   4495: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4496: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4497: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4498: <input type="hidden" name="upfile_associate" 
1.257     albertel 4499:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4500: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4501: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4502: <hr />
                   4503: ENDPICK
1.597     wenzelju 4504:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4505:     return '';
1.26      albertel 4506: 
                   4507: }
                   4508: 
                   4509: sub csvupload_fields {
1.582     raeburn  4510:     my ($symb,$errorref) = @_;
1.745     raeburn  4511:     my $toolsymb;
                   4512:     if ($symb =~ /ext\.tool$/) {
                   4513:         $toolsymb = $symb;
                   4514:     }
1.582     raeburn  4515:     my (@parts) = &getpartlist($symb,$errorref);
                   4516:     if (ref($errorref)) {
                   4517:         if ($$errorref) {
                   4518:             return;
                   4519:         }
                   4520:     }
                   4521: 
1.556     weissno  4522:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4523: 		['username','Student Username'],
1.743     raeburn  4524: 		['clicker','Clicker ID'],
1.243     albertel 4525: 		['domain','Student Domain']);
1.324     albertel 4526:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4527:     foreach my $part (sort(@parts)) {
                   4528: 	my @datum;
1.745     raeburn  4529: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4530: 	my $name=$part;
1.745     raeburn  4531: 	if (!$display) { $display = $name; }
1.41      ng       4532: 	@datum=($name,$display);
1.244     albertel 4533: 	if ($name=~/^stores_(.*)_awarded/) {
                   4534: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4535: 	}
1.41      ng       4536: 	push(@fields,\@datum);
                   4537:     }
                   4538:     return (@fields);
1.26      albertel 4539: }
                   4540: 
                   4541: sub csvuploadmap_footer {
1.41      ng       4542:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4543:     my $buttontext = &mt('Assign Grades');
1.41      ng       4544:     $request->print(<<ENDPICK);
1.26      albertel 4545: </table>
                   4546: <input type="hidden" name="nfields" value="$i" />
                   4547: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4548: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4549: </form>
                   4550: ENDPICK
                   4551: }
                   4552: 
1.283     albertel 4553: sub checkforfile_js {
1.638     www      4554:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4555:     &js_escape(\$alertmsg);
1.597     wenzelju 4556:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4557:     function checkUpload(formname) {
                   4558: 	if (formname.upfile.value == "") {
1.539     riegler  4559: 	    alert("$alertmsg");
1.86      ng       4560: 	    return false;
                   4561: 	}
                   4562: 	formname.submit();
                   4563:     }
                   4564: CSVFORMJS
1.283     albertel 4565:     return $result;
                   4566: }
                   4567: 
                   4568: sub upcsvScores_form {
1.608     www      4569:     my ($request,$symb) = @_;
1.283     albertel 4570:     if (!$symb) {return '';}
                   4571:     my $result=&checkforfile_js();
1.632     www      4572:     $result.=&Apache::loncommon::start_data_table().
                   4573:              &Apache::loncommon::start_data_table_header_row().
                   4574:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4575:              &Apache::loncommon::end_data_table_header_row().
                   4576:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4577:     my $upload=&mt("Upload Scores");
1.86      ng       4578:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4579:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4580:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4581:     $result.=<<ENDUPFORM;
1.106     albertel 4582: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4583: <input type="hidden" name="symb" value="$symb" />
                   4584: <input type="hidden" name="command" value="csvuploadmap" />
                   4585: $upfile_select
1.589     bisitz   4586: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4587: </form>
                   4588: ENDUPFORM
1.370     www      4589:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4590:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4591:              '</td>'.
                   4592:             &Apache::loncommon::end_data_table_row().
                   4593:             &Apache::loncommon::end_data_table();
1.86      ng       4594:     return $result;
                   4595: }
                   4596: 
                   4597: 
1.26      albertel 4598: sub csvuploadmap {
1.608     www      4599:     my ($request,$symb)= @_;
1.41      ng       4600:     if (!$symb) {return '';}
1.72      ng       4601: 
1.41      ng       4602:     my $datatoken;
1.257     albertel 4603:     if (!$env{'form.datatoken'}) {
1.41      ng       4604: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4605:     } else {
1.742     raeburn  4606: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4607:         if ($datatoken ne '') {
                   4608: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4609:         }
1.26      albertel 4610:     }
1.41      ng       4611:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4612:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4613:     my ($i,$keyfields);
                   4614:     if (@records) {
1.582     raeburn  4615:         my $fieldserror;
                   4616: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4617:         if ($fieldserror) {
                   4618:             $request->print(&navmap_errormsg());
                   4619:             return;
                   4620:         }
1.257     albertel 4621: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4622: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4623: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4624: 							  \@fields);
                   4625: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4626: 	    chop($keyfields);
                   4627: 	} else {
                   4628: 	    unshift(@fields,['none','']);
                   4629: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4630: 							    \@fields);
1.311     banghart 4631:             foreach my $rec (@records) {
                   4632:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4633:                 if (%temp) {
                   4634:                     $keyfields=join(',',sort(keys(%temp)));
                   4635:                     last;
                   4636:                 }
                   4637:             }
1.41      ng       4638: 	}
                   4639:     }
                   4640:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4641: 
1.41      ng       4642:     return '';
1.27      albertel 4643: }
                   4644: 
1.246     albertel 4645: sub csvuploadoptions {
1.608     www      4646:     my ($request,$symb)= @_;
1.632     www      4647:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4648:     $request->print(<<ENDPICK);
                   4649: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4650: <input type="hidden" name="command"    value="csvuploadassign" />
                   4651: <p>
                   4652: <label>
                   4653:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4654:    $overwrite
1.246     albertel 4655: </label>
                   4656: </p>
                   4657: ENDPICK
                   4658:     my %fields=&get_fields();
                   4659:     if (!defined($fields{'domain'})) {
1.257     albertel 4660: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4661: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4662:     }
1.257     albertel 4663:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4664: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4665: 	my $cleankey=$1;
                   4666: 	if ($cleankey eq 'command') { next; }
                   4667: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4668: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4669:     }
                   4670:     # FIXME do a check for any duplicated user ids...
                   4671:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4672:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4673: <hr /></form>'."\n");
1.246     albertel 4674:     return '';
                   4675: }
                   4676: 
                   4677: sub get_fields {
                   4678:     my %fields;
1.257     albertel 4679:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4680:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4681: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4682: 	    if ($env{'form.f'.$i} ne 'none') {
                   4683: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4684: 	    }
                   4685: 	} else {
1.257     albertel 4686: 	    if ($env{'form.f'.$i} ne 'none') {
                   4687: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4688: 	    }
                   4689: 	}
1.27      albertel 4690:     }
1.246     albertel 4691:     return %fields;
                   4692: }
                   4693: 
                   4694: sub csvuploadassign {
1.608     www      4695:     my ($request,$symb)= @_;
1.246     albertel 4696:     if (!$symb) {return '';}
1.345     bowersj2 4697:     my $error_msg = '';
1.742     raeburn  4698:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4699:     if ($datatoken ne '') { 
                   4700:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4701:     }
1.246     albertel 4702:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4703:     my %fields=&get_fields();
1.257     albertel 4704:     my $courseid=$env{'request.course.id'};
1.97      albertel 4705:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4706:     my @notallowed;
1.41      ng       4707:     my @skipped;
1.657     raeburn  4708:     my @warnings;
1.41      ng       4709:     my $countdone=0;
                   4710:     foreach my $grade (@gradedata) {
                   4711: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4712: 	my $domain;
                   4713: 	if ($entries{$fields{'domain'}}) {
                   4714: 	    $domain=$entries{$fields{'domain'}};
                   4715: 	} else {
1.257     albertel 4716: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4717: 	}
1.243     albertel 4718: 	$domain=~s/\s//g;
1.41      ng       4719: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4720: 	$username=~s/\s//g;
1.243     albertel 4721: 	if (!$username) {
                   4722: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4723: 	    $id=~s/\s//g;
1.737     raeburn  4724:             if ($id ne '') {
                   4725: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4726: 	        $username=$ids{$id};
                   4727:             } else {
                   4728:                 if ($entries{$fields{'clicker'}}) {
                   4729:                     my $clicker = $entries{$fields{'clicker'}};
                   4730:                     $clicker=~s/\s//g;
                   4731:                     if ($clicker ne '') {
                   4732:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4733:                         if ($clickers{$clicker} ne '') {  
                   4734:                             my $match = 0;
                   4735:                             my @inclass;
                   4736:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4737:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4738:                                     $username = $poss;
                   4739:                                     push(@inclass,$poss);
                   4740:                                     $match ++;
                   4741:                                     
                   4742:                                 }
                   4743:                             }
                   4744:                             if ($match > 1) {
                   4745:                                 undef($username); 
                   4746:                                 $request->print('<p class="LC_warning">'.
                   4747:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4748:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4749:                             }
                   4750:                         }
                   4751:                     }
                   4752:                 }
                   4753:             }
1.243     albertel 4754: 	}
1.41      ng       4755: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4756: 	    my $id=$entries{$fields{'ID'}};
                   4757: 	    $id=~s/\s//g;
1.737     raeburn  4758:             my $clicker = $entries{$fields{'clicker'}};
                   4759:             $clicker=~s/\s//g;
                   4760:             if ($clicker) {
                   4761:                 push(@skipped,"$clicker:$domain");
                   4762: 	    } elsif ($id) {
1.247     albertel 4763: 		push(@skipped,"$id:$domain");
                   4764: 	    } else {
                   4765: 		push(@skipped,"$username:$domain");
                   4766: 	    }
1.41      ng       4767: 	    next;
                   4768: 	}
1.108     albertel 4769: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4770: 	if (!&canmodify($usec)) {
                   4771: 	    push(@notallowed,"$username:$domain");
                   4772: 	    next;
                   4773: 	}
1.244     albertel 4774: 	my %points;
1.41      ng       4775: 	my %grades;
                   4776: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4777: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4778: 		$dest eq 'domain') { next; }
                   4779: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4780: 	    if ($dest=~/stores_(.*)_points/) {
                   4781: 		my $part=$1;
                   4782: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4783: 					      $symb,$domain,$username);
1.345     bowersj2 4784:                 if ($wgt) {
                   4785:                     $entries{$fields{$dest}}=~s/\s//g;
                   4786:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4787:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4788:                                           : 'correct_by_override';
1.638     www      4789:                     if ($pcr>1) {
1.657     raeburn  4790:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4791:                     }
1.345     bowersj2 4792:                     $grades{"resource.$part.awarded"}=$pcr;
                   4793:                     $grades{"resource.$part.solved"}=$award;
                   4794:                     $points{$part}=1;
                   4795:                 } else {
                   4796:                     $error_msg = "<br />" .
                   4797:                         &mt("Some point values were assigned"
                   4798:                             ." for problems with a weight "
                   4799:                             ."of zero. These values were "
                   4800:                             ."ignored.");
                   4801:                 }
1.244     albertel 4802: 	    } else {
                   4803: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4804: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4805: 		my $store_key=$dest;
                   4806: 		$store_key=~s/^stores/resource/;
                   4807: 		$store_key=~s/_/\./g;
                   4808: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4809: 	    }
1.41      ng       4810: 	}
1.508     www      4811: 	if (! %grades) { 
                   4812:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4813:         } else {
                   4814: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4815: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4816: 					   $env{'request.course.id'},
                   4817: 					   $domain,$username);
1.508     www      4818: 	   if ($result eq 'ok') {
1.627     www      4819: # Successfully stored
1.508     www      4820: 	      $request->print('.');
1.627     www      4821: # Remove from grading queue
                   4822:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4823:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4824:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4825:                                              $domain,$username);
                   4826:               $countdone++;
                   4827:            } else {
1.508     www      4828: 	      $request->print("<p><span class=\"LC_error\">".
                   4829:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4830:                                   "$username:$domain",$result)."</span></p>");
                   4831: 	   }
                   4832: 	   $request->rflush();
                   4833:         }
1.41      ng       4834:     }
1.570     www      4835:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4836:     if (@warnings) {
                   4837:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4838:         $request->print(join(', ',@warnings));
                   4839:     }
1.41      ng       4840:     if (@skipped) {
1.571     www      4841: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4842:         $request->print(join(', ',@skipped));
1.106     albertel 4843:     }
                   4844:     if (@notallowed) {
1.571     www      4845: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4846: 	$request->print(join(', ',@notallowed));
1.41      ng       4847:     }
1.106     albertel 4848:     $request->print("<br />\n");
1.345     bowersj2 4849:     return $error_msg;
1.26      albertel 4850: }
1.44      ng       4851: #------------- end of section for handling csv file upload ---------
                   4852: #
                   4853: #-------------------------------------------------------------------
                   4854: #
1.122     ng       4855: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4856: #
                   4857: #--- Select a page/sequence and a student to grade
1.68      ng       4858: sub pickStudentPage {
1.608     www      4859:     my ($request,$symb) = @_;
1.68      ng       4860: 
1.539     riegler  4861:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4862:     &js_escape(\$alertmsg);
1.597     wenzelju 4863:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4864: 
                   4865: function checkPickOne(formname) {
1.76      ng       4866:     if (radioSelection(formname.student) == null) {
1.539     riegler  4867: 	alert("$alertmsg");
1.68      ng       4868: 	return;
                   4869:     }
1.125     ng       4870:     ptr = pullDownSelection(formname.selectpage);
                   4871:     formname.page.value = formname["page"+ptr].value;
                   4872:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4873:     formname.submit();
                   4874: }
                   4875: 
                   4876: LISTJAVASCRIPT
1.118     ng       4877:     &commonJSfunctions($request);
1.608     www      4878: 
1.257     albertel 4879:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4880:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4881:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4882: 
1.398     albertel 4883:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4884: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4885: 
1.80      ng       4886:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4887:     my $map_error;
                   4888:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4889:     if ($map_error) {
                   4890:         $request->print(&navmap_errormsg());
                   4891:         return; 
                   4892:     }
1.137     albertel 4893:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4894: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4895: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4896: 
                   4897:     # Collection of hidden fields
1.70      ng       4898:     my $ctr=0;
1.68      ng       4899:     foreach (@$titles) {
1.700     bisitz   4900:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4901:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4902:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4903:         $ctr++;
1.68      ng       4904:     }
1.700     bisitz   4905:     $result.='<input type="hidden" name="page" />'."\n".
                   4906:         '<input type="hidden" name="title" />'."\n";
                   4907: 
                   4908:     $result.=&build_section_inputs();
                   4909:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4910:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4911: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4912: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4913: 
1.700     bisitz   4914:     # Show grading options
                   4915:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4916:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4917:     $ctr=0;
                   4918:     foreach (@$titles) {
                   4919: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4920: 	$select.='<option value="'.$ctr.'"'.
                   4921: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4922: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4923: 	$ctr++;
                   4924:     }
1.700     bisitz   4925:     $select.= '</select>';
1.68      ng       4926: 
1.700     bisitz   4927:     $result.=
                   4928:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4929:        .$select
                   4930:        .&Apache::lonhtmlcommon::row_closure();
                   4931: 
                   4932:     $result.=
                   4933:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4934:        .'<label><input type="radio" name="vProb" value="no"'
                   4935:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4936:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4937:            .&mt('yes').'</label>'."\n"
                   4938:        .&Apache::lonhtmlcommon::row_closure();
                   4939: 
                   4940:     $result.=
                   4941:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4942:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4943:            .&mt('none').' </label>'."\n"
                   4944:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4945:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4946:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4947:            .&mt('all submissions with details').' </label>'
                   4948:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4949:     
1.700     bisitz   4950:     $result.=
                   4951:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4952:        .'<input type="text" name="CODE" value="" />'
                   4953:        .&Apache::lonhtmlcommon::row_closure(1)
                   4954:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4955: 
1.700     bisitz   4956:     # Show list of students to select for grading
                   4957:     $result.='<br /><input type="button" '.
1.589     bisitz   4958:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4959: 
1.68      ng       4960:     $request->print($result);
                   4961: 
1.485     albertel 4962:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4963: 	&Apache::loncommon::start_data_table().
                   4964: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4965: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4966: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4967: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4968: 	'<th>'.&nameUserString('header').'</th>'.
                   4969: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4970:  
1.76      ng       4971:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4972:     my $ptr = 1;
1.294     albertel 4973:     foreach my $student (sort 
                   4974: 			 {
                   4975: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4976: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4977: 			     }
                   4978: 			     return $a cmp $b;
                   4979: 			 } (keys(%$fullname))) {
1.68      ng       4980: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4981: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4982:                                   : '</td>');
1.126     ng       4983: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4984: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4985: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4986: 	$studentTable.=
                   4987: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4988:                          : '');
1.68      ng       4989: 	$ptr++;
                   4990:     }
1.484     albertel 4991:     if ($ptr%2 == 0) {
                   4992: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4993: 	    &Apache::loncommon::end_data_table_row();
                   4994:     }
                   4995:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4996:     $studentTable.='<input type="button" '.
1.589     bisitz   4997:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4998: 
                   4999:     $request->print($studentTable);
                   5000: 
                   5001:     return '';
                   5002: }
                   5003: 
                   5004: sub getSymbMap {
1.582     raeburn  5005:     my ($map_error) = @_;
1.132     bowersj2 5006:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5007:     unless (ref($navmap)) {
                   5008:         if (ref($map_error)) {
                   5009:             $$map_error = 'navmap';
                   5010:         }
                   5011:         return;
                   5012:     }
1.68      ng       5013:     my %symbx = ();
                   5014:     my @titles = ();
1.117     bowersj2 5015:     my $minder = 0;
                   5016: 
                   5017:     # Gather every sequence that has problems.
1.240     albertel 5018:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5019: 					       1,0,1);
1.117     bowersj2 5020:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5021: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5022: 	    my $title = $minder.'.'.
                   5023: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5024: 	    push(@titles, $title); # minder in case two titles are identical
                   5025: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5026: 	    $minder++;
1.241     albertel 5027: 	}
1.68      ng       5028:     }
                   5029:     return \@titles,\%symbx;
                   5030: }
                   5031: 
1.72      ng       5032: #
                   5033: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5034: sub displayPage {
1.608     www      5035:     my ($request,$symb) = @_;
1.257     albertel 5036:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5037:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5038:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5039:     my $pageTitle = $env{'form.page'};
1.103     albertel 5040:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5041:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5042:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5043: 
                   5044:     #need to make sure we have the correct data for later EXT calls, 
                   5045:     #thus invalidate the cache
                   5046:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5047:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5048:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5049:     &Apache::lonnet::clear_EXT_cache_status();
                   5050: 
1.103     albertel 5051:     if (!&canview($usec)) {
1.712     bisitz   5052:         $request->print(
                   5053:             '<span class="LC_warning">'.
                   5054:             &mt('Unable to view requested student. ([_1])',
                   5055:                     $env{'form.student'}).
                   5056:             '</span>');
                   5057:         return;
1.103     albertel 5058:     }
1.398     albertel 5059:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5060:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5061: 	'</h3>'."\n";
1.500     albertel 5062:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5063:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5064: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5065:     } else {
                   5066: 	delete($env{'form.CODE'});
                   5067:     }
1.71      ng       5068:     &sub_page_js($request);
                   5069:     $request->print($result);
                   5070: 
1.132     bowersj2 5071:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5072:     unless (ref($navmap)) {
                   5073:         $request->print(&navmap_errormsg());
                   5074:         return;
                   5075:     }
1.257     albertel 5076:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5077:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5078:     if (!$map) {
1.485     albertel 5079: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5080: 	return; 
                   5081:     }
1.68      ng       5082:     my $iterator = $navmap->getIterator($map->map_start(),
                   5083: 					$map->map_finish());
                   5084: 
1.71      ng       5085:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5086: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5087: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5088: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5089: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5090: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5091: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5092: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5093: 
1.382     albertel 5094:     if (defined($env{'form.CODE'})) {
                   5095: 	$studentTable.=
                   5096: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5097:     }
1.381     albertel 5098:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5099: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5100: 
1.594     bisitz   5101:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5102:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5103:         '</span>'."\n".
1.484     albertel 5104: 	&Apache::loncommon::start_data_table().
                   5105: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5106: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5107: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5108: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5109: 
1.329     albertel 5110:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5111:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5112:     $iterator->next(); # skip the first BEGIN_MAP
                   5113:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5114:     while ($depth > 0) {
1.68      ng       5115:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5116:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5117: 
1.745     raeburn  5118:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5119: 	    my $parts = $curRes->parts();
1.68      ng       5120:             my $title = $curRes->compTitle();
1.71      ng       5121: 	    my $symbx = $curRes->symb();
1.746     raeburn  5122:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5123: 	    $studentTable.=
                   5124: 		&Apache::loncommon::start_data_table_row().
                   5125: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5126: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5127: 		                        : '<br />('.&mt('[_1]parts',
                   5128: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5129: 		 ).
                   5130: 		 '</td>';
1.71      ng       5131: 	    $studentTable.='<td valign="top">';
1.382     albertel 5132: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5133:             if ($is_tool) {
                   5134:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5135:             } else {
1.745     raeburn  5136: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5137: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5138: 					         undef,'both',\%form);
                   5139: 	        } else {
                   5140: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5141: 		    $companswer =~ s|<form(.*?)>||g;
                   5142: 		    $companswer =~ s|</form>||g;
                   5143: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5144: #		        $companswer =~ s/$1/ /ms;
                   5145: #		        $request->print('match='.$1."<br />\n");
                   5146: #		    }
                   5147: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5148: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5149: 		}
1.71      ng       5150: 	    }
                   5151: 
1.257     albertel 5152: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5153: 
1.257     albertel 5154: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5155: 		if ($record{'version'} eq '') {
1.745     raeburn  5156:                     my $msg = &mt('No recorded submission for this problem.');
                   5157:                     if ($is_tool) {
                   5158:                         $msg = &mt('No recorded transactions for this external tool');
                   5159:                     }
                   5160: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5161: 		} else {
1.116     ng       5162: 		    my %responseType = ();
                   5163: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5164: 			my @responseIds =$curRes->responseIds($partid);
                   5165: 			my @responseType =$curRes->responseType($partid);
                   5166: 			my %responseIds;
                   5167: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5168: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5169: 			}
                   5170: 			$responseType{$partid} = \%responseIds;
1.116     ng       5171: 		    }
1.148     albertel 5172: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5173: 		}
1.257     albertel 5174: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5175: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5176:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5177: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5178: 									$env{'request.course.id'},
1.726     raeburn  5179: 									'','.submission',undef,
                   5180:                                                                         $usec,$identifier);
1.71      ng       5181:  
                   5182: 	    }
1.103     albertel 5183: 	    if (&canmodify($usec)) {
1.585     bisitz   5184:             $studentTable.=&gradeBox_start();
1.103     albertel 5185: 		foreach my $partid (@{$parts}) {
                   5186: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5187: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5188: 		    $question++;
                   5189: 		}
1.585     bisitz   5190:             $studentTable.=&gradeBox_end();
1.196     albertel 5191: 		$prob++;
1.71      ng       5192: 	    }
                   5193: 	    $studentTable.='</td></tr>';
1.68      ng       5194: 
1.103     albertel 5195: 	}
1.68      ng       5196:         $curRes = $iterator->next();
                   5197:     }
                   5198: 
1.589     bisitz   5199:     $studentTable.=
                   5200:         '</table>'."\n".
                   5201:         '<input type="button" value="'.&mt('Save').'" '.
                   5202:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5203:         '</form>'."\n";
1.71      ng       5204:     $request->print($studentTable);
                   5205: 
                   5206:     return '';
1.119     ng       5207: }
                   5208: 
                   5209: sub displaySubByDates {
1.148     albertel 5210:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5211:     my $isCODE=0;
1.335     albertel 5212:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5213:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5214:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5215:     my $studentTable=&Apache::loncommon::start_data_table().
                   5216: 	&Apache::loncommon::start_data_table_header_row().
                   5217: 	'<th>'.&mt('Date/Time').'</th>'.
                   5218: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5219:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5220: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5221: 	'<th>'.&mt('Status').'</th>'.
                   5222: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5223:     my ($version);
                   5224:     my %mark;
1.148     albertel 5225:     my %orders;
1.119     ng       5226:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5227:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5228:         if ($is_tool) {
                   5229:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5230:         } else {
                   5231:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5232:         }
1.147     albertel 5233:     }
1.335     albertel 5234: 
                   5235:     my $interaction;
1.525     raeburn  5236:     my $no_increment = 1;
1.735     raeburn  5237:     my (%lastrndseed,%lasttype);
1.119     ng       5238:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5239: 	my $timestamp = 
                   5240: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5241: 	if (exists($$record{$version.':resource.0.version'})) {
                   5242: 	    $interaction = $$record{$version.':resource.0.version'};
                   5243: 	}
1.671     raeburn  5244:         if ($isTask && $env{'form.previousversion'}) {
                   5245:             next unless ($interaction == $env{'form.previousversion'});
                   5246:         }
1.335     albertel 5247: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5248: 		             : "$version:resource");
1.467     albertel 5249: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5250: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5251: 	if ($isCODE) {
                   5252: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5253: 	}
1.671     raeburn  5254:         if ($isTask) {
                   5255:             $studentTable.='<td>'.$interaction.'</td>';
                   5256:         }
1.119     ng       5257: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5258: 	my @displaySub = ();
                   5259: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5260:             my ($hidden,$type);
                   5261:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5262:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5263:                 $hidden = 1;
                   5264:             }
1.749     raeburn  5265:             my @matchKey;
                   5266:             if ($isTask) {
                   5267:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
                   5268:             } elsif ($is_tool) {
                   5269:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
                   5270:             } else {
                   5271:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
                   5272:             }
1.122     ng       5273: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5274: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5275: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5276: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5277: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5278:                     if ($is_tool) {
                   5279:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5280:                     } else {
1.749     raeburn  5281: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5282: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5283:                         $displaySub[0].='<span class="LC_nobreak">';
                   5284:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5285:                                        .' <span class="LC_internal_info">'
                   5286:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5287:                                        .'</span>'
                   5288:                                        .' <b>';
                   5289:                         if ($hidden) {
                   5290:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5291:                         } else {
                   5292:                             my ($trial,$rndseed,$newvariation);
                   5293:                             if ($type eq 'randomizetry') {
                   5294:                                 $trial = $$record{"$where.$partid.tries"};
                   5295:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5296:                             }
                   5297: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5298: 			        $displaySub[0].=&mt('Trial not counted');
                   5299: 		            } else {
                   5300: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5301: 					        $$record{"$where.$partid.tries"});
                   5302:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5303:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5304:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5305:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5306:                                     }
1.640     raeburn  5307:                                 }
1.749     raeburn  5308:                                 $lastrndseed{$partid} = $rndseed;
                   5309:                                 $lasttype{$partid} = $type;
                   5310: 		            }
                   5311: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5312:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5313: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5314: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5315: 			        $orders{$partid}->{$responseId}=
                   5316: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5317:                                                $no_increment,$type,$trial,$rndseed);
                   5318: 		            }
                   5319: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5320: 		            $displaySub[0].='&nbsp; '.
                   5321: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5322:                         }
1.596     raeburn  5323:                     }
1.147     albertel 5324: 		}
                   5325: 	    }
1.335     albertel 5326: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5327: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5328: 				    $$record{"$where.$partid.checkedin"},
                   5329: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5330: 					'<br />';
1.335     albertel 5331: 	    }
                   5332: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5333: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5334: 		    lc($$record{"$where.$partid.award"}).' '.
                   5335: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5336: 		    '<br />';
1.749     raeburn  5337: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5338: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5339: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5340: 		}
1.147     albertel 5341: 	    }
1.335     albertel 5342: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5343: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5344: 		unless ($is_tool) {
                   5345: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5346: 		}
1.335     albertel 5347: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5348: 		$displaySub[2].=
1.749     raeburn  5349: 		    $$record{"$version:resource.$partid.regrader"};
                   5350:                 unless ($is_tool) {
                   5351: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5352:                 }
1.147     albertel 5353: 	    }
                   5354: 	}
                   5355: 	# needed because old essay regrader has not parts info
                   5356: 	if (exists $$record{"$version:resource.regrader"}) {
                   5357: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5358: 	}
                   5359: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5360: 	if ($displaySub[2]) {
1.467     albertel 5361: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5362: 	}
1.467     albertel 5363: 	$studentTable.='&nbsp;</td>'.
                   5364: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5365:     }
1.467     albertel 5366:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5367:     return $studentTable;
1.71      ng       5368: }
                   5369: 
                   5370: sub updateGradeByPage {
1.608     www      5371:     my ($request,$symb) = @_;
1.71      ng       5372: 
1.257     albertel 5373:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5374:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5375:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5376:     my $pageTitle = $env{'form.page'};
1.103     albertel 5377:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5378:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5379:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5380:     if (!&canmodify($usec)) {
1.526     raeburn  5381: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5382: 	return;
                   5383:     }
1.398     albertel 5384:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5385:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5386: 	'</h3>'."\n";
1.70      ng       5387: 
1.68      ng       5388:     $request->print($result);
                   5389: 
1.582     raeburn  5390: 
1.132     bowersj2 5391:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5392:     unless (ref($navmap)) {
                   5393:         $request->print(&navmap_errormsg());
                   5394:         return;
                   5395:     }
1.257     albertel 5396:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5397:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5398:     if (!$map) {
1.527     raeburn  5399: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5400: 	return; 
                   5401:     }
1.71      ng       5402:     my $iterator = $navmap->getIterator($map->map_start(),
                   5403: 					$map->map_finish());
1.70      ng       5404: 
1.484     albertel 5405:     my $studentTable=
                   5406: 	&Apache::loncommon::start_data_table().
                   5407: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5408: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5409: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5410: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5411: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5412: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5413: 
                   5414:     $iterator->next(); # skip the first BEGIN_MAP
                   5415:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5416:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5417:     while ($depth > 0) {
1.71      ng       5418:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5419:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5420: 
1.385     albertel 5421:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5422: 	    my $parts = $curRes->parts();
1.71      ng       5423:             my $title = $curRes->compTitle();
                   5424: 	    my $symbx = $curRes->symb();
1.484     albertel 5425: 	    $studentTable.=
                   5426: 		&Apache::loncommon::start_data_table_row().
                   5427: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5428: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5429:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5430: 		.')').'</td>';
1.71      ng       5431: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5432: 
                   5433: 	    my %newrecord=();
                   5434: 	    my @displayPts=();
1.269     raeburn  5435:             my %aggregate = ();
                   5436:             my $aggregateflag = 0;
1.726     raeburn  5437:             if ($env{'form.HIDE'.$prob}) {
                   5438:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5439:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5440:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5441:                 $hideflag += $numchgs;
                   5442:             }
1.71      ng       5443: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5444: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5445: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5446: 
1.257     albertel 5447: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5448: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5449: 		my $partial = $newpts/$wgt;
                   5450: 		my $score;
                   5451: 		if ($partial > 0) {
                   5452: 		    $score = 'correct_by_override';
1.125     ng       5453: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5454: 		    $score = 'incorrect_by_override';
                   5455: 		}
1.257     albertel 5456: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5457: 		if ($dropMenu eq 'excused') {
1.71      ng       5458: 		    $partial = '';
                   5459: 		    $score = 'excused';
1.125     ng       5460: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5461: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5462: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5463: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5464: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5465: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5466: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5467: 		    $changeflag++;
                   5468: 		    $newpts = '';
1.269     raeburn  5469:                     
                   5470:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5471:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5472:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5473:                     if ($aggtries > 0) {
                   5474:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5475:                         $aggregateflag = 1;
                   5476:                     }
1.71      ng       5477: 		}
1.324     albertel 5478: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5479: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5480: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5481: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5482: 		    '&nbsp;<br />';
1.526     raeburn  5483: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5484: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5485: 		    '&nbsp;<br />';
1.71      ng       5486: 		$question++;
1.380     albertel 5487: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5488: 
1.71      ng       5489: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5490: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5491: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5492: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5493: 
                   5494: 		$changeflag++;
                   5495: 	    }
                   5496: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5497: 		my %record = 
                   5498: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5499: 					     $udom,$uname);
                   5500: 
                   5501: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5502: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5503: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5504: 		    $newrecord{'resource.CODE'} = '';
                   5505: 		}
1.257     albertel 5506: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5507: 					$udom,$uname);
1.382     albertel 5508: 		%record = &Apache::lonnet::restore($symbx,
                   5509: 						   $env{'request.course.id'},
                   5510: 						   $udom,$uname);
1.380     albertel 5511: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5512: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5513: 	    }
1.380     albertel 5514: 	    
1.269     raeburn  5515:             if ($aggregateflag) {
                   5516:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5517:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5518:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5519:             }
1.125     ng       5520: 
1.71      ng       5521: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5522: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5523: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5524: 
1.196     albertel 5525: 	    $prob++;
1.68      ng       5526: 	}
1.71      ng       5527:         $curRes = $iterator->next();
1.68      ng       5528:     }
1.98      albertel 5529: 
1.484     albertel 5530:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5531:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5532: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5533: 		  $changeflag).'<br />');
                   5534:     my $hidemsg=($hideflag == 0 ? '' :
                   5535:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5536:                      $hideflag).'<br />');
                   5537:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5538: 
1.70      ng       5539:     return '';
                   5540: }
                   5541: 
1.72      ng       5542: #-------- end of section for handling grading by page/sequence ---------
                   5543: #
                   5544: #-------------------------------------------------------------------
                   5545: 
1.581     www      5546: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5547: #
                   5548: #------ start of section for handling grading by page/sequence ---------
                   5549: 
1.423     albertel 5550: =pod
                   5551: 
                   5552: =head1 Bubble sheet grading routines
                   5553: 
1.424     albertel 5554:   For this documentation:
                   5555: 
                   5556:    'scanline' refers to the full line of characters
                   5557:    from the file that we are parsing that represents one entire sheet
                   5558: 
                   5559:    'bubble line' refers to the data
1.659     raeburn  5560:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5561: 
                   5562: 
1.659     raeburn  5563: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5564: into a course. When a user wants to grade, they select a
1.659     raeburn  5565: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5566: one of the predefined configurations for what each scanline looks
                   5567: like.
                   5568: 
                   5569: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5570: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5571: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5572: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5573: invalid student/employee ID
1.424     albertel 5574: 
                   5575: If the CODE option is used that determines the randomization of the
1.556     weissno  5576: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5577: username:domain.
                   5578: 
                   5579: During the validation phase the instructor can choose to skip scanlines. 
                   5580: 
1.659     raeburn  5581: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5582: 
                   5583:   scantron_original_filename (unmodified original file)
                   5584:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5585:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5586: 
                   5587: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5588: correction information that isn't representable in the bubblesheet
1.424     albertel 5589: file (see &scantron_getfile() for more information)
                   5590: 
                   5591: After all scanlines are either valid, marked as valid or skipped, then
                   5592: foreach line foreach problem in the picked sequence, an ssi request is
                   5593: made that simulates a user submitting their selected letter(s) against
                   5594: the homework problem.
1.423     albertel 5595: 
                   5596: =over 4
                   5597: 
                   5598: 
                   5599: 
                   5600: =item defaultFormData
                   5601: 
                   5602:   Returns html hidden inputs used to hold context/default values.
                   5603: 
                   5604:  Arguments:
                   5605:   $symb - $symb of the current resource 
                   5606: 
                   5607: =cut
1.422     foxr     5608: 
1.81      albertel 5609: sub defaultFormData {
1.324     albertel 5610:     my ($symb)=@_;
1.613     www      5611:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5612: }
                   5613: 
1.447     foxr     5614: 
1.423     albertel 5615: =pod 
                   5616: 
                   5617: =item getSequenceDropDown
                   5618: 
                   5619:    Return html dropdown of possible sequences to grade
                   5620:  
                   5621:  Arguments:
1.582     raeburn  5622:    $symb - $symb of the current resource
                   5623:    $map_error - ref to scalar which will container error if
                   5624:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5625: 
                   5626: =cut
1.422     foxr     5627: 
1.75      albertel 5628: sub getSequenceDropDown {
1.582     raeburn  5629:     my ($symb,$map_error)=@_;
1.75      albertel 5630:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5631:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5632:     if (ref($map_error)) {
                   5633:         return if ($$map_error);
                   5634:     }
1.137     albertel 5635:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5636:     my $ctr=0;
                   5637:     foreach (@$titles) {
                   5638: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5639: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5640: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5641: 	    '>'.$showtitle.'</option>'."\n";
                   5642: 	$ctr++;
                   5643:     }
                   5644:     $result.= '</select>';
                   5645:     return $result;
                   5646: }
                   5647: 
1.495     albertel 5648: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5649:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5650: 
                   5651: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5652: 
1.509     raeburn  5653: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5654:                                    # matchresponse or rankresponse, where 
                   5655:                                    # an individual response can have multiple 
                   5656:                                    # lines
1.503     raeburn  5657: 
                   5658: my %responsetype_per_response;     # responsetype for each response
                   5659: 
1.691     raeburn  5660: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5661:                                    # numbered response. Needed when randomorder
                   5662:                                    # or randompick are in use. Key is ID, value 
                   5663:                                    # is response number.
                   5664: 
1.495     albertel 5665: # Save and restore the bubble lines array to the form env.
                   5666: 
                   5667: 
                   5668: sub save_bubble_lines {
                   5669:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5670: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5671: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5672: 	    $first_bubble_line{$line};
1.503     raeburn  5673:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5674:             $subdivided_bubble_lines{$line};
                   5675:         $env{"form.scantron.responsetype.$line"} =
                   5676:             $responsetype_per_response{$line};
1.495     albertel 5677:     }
1.691     raeburn  5678:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5679:         my $line = $masterseq_id_responsenum{$resid};
                   5680:         $env{"form.scantron.residpart.$line"} = $resid;
                   5681:     }
1.495     albertel 5682: }
                   5683: 
                   5684: 
                   5685: sub restore_bubble_lines {
                   5686:     my $line = 0;
                   5687:     %bubble_lines_per_response = ();
1.691     raeburn  5688:     %masterseq_id_responsenum = ();
1.495     albertel 5689:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5690: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5691: 	$bubble_lines_per_response{$line} = $value;
                   5692: 	$first_bubble_line{$line}  =
                   5693: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5694:         $subdivided_bubble_lines{$line} =
                   5695:             $env{"form.scantron.sub_bubblelines.$line"};
                   5696:         $responsetype_per_response{$line} =
                   5697:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5698:         my $id = $env{"form.scantron.residpart.$line"};
                   5699:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5700: 	$line++;
                   5701:     }
                   5702: }
                   5703: 
1.423     albertel 5704: =pod 
                   5705: 
                   5706: =item scantron_filenames
                   5707: 
                   5708:    Returns a list of the scantron files in the current course 
                   5709: 
                   5710: =cut
1.422     foxr     5711: 
1.202     albertel 5712: sub scantron_filenames {
1.257     albertel 5713:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5714:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5715:     my $getpropath = 1;
1.662     raeburn  5716:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5717:                                                         $cname,$getpropath);
1.202     albertel 5718:     my @possiblenames;
1.662     raeburn  5719:     if (ref($dirlist) eq 'ARRAY') {
                   5720:         foreach my $filename (sort(@{$dirlist})) {
                   5721: 	    ($filename)=split(/&/,$filename);
                   5722: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5723: 	    $filename=~s/^scantron_orig_//;
                   5724: 	    push(@possiblenames,$filename);
                   5725:         }
1.202     albertel 5726:     }
                   5727:     return @possiblenames;
                   5728: }
                   5729: 
1.423     albertel 5730: =pod 
                   5731: 
                   5732: =item scantron_uploads
                   5733: 
                   5734:    Returns  html drop-down list of scantron files in current course.
                   5735: 
                   5736:  Arguments:
                   5737:    $file2grade - filename to set as selected in the dropdown
                   5738: 
                   5739: =cut
1.422     foxr     5740: 
1.202     albertel 5741: sub scantron_uploads {
1.209     ng       5742:     my ($file2grade) = @_;
1.202     albertel 5743:     my $result=	'<select name="scantron_selectfile">';
                   5744:     $result.="<option></option>";
                   5745:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5746: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5747:     }
                   5748:     $result.="</select>";
                   5749:     return $result;
                   5750: }
                   5751: 
1.423     albertel 5752: =pod 
                   5753: 
                   5754: =item scantron_scantab
                   5755: 
                   5756:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5757:   file.
                   5758: 
                   5759: =cut
1.422     foxr     5760: 
1.82      albertel 5761: sub scantron_scantab {
                   5762:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5763:     $result.='<option></option>'."\n";
1.518     raeburn  5764:     my @lines = &get_scantronformat_file();
                   5765:     if (@lines > 0) {
                   5766:         foreach my $line (@lines) {
                   5767:             next if (($line =~ /^\#/) || ($line eq ''));
                   5768: 	    my ($name,$descrip)=split(/:/,$line);
                   5769: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5770:         }
1.82      albertel 5771:     }
                   5772:     $result.='</select>'."\n";
1.518     raeburn  5773:     return $result;
                   5774: }
                   5775: 
                   5776: =pod
                   5777: 
                   5778: =item get_scantronformat_file
                   5779: 
                   5780:   Returns an array containing lines from the scantron format file for
                   5781:   the domain of the course.
                   5782: 
                   5783:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5784:   lines are from this file.
                   5785: 
                   5786:   Otherwise, if a default.tab has been published in RES space by the 
                   5787:   domainconfig user, lines are from this file.
                   5788: 
                   5789:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5790:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5791: 
1.518     raeburn  5792: =cut
                   5793: 
                   5794: sub get_scantronformat_file {
                   5795:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5796:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5797:     my $gottab = 0;
                   5798:     my @lines;
                   5799:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5800:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5801:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5802:             if ($formatfile ne '-1') {
                   5803:                 @lines = split("\n",$formatfile,-1);
                   5804:                 $gottab = 1;
                   5805:             }
                   5806:         }
                   5807:     }
                   5808:     if (!$gottab) {
                   5809:         my $confname = $cdom.'-domainconfig';
                   5810:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5811:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5812:         if ($formatfile ne '-1') {
                   5813:             @lines = split("\n",$formatfile,-1);
                   5814:             $gottab = 1;
                   5815:         }
                   5816:     }
                   5817:     if (!$gottab) {
1.519     raeburn  5818:         my @domains = &Apache::lonnet::current_machine_domains();
                   5819:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5820:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5821:             @lines = <$fh>;
                   5822:             close($fh);
                   5823:         } else {
                   5824:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5825:             @lines = <$fh>;
                   5826:             close($fh);
                   5827:         }
1.518     raeburn  5828:     }
                   5829:     return @lines;
1.82      albertel 5830: }
                   5831: 
1.423     albertel 5832: =pod 
                   5833: 
                   5834: =item scantron_CODElist
                   5835: 
                   5836:   Returns html drop down of the saved CODE lists from current course,
                   5837:   generated from earlier printings.
                   5838: 
                   5839: =cut
1.422     foxr     5840: 
1.186     albertel 5841: sub scantron_CODElist {
1.257     albertel 5842:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5843:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5844:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5845:     my $namechoice='<option></option>';
1.225     albertel 5846:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5847: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5848: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5849: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5850:     }
                   5851:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5852:     return $namechoice;
                   5853: }
                   5854: 
1.423     albertel 5855: =pod 
                   5856: 
                   5857: =item scantron_CODEunique
                   5858: 
                   5859:   Returns the html for "Each CODE to be used once" radio.
                   5860: 
                   5861: =cut
1.422     foxr     5862: 
1.186     albertel 5863: sub scantron_CODEunique {
1.532     bisitz   5864:     my $result='<span class="LC_nobreak">
1.272     albertel 5865:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5866:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5867:                 </span>
1.532     bisitz   5868:                 <span class="LC_nobreak">
1.272     albertel 5869:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5870:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5871:                 </span>';
1.186     albertel 5872:     return $result;
                   5873: }
1.423     albertel 5874: 
                   5875: =pod 
                   5876: 
                   5877: =item scantron_selectphase
                   5878: 
1.659     raeburn  5879:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5880:   Allows for - starting a grading run.
1.424     albertel 5881:              - downloading existing scan data (original, corrected
1.423     albertel 5882:                                                 or skipped info)
                   5883: 
                   5884:              - uploading new scan data
                   5885: 
                   5886:  Arguments:
                   5887:   $r          - The Apache request object
                   5888:   $file2grade - name of the file that contain the scanned data to score
                   5889: 
                   5890: =cut
1.186     albertel 5891: 
1.75      albertel 5892: sub scantron_selectphase {
1.608     www      5893:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5894:     if (!$symb) {return '';}
1.582     raeburn  5895:     my $map_error;
                   5896:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5897:     if ($map_error) {
                   5898:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5899:         return;
                   5900:     }
1.324     albertel 5901:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5902:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5903:     my $format_selector=&scantron_scantab();
1.186     albertel 5904:     my $CODE_selector=&scantron_CODElist();
                   5905:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5906:     my $result;
1.422     foxr     5907: 
1.513     foxr     5908:     $ssi_error = 0;
                   5909: 
1.606     wenzelju 5910:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5911:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5912: 
                   5913: 	# Chunk of form to prompt for a scantron file upload.
                   5914: 
                   5915:         $r->print('
                   5916:     <br />
                   5917:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5918:        '.&Apache::loncommon::start_data_table_header_row().'
                   5919:             <th>
                   5920:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5921:             </th>
                   5922:        '.&Apache::loncommon::end_data_table_header_row().'
                   5923:        '.&Apache::loncommon::start_data_table_row().'
                   5924:             <td>
                   5925: ');
1.608     www      5926:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5927:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5928:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5929:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5930:     &js_escape(\$alertmsg);
1.606     wenzelju 5931:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5932:     function checkUpload(formname) {
                   5933: 	if (formname.upfile.value == "") {
1.736     damieng  5934: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5935: 	    return false;
                   5936: 	}
                   5937: 	formname.submit();
                   5938:     }'));
                   5939:     $r->print('
                   5940:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5941:                 '.$default_form_data.'
                   5942:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5943:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5944:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5945:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5946:                 <br />
                   5947:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5948:               </form>
                   5949: ');
                   5950: 
                   5951:         $r->print('
                   5952:             </td>
                   5953:        '.&Apache::loncommon::end_data_table_row().'
                   5954:        '.&Apache::loncommon::end_data_table().'
                   5955: ');
                   5956:     }
                   5957: 
1.422     foxr     5958:     # Chunk of form to prompt for a file to grade and how:
                   5959: 
1.489     albertel 5960:     $result.= '
                   5961:     <br />
                   5962:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5963:     <input type="hidden" name="command" value="scantron_warning" />
                   5964:     '.$default_form_data.'
                   5965:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5966:        '.&Apache::loncommon::start_data_table_header_row().'
                   5967:             <th colspan="2">
1.492     albertel 5968:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5969:             </th>
                   5970:        '.&Apache::loncommon::end_data_table_header_row().'
                   5971:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5972:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5973:        '.&Apache::loncommon::end_data_table_row().'
                   5974:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5975:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5976:        '.&Apache::loncommon::end_data_table_row().'
                   5977:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5978:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5979:        '.&Apache::loncommon::end_data_table_row().'
                   5980:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5981:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5982:        '.&Apache::loncommon::end_data_table_row().'
                   5983:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5984:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5985:        '.&Apache::loncommon::end_data_table_row().'
                   5986:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5987: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5988:             <td>
1.492     albertel 5989: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5990:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5991:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5992: 	    </td>
1.489     albertel 5993:        '.&Apache::loncommon::end_data_table_row().'
                   5994:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5995:             <td colspan="2">
1.572     www      5996:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5997:             </td>
1.489     albertel 5998:        '.&Apache::loncommon::end_data_table_row().'
                   5999:     '.&Apache::loncommon::end_data_table().'
                   6000:     </form>
                   6001: ';
1.162     albertel 6002:    
                   6003:     $r->print($result);
                   6004: 
1.422     foxr     6005: 
                   6006: 
                   6007:     # Chunk of the form that prompts to view a scoring office file,
                   6008:     # corrected file, skipped records in a file.
                   6009: 
1.489     albertel 6010:     $r->print('
                   6011:    <br />
                   6012:    <form action="/adm/grades" name="scantron_download">
                   6013:      '.$default_form_data.'
                   6014:      <input type="hidden" name="command" value="scantron_download" />
                   6015:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6016:        '.&Apache::loncommon::start_data_table_header_row().'
                   6017:               <th>
1.492     albertel 6018:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6019:               </th>
                   6020:        '.&Apache::loncommon::end_data_table_header_row().'
                   6021:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6022:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6023:                 <br />
1.492     albertel 6024:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6025:        '.&Apache::loncommon::end_data_table_row().'
                   6026:      '.&Apache::loncommon::end_data_table().'
                   6027:    </form>
                   6028:    <br />
                   6029: ');
1.162     albertel 6030: 
1.457     banghart 6031:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6032: 
1.694     bisitz   6033:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6034:              $default_form_data."\n".
                   6035:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6036:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6037:              '<th colspan="2">
1.572     www      6038:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6039:              '</th>'."\n".
                   6040:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6041:               &Apache::loncommon::start_data_table_row()."\n".
                   6042:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6043:               '<td> '.$sequence_selector.' </td>'.
                   6044:               &Apache::loncommon::end_data_table_row()."\n".
                   6045:               &Apache::loncommon::start_data_table_row()."\n".
                   6046:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6047:               '<td> '.$file_selector.' </td>'."\n".
                   6048:               &Apache::loncommon::end_data_table_row()."\n".
                   6049:               &Apache::loncommon::start_data_table_row()."\n".
                   6050:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6051:               '<td> '.$format_selector.' </td>'."\n".
                   6052:               &Apache::loncommon::end_data_table_row()."\n".
                   6053:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6054:               '<td> '.&mt('Options').' </td>'."\n".
                   6055:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6056:               &Apache::loncommon::end_data_table_row()."\n".
                   6057:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6058:               '<td colspan="2">'."\n".
                   6059:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6060:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6061:               '</td>'."\n".
                   6062:               &Apache::loncommon::end_data_table_row()."\n".
                   6063:               &Apache::loncommon::end_data_table()."\n".
                   6064:               '</form><br />');
                   6065:     return;
1.75      albertel 6066: }
                   6067: 
1.423     albertel 6068: =pod
                   6069: 
                   6070: =item get_scantron_config
                   6071: 
1.711     bisitz   6072:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 6073:    hash of configuration file fields.
                   6074: 
                   6075:  Arguments:
                   6076:     which - the name of the configuration to parse from the file.
                   6077: 
                   6078: 
                   6079:  Returns:
                   6080:             If the named configuration is not in the file, an empty
                   6081:             hash is returned.
                   6082:     a hash with the fields
                   6083:       name         - internal name for the this configuration setup
                   6084:       description  - text to display to operator that describes this config
                   6085:       CODElocation - if 0 or the string 'none'
                   6086:                           - no CODE exists for this config
                   6087:                      if -1 || the string 'letter'
                   6088:                           - a CODE exists for this config and is
                   6089:                             a string of letters
                   6090:                      Unsupported value (but planned for future support)
                   6091:                           if a positive integer
                   6092:                                - The CODE exists as the first n items from
                   6093:                                  the question section of the form
                   6094:                           if the string 'number'
                   6095:                                - The CODE exists for this config and is
                   6096:                                  a string of numbers
                   6097:       CODEstart   - (only matter if a CODE exists) column in the line where
                   6098:                      the CODE starts
                   6099:       CODElength  - length of the CODE
1.573     bisitz   6100:       IDstart     - column where the student/employee ID starts
1.556     weissno  6101:       IDlength    - length of the student/employee ID info
1.423     albertel 6102:       Qstart      - column where the information from the bubbled
                   6103:                     'questions' start
                   6104:       Qlength     - number of columns comprising a single bubble line from
                   6105:                     the sheet. (usually either 1 or 10)
1.424     albertel 6106:       Qon         - either a single character representing the character used
1.423     albertel 6107:                     to signal a bubble was chosen in the positional setup, or
                   6108:                     the string 'letter' if the letter of the chosen bubble is
                   6109:                     in the final, or 'number' if a number representing the
                   6110:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 6111:       Qoff        - the character used to represent that a bubble was
                   6112:                     left blank
1.423     albertel 6113:       PaperID     - if the scanning process generates a unique number for each
                   6114:                     sheet scanned the column that this ID number starts in
                   6115:       PaperIDlength - number of columns that comprise the unique ID number
                   6116:                       for the sheet of paper
1.424     albertel 6117:       FirstName   - column that the first name starts in
1.423     albertel 6118:       FirstNameLength - number of columns that the first name spans
                   6119:  
                   6120:       LastName    - column that the last name starts in
                   6121:       LastNameLength - number of columns that the last name spans
1.649     raeburn  6122:       BubblesPerRow - number of bubbles available in each row used to 
                   6123:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  6124: 
1.423     albertel 6125: =cut
1.422     foxr     6126: 
1.82      albertel 6127: sub get_scantron_config {
                   6128:     my ($which) = @_;
1.518     raeburn  6129:     my @lines = &get_scantronformat_file();
1.82      albertel 6130:     my %config;
1.157     albertel 6131:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  6132:     foreach my $line (@lines) {
1.82      albertel 6133: 	my ($name,$descrip)=split(/:/,$line);
                   6134: 	if ($name ne $which ) { next; }
                   6135: 	chomp($line);
                   6136: 	my @config=split(/:/,$line);
                   6137: 	$config{'name'}=$config[0];
                   6138: 	$config{'description'}=$config[1];
                   6139: 	$config{'CODElocation'}=$config[2];
                   6140: 	$config{'CODEstart'}=$config[3];
                   6141: 	$config{'CODElength'}=$config[4];
                   6142: 	$config{'IDstart'}=$config[5];
                   6143: 	$config{'IDlength'}=$config[6];
                   6144: 	$config{'Qstart'}=$config[7];
1.497     foxr     6145:  	$config{'Qlength'}=$config[8];
1.82      albertel 6146: 	$config{'Qoff'}=$config[9];
                   6147: 	$config{'Qon'}=$config[10];
1.157     albertel 6148: 	$config{'PaperID'}=$config[11];
                   6149: 	$config{'PaperIDlength'}=$config[12];
                   6150: 	$config{'FirstName'}=$config[13];
                   6151: 	$config{'FirstNamelength'}=$config[14];
                   6152: 	$config{'LastName'}=$config[15];
                   6153: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  6154:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 6155: 	last;
                   6156:     }
                   6157:     return %config;
                   6158: }
                   6159: 
1.423     albertel 6160: =pod 
                   6161: 
                   6162: =item username_to_idmap
                   6163: 
1.556     weissno  6164:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6165:     student username:domain. If a single ID occurs for more than one student,
                   6166:     the status of the student is checked, and if Active, the value in the hash
                   6167:     will be set to the Active student.
1.423     albertel 6168: 
                   6169:   Arguments:
                   6170: 
                   6171:     $classlist - reference to the class list hash. This is a hash
                   6172:                  keyed by student name:domain  whose elements are references
1.424     albertel 6173:                  to arrays containing various chunks of information
1.423     albertel 6174:                  about the student. (See loncoursedata for more info).
                   6175: 
                   6176:   Returns
                   6177:     %idmap - the constructed hash
                   6178: 
                   6179: =cut
                   6180: 
1.82      albertel 6181: sub username_to_idmap {
                   6182:     my ($classlist)= @_;
                   6183:     my %idmap;
                   6184:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6185:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6186:         unless ($id eq '') {
                   6187:             if (!exists($idmap{$id})) {
                   6188:                 $idmap{$id} = $student;
                   6189:             } else {
                   6190:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6191:                 if ($status eq 'Active') {
                   6192:                     $idmap{$id} = $student;
                   6193:                 }
                   6194:             }
                   6195:         }
1.82      albertel 6196:     }
                   6197:     return %idmap;
                   6198: }
1.423     albertel 6199: 
                   6200: =pod
                   6201: 
1.424     albertel 6202: =item scantron_fixup_scanline
1.423     albertel 6203: 
                   6204:    Process a requested correction to a scanline.
                   6205: 
                   6206:   Arguments:
                   6207:     $scantron_config   - hash from &get_scantron_config()
                   6208:     $scan_data         - hash of correction information 
                   6209:                           (see &scantron_getfile())
                   6210:     $line              - existing scanline
                   6211:     $whichline         - line number of the passed in scanline
                   6212:     $field             - type of change to process 
                   6213:                          (either 
1.573     bisitz   6214:                           'ID'     -> correct the student/employee ID
1.423     albertel 6215:                           'CODE'   -> correct the CODE
                   6216:                           'answer' -> fixup the submitted answers)
                   6217:     
                   6218:    $args               - hash of additional info,
                   6219:                           - 'ID' 
                   6220:                                'newid' -> studentID to use in replacement
1.424     albertel 6221:                                           of existing one
1.423     albertel 6222:                           - 'CODE' 
                   6223:                                'CODE_ignore_dup' - set to true if duplicates
                   6224:                                                    should be ignored.
                   6225: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6226:                                         if the existing unfound code should
1.423     albertel 6227:                                         be used as is
                   6228:                           - 'answer'
                   6229:                                'response' - new answer or 'none' if blank
                   6230:                                'question' - the bubble line to change
1.503     raeburn  6231:                                'questionnum' - the question identifier,
                   6232:                                                may include subquestion. 
1.423     albertel 6233: 
                   6234:   Returns:
                   6235:     $line - the modified scanline
                   6236: 
                   6237:   Side effects: 
                   6238:     $scan_data - may be updated
                   6239: 
                   6240: =cut
                   6241: 
1.82      albertel 6242: 
1.157     albertel 6243: sub scantron_fixup_scanline {
                   6244:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6245:     if ($field eq 'ID') {
                   6246: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6247: 	    return ($line,1,'New value too large');
1.157     albertel 6248: 	}
                   6249: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6250: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6251: 				     $args->{'newid'});
                   6252: 	}
                   6253: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6254: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6255: 	if ($args->{'newid'}=~/^\s*$/) {
                   6256: 	    &scan_data($scan_data,"$whichline.user",
                   6257: 		       $args->{'username'}.':'.$args->{'domain'});
                   6258: 	}
1.186     albertel 6259:     } elsif ($field eq 'CODE') {
1.192     albertel 6260: 	if ($args->{'CODE_ignore_dup'}) {
                   6261: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6262: 	}
                   6263: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6264: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6265: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6266: 		return ($line,1,'New CODE value too large');
                   6267: 	    }
                   6268: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6269: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6270: 	    }
                   6271: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6272: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6273: 	}
1.157     albertel 6274:     } elsif ($field eq 'answer') {
1.497     foxr     6275: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6276: 	my $off=$scantron_config->{'Qoff'};
                   6277: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6278: 	my $answer=${off}x$length;
                   6279: 	if ($args->{'response'} eq 'none') {
                   6280: 	    &scan_data($scan_data,
1.503     raeburn  6281: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6282: 	} else {
                   6283: 	    if ($on eq 'letter') {
                   6284: 		my @alphabet=('A'..'Z');
                   6285: 		$answer=$alphabet[$args->{'response'}];
                   6286: 	    } elsif ($on eq 'number') {
                   6287: 		$answer=$args->{'response'}+1;
                   6288: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6289: 	    } else {
1.497     foxr     6290: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6291: 	    }
1.497     foxr     6292: 	    &scan_data($scan_data,
1.503     raeburn  6293: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6294: 	}
1.497     foxr     6295: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6296: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6297:     }
                   6298:     return $line;
                   6299: }
1.423     albertel 6300: 
                   6301: =pod
                   6302: 
                   6303: =item scan_data
                   6304: 
                   6305:     Edit or look up  an item in the scan_data hash.
                   6306: 
                   6307:   Arguments:
                   6308:     $scan_data  - The hash (see scantron_getfile)
                   6309:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6310:                   scantronfilename_key).
1.423     albertel 6311:     $data        - New value of the hash entry.
                   6312:     $delete      - If true, the entry is removed from the hash.
                   6313: 
                   6314:   Returns:
                   6315:     The new value of the hash table field (undefined if deleted).
                   6316: 
                   6317: =cut
                   6318: 
                   6319: 
1.157     albertel 6320: sub scan_data {
                   6321:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6322:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6323:     if (defined($value)) {
                   6324: 	$scan_data->{$filename.'_'.$key} = $value;
                   6325:     }
                   6326:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6327:     return $scan_data->{$filename.'_'.$key};
                   6328: }
1.423     albertel 6329: 
1.495     albertel 6330: # ----- These first few routines are general use routines.----
                   6331: 
                   6332: # Return the number of occurences of a pattern in a string.
                   6333: 
                   6334: sub occurence_count {
                   6335:     my ($string, $pattern) = @_;
                   6336: 
                   6337:     my @matches = ($string =~ /$pattern/g);
                   6338: 
                   6339:     return scalar(@matches);
                   6340: }
                   6341: 
                   6342: 
                   6343: # Take a string known to have digits and convert all the
                   6344: # digits into letters in the range J,A..I.
                   6345: 
                   6346: sub digits_to_letters {
                   6347:     my ($input) = @_;
                   6348: 
                   6349:     my @alphabet = ('J', 'A'..'I');
                   6350: 
                   6351:     my @input    = split(//, $input);
                   6352:     my $output ='';
                   6353:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6354: 	if ($input[$i] =~ /\d/) {
                   6355: 	    $output .= $alphabet[$input[$i]];
                   6356: 	} else {
                   6357: 	    $output .= $input[$i];
                   6358: 	}
                   6359:     }
                   6360:     return $output;
                   6361: }
                   6362: 
1.423     albertel 6363: =pod 
                   6364: 
                   6365: =item scantron_parse_scanline
                   6366: 
1.711     bisitz   6367:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6368: 
                   6369:  Arguments:
1.711     bisitz   6370:     line             - The text of the bubblesheet file line to process
1.423     albertel 6371:     whichline        - Line number
1.711     bisitz   6372:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6373:     scan_data        - Hash of extra information about the scanline
                   6374:                        (see scantron_getfile for more information)
                   6375:     just_header      - True if should not process question answers but only
                   6376:                        the stuff to the left of the answers.
1.691     raeburn  6377:     randomorder      - True if randomorder in use
                   6378:     randompick       - True if randompick in use
                   6379:     sequence         - Exam folder URL
                   6380:     master_seq       - Ref to array containing symbs in exam folder
                   6381:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6382:                        (corresponding values are resource objects)
                   6383:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6384:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6385:                        are refs to an array of resource objects, ordered
                   6386:                        according to order used for CODE, when randomorder
                   6387:                        and or randompick are in use.
                   6388:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6389:                        for current line to question number used for same question
                   6390:                         in "Master Sequence" (as seen by Course Coordinator).
                   6391:     startline        - Ref to hash where key is question number (0 is first)
                   6392:                        and value is number of first bubble line for current 
                   6393:                        student or code-based randompick and/or randomorder.
                   6394:     totalref         - Ref of scalar used to score total number of bubble
                   6395:                        lines needed for responses in a scan line (used when
                   6396:                        randompick in use. 
                   6397:     
1.423     albertel 6398:  Returns:
                   6399:    Hash containing the result of parsing the scanline
                   6400: 
                   6401:    Keys are all proceeded by the string 'scantron.'
                   6402: 
                   6403:        CODE    - the CODE in use for this scanline
                   6404:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6405:                  by the operator
                   6406:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6407:                             CODEs were selected, but the usage has been
                   6408:                             forced by the operator
1.556     weissno  6409:        ID  - student/employee ID
1.423     albertel 6410:        PaperID - if used, the ID number printed on the sheet when the 
                   6411:                  paper was scanned
                   6412:        FirstName - first name from the sheet
                   6413:        LastName  - last name from the sheet
                   6414: 
                   6415:      if just_header was not true these key may also exist
                   6416: 
1.447     foxr     6417:        missingerror - a list of bubble ranges that are considered to be answers
                   6418:                       to a single question that don't have any bubbles filled in.
                   6419:                       Of the form questionnumber:firstbubblenumber:count.
                   6420:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6421:                       to a single question that have more than one bubble filled in.
                   6422:                       Of the form questionnumber::firstbubblenumber:count
                   6423:    
                   6424:                 In the above, count is the number of bubble responses in the
                   6425:                 input line needed to represent the possible answers to the question.
                   6426:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6427:                 per line would have count = 2.
                   6428: 
1.423     albertel 6429:        maxquest     - the number of the last bubble line that was parsed
                   6430: 
                   6431:        (<number> starts at 1)
                   6432:        <number>.answer - zero or more letters representing the selected
                   6433:                          letters from the scanline for the bubble line 
                   6434:                          <number>.
                   6435:                          if blank there was either no bubble or there where
                   6436:                          multiple bubbles, (consult the keys missingerror and
                   6437:                          doubleerror if this is an error condition)
                   6438: 
                   6439: =cut
                   6440: 
1.82      albertel 6441: sub scantron_parse_scanline {
1.691     raeburn  6442:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6443:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6444:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6445: 
1.82      albertel 6446:     my %record;
1.691     raeburn  6447:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6448:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6449: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6450: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6451: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6452: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6453: 	    $record{'scantron.CODE'}=substr($data,
                   6454: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6455: 					    $$scantron_config{'CODElength'});
1.191     albertel 6456: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6457: 		$record{'scantron.useCODE'}=1;
                   6458: 	    }
1.192     albertel 6459: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6460: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6461: 	    }
1.82      albertel 6462: 	} else {
                   6463: 	    #FIXME interpret first N questions
                   6464: 	}
                   6465:     }
1.83      albertel 6466:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6467: 				  $$scantron_config{'IDlength'});
1.157     albertel 6468:     $record{'scantron.PaperID'}=
                   6469: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6470: 	       $$scantron_config{'PaperIDlength'});
                   6471:     $record{'scantron.FirstName'}=
                   6472: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6473: 	       $$scantron_config{'FirstNamelength'});
                   6474:     $record{'scantron.LastName'}=
                   6475: 	substr($data,$$scantron_config{'LastName'}-1,
                   6476: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6477:     if ($just_header) { return \%record; }
1.194     albertel 6478: 
1.82      albertel 6479:     my @alphabet=('A'..'Z');
                   6480:     my $questnum=0;
1.447     foxr     6481:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6482: 
1.691     raeburn  6483:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6484:     if ($randompick || $randomorder) {
                   6485:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6486:                                          $master_seq,$symb_to_resource,
                   6487:                                          $partids_by_symb,$orderedforcode,
                   6488:                                          $respnumlookup,$startline);
                   6489:         if ($total) {
                   6490:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6491:         }
                   6492:         if (ref($totalref)) {
                   6493:             $$totalref = $total;
                   6494:         }
                   6495:     }
                   6496:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6497:     chomp($questions);		# Get rid of any trailing \n.
                   6498:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6499:     while (length($questions)) {
1.691     raeburn  6500:         my $answers_needed;
                   6501:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6502:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6503:         } else {
                   6504: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6505:         }
1.503     raeburn  6506:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6507:                              || 1;
                   6508:         $questnum++;
                   6509:         my $quest_id = $questnum;
                   6510:         my $currentquest = substr($questions,0,$answer_length);
                   6511:         $questions       = substr($questions,$answer_length);
                   6512:         if (length($currentquest) < $answer_length) { next; }
                   6513: 
1.691     raeburn  6514:         my $subdivided;
                   6515:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6516:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6517:         } else {
                   6518:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6519:         }
                   6520:         if ($subdivided =~ /,/) {
1.503     raeburn  6521:             my $subquestnum = 1;
                   6522:             my $subquestions = $currentquest;
1.691     raeburn  6523:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6524:             foreach my $subans (@subanswers_needed) {
                   6525:                 my $subans_length =
                   6526:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6527:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6528:                 $subquestions   = substr($subquestions,$subans_length);
                   6529:                 $quest_id = "$questnum.$subquestnum";
                   6530:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6531:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6532:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6533:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6534:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6535:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6536:                 } else {
                   6537:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6538:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6539:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6540:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6541:                 }
                   6542:                 $subquestnum ++;
                   6543:             }
                   6544:         } else {
                   6545:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6546:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6547:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6548:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6549:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6550:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6551:             } else {
                   6552:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6553:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6554:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6555:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6556:             }
                   6557:         }
                   6558:     }
                   6559:     $record{'scantron.maxquest'}=$questnum;
                   6560:     return \%record;
                   6561: }
1.447     foxr     6562: 
1.691     raeburn  6563: sub get_master_seq {
                   6564:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6565:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6566:                    (ref($symb_to_resource) eq 'HASH'));
                   6567:     my $resource_error;
                   6568:     foreach my $resource (@{$resources}) {
                   6569:         my $ressymb;
                   6570:         if (ref($resource)) {
                   6571:             $ressymb = $resource->symb();
                   6572:             push(@{$master_seq},$ressymb);
                   6573:             $symb_to_resource->{$ressymb} = $resource;
                   6574:         } else {
                   6575:             $resource_error = 1;
                   6576:             last;
                   6577:         }
                   6578:     }
                   6579:     return $resource_error;
                   6580: }
                   6581: 
                   6582: sub get_respnum_lookups {
                   6583:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6584:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6585:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6586:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6587:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6588:                    (ref($startline) eq 'HASH'));
                   6589:     my ($user,$scancode);
                   6590:     if ((exists($record->{'scantron.CODE'})) &&
                   6591:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6592:         $scancode = $record->{'scantron.CODE'};
                   6593:     } else {
                   6594:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6595:     }
                   6596:     my @mapresources =
                   6597:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6598:                      $orderedforcode);
                   6599:     my $total = 0;
                   6600:     my $count = 0;
                   6601:     foreach my $resource (@mapresources) {
                   6602:         my $id = $resource->id();
                   6603:         my $symb = $resource->symb();
                   6604:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6605:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6606:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6607:                 if ($respnum ne '') {
                   6608:                     $respnumlookup->{$count} = $respnum;
                   6609:                     $startline->{$count} = $total;
                   6610:                     $total += $bubble_lines_per_response{$respnum};
                   6611:                     $count ++;
                   6612:                 }
                   6613:             }
                   6614:         }
                   6615:     }
                   6616:     return $total;
                   6617: }
                   6618: 
1.503     raeburn  6619: sub scantron_validator_lettnum {
                   6620:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6621:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6622:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6623: 
                   6624:     # Qon 'letter' implies for each slot in currquest we have:
                   6625:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6626:     #    about anything else (esp. a value of Qoff) for missing
                   6627:     #    bubbles.
                   6628:     #
                   6629:     # Qon 'number' implies each slot gives a digit that indexes the
                   6630:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6631:     #    and * or ? for double bubbles on a single line.
                   6632:     #
1.447     foxr     6633: 
1.503     raeburn  6634:     my $matchon;
                   6635:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6636:         $matchon = '[A-Z]';
                   6637:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6638:         $matchon = '\d';
                   6639:     }
                   6640:     my $occurrences = 0;
1.691     raeburn  6641:     my $responsenum = $questnum-1;
                   6642:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6643:        $responsenum = $respnumlookup->{$questnum-1} 
                   6644:     }
                   6645:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6646:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6647:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6648:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6649:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6650:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6651:         my @singlelines = split('',$currquest);
                   6652:         foreach my $entry (@singlelines) {
                   6653:             $occurrences = &occurence_count($entry,$matchon);
                   6654:             if ($occurrences > 1) {
                   6655:                 last;
                   6656:             }
1.691     raeburn  6657:         }
1.503     raeburn  6658:     } else {
                   6659:         $occurrences = &occurence_count($currquest,$matchon); 
                   6660:     }
                   6661:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6662:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6663:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6664:             my $bubble = substr($currquest,$ans,1);
                   6665:             if ($bubble =~ /$matchon/ ) {
                   6666:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6667:                     if ($bubble == 0) {
                   6668:                         $bubble = 10; 
                   6669:                     }
                   6670:                     $record->{"scantron.$ansnum.answer"} = 
                   6671:                         $alphabet->[$bubble-1];
                   6672:                 } else {
                   6673:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6674:                 }
                   6675:             } else {
                   6676:                 $record->{"scantron.$ansnum.answer"}='';
                   6677:             }
                   6678:             $ansnum++;
                   6679:         }
                   6680:     } elsif (!defined($currquest)
                   6681:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6682:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6683:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6684:             $record->{"scantron.$ansnum.answer"}='';
                   6685:             $ansnum++;
                   6686:         }
                   6687:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6688:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6689:         }
                   6690:     } else {
                   6691:         if ($$scantron_config{'Qon'} eq 'number') {
                   6692:             $currquest = &digits_to_letters($currquest);            
                   6693:         }
                   6694:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6695:             my $bubble = substr($currquest,$ans,1);
                   6696:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6697:             $ansnum++;
                   6698:         }
                   6699:     }
                   6700:     return $ansnum;
                   6701: }
1.447     foxr     6702: 
1.503     raeburn  6703: sub scantron_validator_positional {
                   6704:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6705:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6706:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6707: 
1.503     raeburn  6708:     # Otherwise there's a positional notation;
                   6709:     # each bubble line requires Qlength items, and there are filled in
                   6710:     # bubbles for each case where there 'Qon' characters.
                   6711:     #
1.447     foxr     6712: 
1.503     raeburn  6713:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6714: 
1.503     raeburn  6715:     # If the split only gives us one element.. the full length of the
                   6716:     # answer string, no bubbles are filled in:
1.447     foxr     6717: 
1.507     raeburn  6718:     if ($answers_needed eq '') {
                   6719:         return;
                   6720:     }
                   6721: 
1.503     raeburn  6722:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6723:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6724:             $record->{"scantron.$ansnum.answer"}='';
                   6725:             $ansnum++;
                   6726:         }
                   6727:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6728:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6729:         }
                   6730:     } elsif (scalar(@array) == 2) {
                   6731:         my $location = length($array[0]);
                   6732:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6733:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6734:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6735:             if ($ans eq $line_num) {
                   6736:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6737:             } else {
                   6738:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6739:             }
                   6740:             $ansnum++;
                   6741:          }
                   6742:     } else {
                   6743:         #  If there's more than one instance of a bubble character
                   6744:         #  That's a double bubble; with positional notation we can
                   6745:         #  record all the bubbles filled in as well as the
                   6746:         #  fact this response consists of multiple bubbles.
                   6747:         #
1.691     raeburn  6748:         my $responsenum = $questnum-1;
                   6749:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6750:             $responsenum = $respnumlookup->{$questnum-1}
                   6751:         }
                   6752:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6753:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6754:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6755:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6756:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6757:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6758:             my $doubleerror = 0;
                   6759:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6760:                    (!$doubleerror)) {
                   6761:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6762:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6763:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6764:                if (length(@currarray) > 2) {
                   6765:                    $doubleerror = 1;
                   6766:                } 
                   6767:             }
                   6768:             if ($doubleerror) {
                   6769:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6770:             }
                   6771:         } else {
                   6772:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6773:         }
                   6774:         my $item = $ansnum;
                   6775:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6776:             $record->{"scantron.$item.answer"} = '';
                   6777:             $item ++;
                   6778:         }
1.447     foxr     6779: 
1.503     raeburn  6780:         my @ans=@array;
                   6781:         my $i=0;
                   6782:         my $increment = 0;
                   6783:         while ($#ans) {
                   6784:             $i+=length($ans[0]) + $increment;
                   6785:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6786:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6787:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6788:             shift(@ans);
                   6789:             $increment = 1;
                   6790:         }
                   6791:         $ansnum += $answers_needed;
1.82      albertel 6792:     }
1.503     raeburn  6793:     return $ansnum;
1.82      albertel 6794: }
                   6795: 
1.423     albertel 6796: =pod
                   6797: 
                   6798: =item scantron_add_delay
                   6799: 
                   6800:    Adds an error message that occurred during the grading phase to a
                   6801:    queue of messages to be shown after grading pass is complete
                   6802: 
                   6803:  Arguments:
1.424     albertel 6804:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6805:    $scanline    - the scanline that caused the error
                   6806:    $errormesage - the error message
                   6807:    $errorcode   - a numeric code for the error
                   6808: 
                   6809:  Side Effects:
1.424     albertel 6810:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6811: 
                   6812: =cut
                   6813: 
1.82      albertel 6814: sub scantron_add_delay {
1.140     albertel 6815:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6816:     push(@$delayqueue,
                   6817: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6818: 	  'ecode' => $errorcode }
                   6819: 	 );
1.82      albertel 6820: }
                   6821: 
1.423     albertel 6822: =pod
                   6823: 
                   6824: =item scantron_find_student
                   6825: 
1.424     albertel 6826:    Finds the username for the current scanline
                   6827: 
                   6828:   Arguments:
                   6829:    $scantron_record - hash result from scantron_parse_scanline
                   6830:    $scan_data       - hash of correction information 
                   6831:                       (see &scantron_getfile() form more information)
                   6832:    $idmap           - hash from &username_to_idmap()
                   6833:    $line            - number of current scanline
                   6834:  
                   6835:   Returns:
                   6836:    Either 'username:domain' or undef if unknown
                   6837: 
1.423     albertel 6838: =cut
                   6839: 
1.82      albertel 6840: sub scantron_find_student {
1.157     albertel 6841:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6842:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6843:     if ($scanID =~ /^\s*$/) {
                   6844:  	return &scan_data($scan_data,"$line.user");
                   6845:     }
1.83      albertel 6846:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6847:  	if (lc($id) eq lc($scanID)) {
                   6848:  	    return $$idmap{$id};
                   6849:  	}
1.83      albertel 6850:     }
                   6851:     return undef;
                   6852: }
                   6853: 
1.423     albertel 6854: =pod
                   6855: 
                   6856: =item scantron_filter
                   6857: 
1.424     albertel 6858:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6859:    hidden resources was selected
                   6860: 
1.423     albertel 6861: =cut
                   6862: 
1.83      albertel 6863: sub scantron_filter {
                   6864:     my ($curres)=@_;
1.331     albertel 6865: 
                   6866:     if (ref($curres) && $curres->is_problem()) {
                   6867: 	# if the user has asked to not have either hidden
                   6868: 	# or 'randomout' controlled resources to be graded
                   6869: 	# don't include them
                   6870: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6871: 	    && $curres->randomout) {
                   6872: 	    return 0;
                   6873: 	}
1.83      albertel 6874: 	return 1;
                   6875:     }
                   6876:     return 0;
1.82      albertel 6877: }
                   6878: 
1.423     albertel 6879: =pod
                   6880: 
                   6881: =item scantron_process_corrections
                   6882: 
1.424     albertel 6883:    Gets correction information out of submitted form data and corrects
                   6884:    the scanline
                   6885: 
1.423     albertel 6886: =cut
                   6887: 
1.157     albertel 6888: sub scantron_process_corrections {
                   6889:     my ($r) = @_;
1.257     albertel 6890:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6891:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6892:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6893:     my $which=$env{'form.scantron_line'};
1.200     albertel 6894:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6895:     my ($skip,$err,$errmsg);
1.257     albertel 6896:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6897: 	$skip=1;
1.257     albertel 6898:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6899: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6900: 	    $env{'form.scantron_domain'};
1.157     albertel 6901: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6902: 	($line,$err,$errmsg)=
                   6903: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6904: 				     'ID',{'newid'=>$newid,
1.257     albertel 6905: 				    'username'=>$env{'form.scantron_username'},
                   6906: 				    'domain'=>$env{'form.scantron_domain'}});
                   6907:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6908: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6909: 	my $newCODE;
1.192     albertel 6910: 	my %args;
1.190     albertel 6911: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6912: 	    $newCODE='use_unfound';
1.190     albertel 6913: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6914: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6915: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6916: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6917: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6918: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6919: 	}
1.257     albertel 6920: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6921: 	    $args{'CODE_ignore_dup'}=1;
                   6922: 	}
                   6923: 	$args{'CODE'}=$newCODE;
1.186     albertel 6924: 	($line,$err,$errmsg)=
                   6925: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6926: 				     'CODE',\%args);
1.257     albertel 6927:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6928: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6929: 	    ($line,$err,$errmsg)=
                   6930: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6931: 					 $which,'answer',
                   6932: 					 { 'question'=>$question,
1.503     raeburn  6933: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6934:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6935: 	    if ($err) { last; }
                   6936: 	}
                   6937:     }
                   6938:     if ($err) {
1.703     bisitz   6939:         $r->print(
                   6940:             '<p class="LC_error">'
                   6941:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6942:                 $errmsg)
1.704     raeburn  6943:            .'</p>');
1.157     albertel 6944:     } else {
1.200     albertel 6945: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6946: 	&scantron_putfile($scanlines,$scan_data);
                   6947:     }
                   6948: }
                   6949: 
1.423     albertel 6950: =pod
                   6951: 
                   6952: =item reset_skipping_status
                   6953: 
1.424     albertel 6954:    Forgets the current set of remember skipped scanlines (and thus
                   6955:    reverts back to considering all lines in the
                   6956:    scantron_skipped_<filename> file)
                   6957: 
1.423     albertel 6958: =cut
                   6959: 
1.200     albertel 6960: sub reset_skipping_status {
                   6961:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6962:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6963:     &scantron_putfile(undef,$scan_data);
                   6964: }
                   6965: 
1.423     albertel 6966: =pod
                   6967: 
                   6968: =item start_skipping
                   6969: 
1.424     albertel 6970:    Marks a scanline to be skipped. 
                   6971: 
1.423     albertel 6972: =cut
                   6973: 
1.376     albertel 6974: sub start_skipping {
1.200     albertel 6975:     my ($scan_data,$i)=@_;
                   6976:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6977:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6978: 	$remembered{$i}=2;
                   6979:     } else {
                   6980: 	$remembered{$i}=1;
                   6981:     }
1.200     albertel 6982:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6983: }
                   6984: 
1.423     albertel 6985: =pod
                   6986: 
                   6987: =item should_be_skipped
                   6988: 
1.424     albertel 6989:    Checks whether a scanline should be skipped.
                   6990: 
1.423     albertel 6991: =cut
                   6992: 
1.200     albertel 6993: sub should_be_skipped {
1.376     albertel 6994:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6995:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6996: 	# not redoing old skips
1.376     albertel 6997: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6998: 	return 0;
                   6999:     }
                   7000:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7001: 
                   7002:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7003: 	return 0;
                   7004:     }
1.200     albertel 7005:     return 1;
                   7006: }
                   7007: 
1.423     albertel 7008: =pod
                   7009: 
                   7010: =item remember_current_skipped
                   7011: 
1.424     albertel 7012:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7013:    file and remembers them into scan_data for later use.
                   7014: 
1.423     albertel 7015: =cut
                   7016: 
1.200     albertel 7017: sub remember_current_skipped {
                   7018:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7019:     my %to_remember;
                   7020:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7021: 	if ($scanlines->{'skipped'}[$i]) {
                   7022: 	    $to_remember{$i}=1;
                   7023: 	}
                   7024:     }
1.376     albertel 7025: 
1.200     albertel 7026:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7027:     &scantron_putfile(undef,$scan_data);
                   7028: }
                   7029: 
1.423     albertel 7030: =pod
                   7031: 
                   7032: =item check_for_error
                   7033: 
1.424     albertel 7034:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7035:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7036:     something went wrong.
                   7037: 
1.423     albertel 7038: =cut
                   7039: 
1.200     albertel 7040: sub check_for_error {
                   7041:     my ($r,$result)=@_;
                   7042:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7043: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7044:     }
                   7045: }
1.157     albertel 7046: 
1.423     albertel 7047: =pod
                   7048: 
                   7049: =item scantron_warning_screen
                   7050: 
1.424     albertel 7051:    Interstitial screen to make sure the operator has selected the
                   7052:    correct options before we start the validation phase.
                   7053: 
1.423     albertel 7054: =cut
                   7055: 
1.203     albertel 7056: sub scantron_warning_screen {
1.650     raeburn  7057:     my ($button_text,$symb)=@_;
1.257     albertel 7058:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 7059:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7060:     my $CODElist;
1.284     albertel 7061:     if ($scantron_config{'CODElocation'} &&
                   7062: 	$scantron_config{'CODEstart'} &&
                   7063: 	$scantron_config{'CODElength'}) {
                   7064: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7065: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7066: 	$CODElist=
1.492     albertel 7067: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7068: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7069:     }
1.663     raeburn  7070:     my $lastbubblepoints;
                   7071:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7072:         $lastbubblepoints =
                   7073:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7074:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7075:     }
1.492     albertel 7076:     return ('
1.203     albertel 7077: <p>
1.492     albertel 7078: <span class="LC_warning">
1.705     raeburn  7079: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7080: </p>
                   7081: <table>
1.492     albertel 7082: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7083: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7084: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7085: </table>
1.680     raeburn  7086: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7087: '.&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 7088: 
                   7089: <br />
1.492     albertel 7090: ');
1.203     albertel 7091: }
                   7092: 
1.423     albertel 7093: =pod
                   7094: 
                   7095: =item scantron_do_warning
                   7096: 
1.424     albertel 7097:    Check if the operator has picked something for all required
                   7098:    fields. Error out if something is missing.
                   7099: 
1.423     albertel 7100: =cut
                   7101: 
1.203     albertel 7102: sub scantron_do_warning {
1.608     www      7103:     my ($r,$symb)=@_;
1.203     albertel 7104:     if (!$symb) {return '';}
1.324     albertel 7105:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7106:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7107:     if ( $env{'form.selectpage'} eq '' ||
                   7108: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7109: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7110: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7111: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7112: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7113: 	} 
1.257     albertel 7114: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7115: 	    $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 7116: 	} 
1.257     albertel 7117: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7118: 	    $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 7119: 	} 
                   7120:     } else {
1.650     raeburn  7121: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  7122:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7123: 	$r->print('
1.663     raeburn  7124: '.$warning.$bubbledbyhand.'
1.492     albertel 7125: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7126: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7127: ');
1.237     albertel 7128:     }
1.614     www      7129:     $r->print("</form><br />");
1.203     albertel 7130:     return '';
                   7131: }
                   7132: 
1.423     albertel 7133: =pod
                   7134: 
                   7135: =item scantron_form_start
                   7136: 
1.424     albertel 7137:     html hidden input for remembering all selected grading options
                   7138: 
1.423     albertel 7139: =cut
                   7140: 
1.203     albertel 7141: sub scantron_form_start {
                   7142:     my ($max_bubble)=@_;
                   7143:     my $result= <<SCANTRONFORM;
                   7144: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7145:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7146:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7147:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7148:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7149:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7150:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7151:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7152:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7153:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7154: SCANTRONFORM
1.447     foxr     7155: 
                   7156:   my $line = 0;
                   7157:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7158:        my $chunk =
                   7159: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7160:        $chunk .=
                   7161: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7162:        $chunk .= 
                   7163:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7164:        $chunk .=
                   7165:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7166:        $chunk .=
                   7167:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7168:        $result .= $chunk;
                   7169:        $line++;
1.691     raeburn  7170:     }
1.203     albertel 7171:     return $result;
                   7172: }
                   7173: 
1.423     albertel 7174: =pod
                   7175: 
                   7176: =item scantron_validate_file
                   7177: 
1.659     raeburn  7178:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7179: 
                   7180:     Also processes any necessary information resets that need to
                   7181:     occur before validation begins (ignore previous corrections,
                   7182:     restarting the skipped records processing)
                   7183: 
1.423     albertel 7184: =cut
                   7185: 
1.157     albertel 7186: sub scantron_validate_file {
1.608     www      7187:     my ($r,$symb) = @_;
1.157     albertel 7188:     if (!$symb) {return '';}
1.324     albertel 7189:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7190:     
1.703     bisitz   7191:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7192:     # them when doing the corrections reset
1.257     albertel 7193:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7194: 	&reset_skipping_status();
                   7195:     }
1.257     albertel 7196:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7197: 	&remember_current_skipped();
1.257     albertel 7198: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7199:     }
                   7200: 
1.257     albertel 7201:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7202: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7203: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7204: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7205: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7206:     }
1.200     albertel 7207: 
1.257     albertel 7208:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7209: 	&scantron_process_corrections($r);
                   7210:     }
1.503     raeburn  7211:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7212:     #get the student pick code ready
                   7213:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7214:     my $nav_error;
1.649     raeburn  7215:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   7216:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7217:     if ($nav_error) {
                   7218:         $r->print(&navmap_errormsg());
                   7219:         return '';
                   7220:     }
1.203     albertel 7221:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7222:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7223:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7224:     }
1.157     albertel 7225:     $r->print($result);
                   7226:     
1.334     albertel 7227:     my @validate_phases=( 'sequence',
                   7228: 			  'ID',
1.157     albertel 7229: 			  'CODE',
                   7230: 			  'doublebubble',
                   7231: 			  'missingbubbles');
1.257     albertel 7232:     if (!$env{'form.validatepass'}) {
                   7233: 	$env{'form.validatepass'} = 0;
1.157     albertel 7234:     }
1.257     albertel 7235:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7236: 
1.448     foxr     7237: 
1.157     albertel 7238:     my $stop=0;
                   7239:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7240: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7241: 	$r->rflush();
1.691     raeburn  7242:      
1.157     albertel 7243: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7244: 	{
                   7245: 	    no strict 'refs';
                   7246: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7247: 	}
                   7248:     }
                   7249:     if (!$stop) {
1.650     raeburn  7250: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7251: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7252:                   $warning.
                   7253:                   &mt('Perform verification for each student after storage of submissions?').
                   7254:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7255:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7256:                   ('&nbsp;'x3).'<label>'.
                   7257:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7258:                   '</label></span><br />'.
                   7259:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7260:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7261:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7262:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7263:     } else {
                   7264: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7265: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7266:     }
                   7267:     if ($stop) {
1.334     albertel 7268: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7269: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7270: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7271: 
1.650     raeburn  7272: 	    $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 7273: 	} else {
1.503     raeburn  7274:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7275: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7276:             } else {
1.539     riegler  7277:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7278:             }
1.492     albertel 7279: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7280: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7281: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7282: 	}
1.157     albertel 7283:     }
1.614     www      7284:     $r->print(" </form><br />");
1.157     albertel 7285:     return '';
                   7286: }
                   7287: 
1.423     albertel 7288: 
                   7289: =pod
                   7290: 
                   7291: =item scantron_remove_file
                   7292: 
1.659     raeburn  7293:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7294:    scantron_original_<filename> is never removed
                   7295: 
                   7296: 
1.423     albertel 7297: =cut
                   7298: 
1.200     albertel 7299: sub scantron_remove_file {
1.192     albertel 7300:     my ($which)=@_;
1.257     albertel 7301:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7302:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7303:     my $file='scantron_';
1.200     albertel 7304:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7305: 	$file.=$which.'_';
1.192     albertel 7306:     } else {
                   7307: 	return 'refused';
                   7308:     }
1.257     albertel 7309:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7310:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7311: }
                   7312: 
1.423     albertel 7313: 
                   7314: =pod
                   7315: 
                   7316: =item scantron_remove_scan_data
                   7317: 
1.659     raeburn  7318:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7319:    data file.  (In the case that both the are doing skipped records we need
                   7320:    to remember the old skipped lines for the time being so that element
                   7321:    persists for a while.)
                   7322: 
1.423     albertel 7323: =cut
                   7324: 
1.200     albertel 7325: sub scantron_remove_scan_data {
1.257     albertel 7326:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7327:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7328:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7329:     my @todelete;
1.257     albertel 7330:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7331:     foreach my $key (@keys) {
                   7332: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7333: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7334: 		$key=~/remember_skipping/) {
                   7335: 		next;
                   7336: 	    }
1.192     albertel 7337: 	    push(@todelete,$key);
                   7338: 	}
                   7339:     }
1.200     albertel 7340:     my $result;
1.192     albertel 7341:     if (@todelete) {
1.491     albertel 7342: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7343: 				       \@todelete,$cdom,$cname);
                   7344:     } else {
                   7345: 	$result = 'ok';
1.192     albertel 7346:     }
                   7347:     return $result;
                   7348: }
                   7349: 
1.423     albertel 7350: 
                   7351: =pod
                   7352: 
                   7353: =item scantron_getfile
                   7354: 
1.659     raeburn  7355:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7356:     the scan_data hash
                   7357:   
                   7358:   Arguments:
                   7359:     None
                   7360: 
                   7361:   Returns:
                   7362:     2 hash references
                   7363: 
                   7364:      - first one has 
                   7365:          orig      -
                   7366:          corrected -
                   7367:          skipped   -  each of which points to an array ref of the specified
                   7368:                       file broken up into individual lines
                   7369:          count     - number of scanlines
                   7370:  
                   7371:      - second is the scan_data hash possible keys are
1.425     albertel 7372:        ($number refers to scanline numbered $number and thus the key affects
                   7373:         only that scanline
                   7374:         $bubline refers to the specific bubble line element and the aspects
                   7375:         refers to that specific bubble line element)
                   7376: 
                   7377:        $number.user - username:domain to use
                   7378:        $number.CODE_ignore_dup 
                   7379:                     - ignore the duplicate CODE error 
                   7380:        $number.useCODE
                   7381:                     - use the CODE in the scanline as is
                   7382:        $number.no_bubble.$bubline
                   7383:                     - it is valid that there is no bubbled in bubble
                   7384:                       at $number $bubline
                   7385:        remember_skipping
                   7386:                     - a frozen hash containing keys of $number and values
                   7387:                       of either 
                   7388:                         1 - we are on a 'do skipped records pass' and plan
                   7389:                             on processing this line
                   7390:                         2 - we are on a 'do skipped records pass' and this
                   7391:                             scanline has been marked to skip yet again
1.424     albertel 7392: 
1.423     albertel 7393: =cut
                   7394: 
1.157     albertel 7395: sub scantron_getfile {
1.200     albertel 7396:     #FIXME really would prefer a scantron directory
1.257     albertel 7397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7399:     my $lines;
                   7400:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7401: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7402:     my %scanlines;
                   7403:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7404:     my $temp=$scanlines{'orig'};
                   7405:     $scanlines{'count'}=$#$temp;
                   7406: 
                   7407:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7408: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7409:     if ($lines eq '-1') {
                   7410: 	$scanlines{'corrected'}=[];
                   7411:     } else {
                   7412: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7413:     }
                   7414:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7415: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7416:     if ($lines eq '-1') {
                   7417: 	$scanlines{'skipped'}=[];
                   7418:     } else {
                   7419: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7420:     }
1.175     albertel 7421:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7422:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7423:     my %scan_data = @tmp;
                   7424:     return (\%scanlines,\%scan_data);
                   7425: }
                   7426: 
1.423     albertel 7427: =pod
                   7428: 
                   7429: =item lonnet_putfile
                   7430: 
1.424     albertel 7431:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7432: 
                   7433:  Arguments:
                   7434:    $contents - data to store
                   7435:    $filename - filename to store $contents into
                   7436: 
                   7437:  Returns:
                   7438:    result value from &Apache::lonnet::finishuserfileupload
                   7439: 
1.423     albertel 7440: =cut
                   7441: 
1.157     albertel 7442: sub lonnet_putfile {
                   7443:     my ($contents,$filename)=@_;
1.257     albertel 7444:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7445:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7446:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7447:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7448: 
                   7449: }
                   7450: 
1.423     albertel 7451: =pod
                   7452: 
                   7453: =item scantron_putfile
                   7454: 
1.659     raeburn  7455:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7456:     scan_data hash. (Does not modify the original version only the
                   7457:     corrected and skipped versions.
                   7458: 
                   7459:  Arguments:
                   7460:     $scanlines - hash ref that looks like the first return value from
                   7461:                  &scantron_getfile()
                   7462:     $scan_data - hash ref that looks like the second return value from
                   7463:                  &scantron_getfile()
                   7464: 
1.423     albertel 7465: =cut
                   7466: 
1.157     albertel 7467: sub scantron_putfile {
                   7468:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7469:     #FIXME really would prefer a scantron directory
1.257     albertel 7470:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7471:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7472:     if ($scanlines) {
                   7473: 	my $prefix='scantron_';
1.157     albertel 7474: # no need to update orig, shouldn't change
                   7475: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7476: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7477: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7478: 			$prefix.'corrected_'.
1.257     albertel 7479: 			$env{'form.scantron_selectfile'});
1.200     albertel 7480: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7481: 			$prefix.'skipped_'.
1.257     albertel 7482: 			$env{'form.scantron_selectfile'});
1.200     albertel 7483:     }
1.175     albertel 7484:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7485: }
                   7486: 
1.423     albertel 7487: =pod
                   7488: 
                   7489: =item scantron_get_line
                   7490: 
1.424     albertel 7491:    Returns the correct version of the scanline
                   7492: 
                   7493:  Arguments:
                   7494:     $scanlines - hash ref that looks like the first return value from
                   7495:                  &scantron_getfile()
                   7496:     $scan_data - hash ref that looks like the second return value from
                   7497:                  &scantron_getfile()
                   7498:     $i         - number of the requested line (starts at 0)
                   7499: 
                   7500:  Returns:
                   7501:    A scanline, (either the original or the corrected one if it
                   7502:    exists), or undef if the requested scanline should be
                   7503:    skipped. (Either because it's an skipped scanline, or it's an
                   7504:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7505:    pass.
                   7506: 
1.423     albertel 7507: =cut
                   7508: 
1.157     albertel 7509: sub scantron_get_line {
1.200     albertel 7510:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7511:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7512:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7513:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7514:     return $scanlines->{'orig'}[$i]; 
                   7515: }
                   7516: 
1.423     albertel 7517: =pod
                   7518: 
                   7519: =item scantron_todo_count
                   7520: 
1.424     albertel 7521:     Counts the number of scanlines that need processing.
                   7522: 
                   7523:  Arguments:
                   7524:     $scanlines - hash ref that looks like the first return value from
                   7525:                  &scantron_getfile()
                   7526:     $scan_data - hash ref that looks like the second return value from
                   7527:                  &scantron_getfile()
                   7528: 
                   7529:  Returns:
                   7530:     $count - number of scanlines to process
                   7531: 
1.423     albertel 7532: =cut
                   7533: 
1.200     albertel 7534: sub get_todo_count {
                   7535:     my ($scanlines,$scan_data)=@_;
                   7536:     my $count=0;
                   7537:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7538: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7539: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7540: 	$count++;
                   7541:     }
                   7542:     return $count;
                   7543: }
                   7544: 
1.423     albertel 7545: =pod
                   7546: 
                   7547: =item scantron_put_line
                   7548: 
1.659     raeburn  7549:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7550:     data file.
                   7551: 
                   7552:  Arguments:
                   7553:     $scanlines - hash ref that looks like the first return value from
                   7554:                  &scantron_getfile()
                   7555:     $scan_data - hash ref that looks like the second return value from
                   7556:                  &scantron_getfile()
                   7557:     $i         - line number to update
                   7558:     $newline   - contents of the updated scanline
                   7559:     $skip      - if true make the line for skipping and update the
                   7560:                  'skipped' file
                   7561: 
1.423     albertel 7562: =cut
                   7563: 
1.157     albertel 7564: sub scantron_put_line {
1.200     albertel 7565:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7566:     if ($skip) {
                   7567: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7568: 	&start_skipping($scan_data,$i);
1.157     albertel 7569: 	return;
                   7570:     }
                   7571:     $scanlines->{'corrected'}[$i]=$newline;
                   7572: }
                   7573: 
1.423     albertel 7574: =pod
                   7575: 
                   7576: =item scantron_clear_skip
                   7577: 
1.424     albertel 7578:    Remove a line from the 'skipped' file
                   7579: 
                   7580:  Arguments:
                   7581:     $scanlines - hash ref that looks like the first return value from
                   7582:                  &scantron_getfile()
                   7583:     $scan_data - hash ref that looks like the second return value from
                   7584:                  &scantron_getfile()
                   7585:     $i         - line number to update
                   7586: 
1.423     albertel 7587: =cut
                   7588: 
1.376     albertel 7589: sub scantron_clear_skip {
                   7590:     my ($scanlines,$scan_data,$i)=@_;
                   7591:     if (exists($scanlines->{'skipped'}[$i])) {
                   7592: 	undef($scanlines->{'skipped'}[$i]);
                   7593: 	return 1;
                   7594:     }
                   7595:     return 0;
                   7596: }
                   7597: 
1.423     albertel 7598: =pod
                   7599: 
                   7600: =item scantron_filter_not_exam
                   7601: 
1.424     albertel 7602:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7603:    filter out resources that are not marked as 'exam' mode
                   7604: 
1.423     albertel 7605: =cut
                   7606: 
1.334     albertel 7607: sub scantron_filter_not_exam {
                   7608:     my ($curres)=@_;
                   7609:     
                   7610:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7611: 	# if the user has asked to not have either hidden
                   7612: 	# or 'randomout' controlled resources to be graded
                   7613: 	# don't include them
                   7614: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7615: 	    && $curres->randomout) {
                   7616: 	    return 0;
                   7617: 	}
                   7618: 	return 1;
                   7619:     }
                   7620:     return 0;
                   7621: }
                   7622: 
1.423     albertel 7623: =pod
                   7624: 
                   7625: =item scantron_validate_sequence
                   7626: 
1.424     albertel 7627:     Validates the selected sequence, checking for resource that are
                   7628:     not set to exam mode.
                   7629: 
1.423     albertel 7630: =cut
                   7631: 
1.334     albertel 7632: sub scantron_validate_sequence {
                   7633:     my ($r,$currentphase) = @_;
                   7634: 
                   7635:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7636:     unless (ref($navmap)) {
                   7637:         $r->print(&navmap_errormsg());
                   7638:         return (1,$currentphase);
                   7639:     }
1.334     albertel 7640:     my (undef,undef,$sequence)=
                   7641: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7642: 
                   7643:     my $map=$navmap->getResourceByUrl($sequence);
                   7644: 
                   7645:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7646:                                     value="ignore" />');
                   7647:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7648: 	my @resources=
                   7649: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7650: 	if (@resources) {
1.675     bisitz   7651: 	    $r->print(
                   7652:                 '<p class="LC_warning">'
                   7653:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7654:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7655:                    .' work correctly.')
                   7656:                .'</p>'
                   7657:             );
1.334     albertel 7658: 	    return (1,$currentphase);
                   7659: 	}
                   7660:     }
                   7661: 
                   7662:     return (0,$currentphase+1);
                   7663: }
                   7664: 
1.423     albertel 7665: 
                   7666: 
1.157     albertel 7667: sub scantron_validate_ID {
                   7668:     my ($r,$currentphase) = @_;
                   7669:     
                   7670:     #get student info
                   7671:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7672:     my %idmap=&username_to_idmap($classlist);
                   7673: 
                   7674:     #get scantron line setup
1.257     albertel 7675:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7676:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7677: 
                   7678:     my $nav_error;
1.649     raeburn  7679:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7680:     if ($nav_error) {
                   7681:         $r->print(&navmap_errormsg());
                   7682:         return(1,$currentphase);
                   7683:     }
1.157     albertel 7684: 
                   7685:     my %found=('ids'=>{},'usernames'=>{});
                   7686:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7687: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7688: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7689: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7690: 						 $scan_data);
                   7691: 	my $id=$$scan_record{'scantron.ID'};
                   7692: 	my $found;
                   7693: 	foreach my $checkid (keys(%idmap)) {
                   7694: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7695: 	}
                   7696: 	if ($found) {
                   7697: 	    my $username=$idmap{$found};
                   7698: 	    if ($found{'ids'}{$found}) {
                   7699: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7700: 					 $line,'duplicateID',$found);
1.194     albertel 7701: 		return(1,$currentphase);
1.157     albertel 7702: 	    } elsif ($found{'usernames'}{$username}) {
                   7703: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7704: 					 $line,'duplicateID',$username);
1.194     albertel 7705: 		return(1,$currentphase);
1.157     albertel 7706: 	    }
1.186     albertel 7707: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7708: 	    $found{'ids'}{$found}++;
                   7709: 	    $found{'usernames'}{$username}++;
                   7710: 	} else {
                   7711: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7712: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7713: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7714: 		    &scantron_get_correction($r,$i,$scan_record,
                   7715: 					     \%scantron_config,
                   7716: 					     $line,'duplicateID',$username);
1.194     albertel 7717: 		    return(1,$currentphase);
1.157     albertel 7718: 		} elsif (!defined($username)) {
                   7719: 		    &scantron_get_correction($r,$i,$scan_record,
                   7720: 					     \%scantron_config,
                   7721: 					     $line,'incorrectID');
1.194     albertel 7722: 		    return(1,$currentphase);
1.157     albertel 7723: 		}
                   7724: 		$found{'usernames'}{$username}++;
                   7725: 	    } else {
                   7726: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7727: 					 $line,'incorrectID');
1.194     albertel 7728: 		return(1,$currentphase);
1.157     albertel 7729: 	    }
                   7730: 	}
                   7731:     }
                   7732: 
                   7733:     return (0,$currentphase+1);
                   7734: }
                   7735: 
1.423     albertel 7736: 
1.157     albertel 7737: sub scantron_get_correction {
1.691     raeburn  7738:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7739:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7740: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7741: #to show both the current line and the previous one and allow skipping
                   7742: #the previous one or the current one
                   7743: 
1.333     albertel 7744:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7745:         $r->print(
                   7746:             '<p class="LC_warning">'
                   7747:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7748:                 "<b>$error</b>",
                   7749:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7750:            ."</p> \n");
1.157     albertel 7751:     } else {
1.658     bisitz   7752:         $r->print(
                   7753:             '<p class="LC_warning">'
                   7754:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7755:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7756:            ."</p> \n");
                   7757:     }
                   7758:     my $message =
                   7759:         '<p>'
                   7760:        .&mt('The ID on the form is [_1]',
                   7761:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7762:        .'<br />'
1.665     raeburn  7763:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7764:             $$scan_record{'scantron.LastName'},
                   7765:             $$scan_record{'scantron.FirstName'})
                   7766:        .'</p>';
1.242     albertel 7767: 
1.157     albertel 7768:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7769:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7770:                            # Array populated for doublebubble or
                   7771:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7772:                            # to validate radio button checking   
                   7773: 
1.157     albertel 7774:     if ($error =~ /ID$/) {
1.186     albertel 7775: 	if ($error eq 'incorrectID') {
1.658     bisitz   7776:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7777: 		      "</p>\n");
1.157     albertel 7778: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7779:             $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 7780: 	}
1.242     albertel 7781: 	$r->print($message);
1.492     albertel 7782: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7783: 	$r->print("\n<ul><li> ");
                   7784: 	#FIXME it would be nice if this sent back the user ID and
                   7785: 	#could do partial userID matches
                   7786: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7787: 				       'scantron_username','scantron_domain'));
                   7788: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7789: 	$r->print("\n:\n".
1.257     albertel 7790: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7791: 
                   7792: 	$r->print('</li>');
1.186     albertel 7793:     } elsif ($error =~ /CODE$/) {
                   7794: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7795: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7796: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7797: 	    $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 7798: 	}
1.658     bisitz   7799: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7800: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7801:                  ."</p>\n");
1.242     albertel 7802: 	$r->print($message);
1.658     bisitz   7803: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7804: 	$r->print("\n<br /> ");
1.194     albertel 7805: 	my $i=0;
1.273     albertel 7806: 	if ($error eq 'incorrectCODE' 
                   7807: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7808: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7809: 	    if ($closest > 0) {
                   7810: 		foreach my $testcode (@{$closest}) {
                   7811: 		    my $checked='';
1.569     bisitz   7812: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7813: 		    $r->print("
                   7814:    <label>
1.569     bisitz   7815:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7816:        ".&mt("Use the similar CODE [_1] instead.",
                   7817: 	    "<b><tt>".$testcode."</tt></b>")."
                   7818:     </label>
                   7819:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7820: 		    $r->print("\n<br />");
                   7821: 		    $i++;
                   7822: 		}
1.194     albertel 7823: 	    }
                   7824: 	}
1.273     albertel 7825: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7826: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7827: 	    $r->print("
                   7828:     <label>
1.569     bisitz   7829:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7830:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7831: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7832:     </label>");
1.273     albertel 7833: 	    $r->print("\n<br />");
                   7834: 	}
1.194     albertel 7835: 
1.597     wenzelju 7836: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7837: function change_radio(field) {
1.190     albertel 7838:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7839:     var i;
                   7840:     for (i=0;i<slct.length;i++) {
                   7841:         if (slct[i].value==field) { slct[i].checked=true; }
                   7842:     }
                   7843: }
                   7844: ENDSCRIPT
1.187     albertel 7845: 	my $href="/adm/pickcode?".
1.359     www      7846: 	   "form=".&escape("scantronupload").
                   7847: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7848: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7849: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7850: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7851: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7852: 	    $r->print("
                   7853:     <label>
                   7854:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7855:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7856: 	     "<a target='_blank' href='$href'>","</a>")."
                   7857:     </label> 
1.558     bisitz   7858:     ".&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 7859: 	    $r->print("\n<br />");
                   7860: 	}
1.492     albertel 7861: 	$r->print("
                   7862:     <label>
                   7863:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7864:        ".&mt("Use [_1] as the CODE.",
                   7865: 	     "</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 7866: 	$r->print("\n<br /><br />");
1.157     albertel 7867:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7868: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7869: 
                   7870: 	# The form field scantron_questions is acutally a list of line numbers.
                   7871: 	# represented by this form so:
                   7872: 
1.691     raeburn  7873: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7874:                                                 $respnumlookup,$startline);
1.497     foxr     7875: 
1.157     albertel 7876: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7877: 		  $line_list.'" />');
1.242     albertel 7878: 	$r->print($message);
1.492     albertel 7879: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7880: 	foreach my $question (@{$arg}) {
1.503     raeburn  7881: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7882:                                                    $scan_record, $error,
                   7883:                                                    $randomorder,$randompick,
                   7884:                                                    $respnumlookup,$startline);
1.524     raeburn  7885:             push(@lines_to_correct,@linenums);
1.157     albertel 7886: 	}
1.503     raeburn  7887:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7888:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7889: 	$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 7890: 	$r->print($message);
1.492     albertel 7891: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7892: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7893: 
1.503     raeburn  7894: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7895: 	# a list of question numbers. Therefore:
                   7896: 	#
1.691     raeburn  7897: 
                   7898: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7899:                                                 $respnumlookup,$startline);
1.497     foxr     7900: 
1.157     albertel 7901: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7902: 		  $line_list.'" />');
1.157     albertel 7903: 	foreach my $question (@{$arg}) {
1.503     raeburn  7904: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7905:                                                    $scan_record, $error,
                   7906:                                                    $randomorder,$randompick,
                   7907:                                                    $respnumlookup,$startline);
1.524     raeburn  7908:             push(@lines_to_correct,@linenums);
1.157     albertel 7909: 	}
1.503     raeburn  7910:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7911:     } else {
                   7912: 	$r->print("\n<ul>");
                   7913:     }
                   7914:     $r->print("\n</li></ul>");
1.497     foxr     7915: }
                   7916: 
1.503     raeburn  7917: sub verify_bubbles_checked {
                   7918:     my (@ansnums) = @_;
                   7919:     my $ansnumstr = join('","',@ansnums);
                   7920:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7921:     &js_escape(\$warning);
1.597     wenzelju 7922:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7923: function verify_bubble_radio(form) {
                   7924:     var ansnumArray = new Array ("$ansnumstr");
                   7925:     var need_bubble_count = 0;
                   7926:     for (var i=0; i<ansnumArray.length; i++) {
                   7927:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7928:             var bubble_picked = 0; 
                   7929:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7930:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7931:                     bubble_picked = 1;
                   7932:                 }
                   7933:             }
                   7934:             if (bubble_picked == 0) {
                   7935:                 need_bubble_count ++;
                   7936:             }
                   7937:         }
                   7938:     }
                   7939:     if (need_bubble_count) {
                   7940:         alert("$warning");
                   7941:         return;
                   7942:     }
                   7943:     form.submit(); 
                   7944: }
                   7945: ENDSCRIPT
                   7946:     return $output;
                   7947: }
                   7948: 
1.497     foxr     7949: =pod
                   7950: 
                   7951: =item  questions_to_line_list
1.157     albertel 7952: 
1.497     foxr     7953: Converts a list of questions into a string of comma separated
                   7954: line numbers in the answer sheet used by the questions.  This is
                   7955: used to fill in the scantron_questions form field.
                   7956: 
                   7957:   Arguments:
                   7958:      questions    - Reference to an array of questions.
1.691     raeburn  7959:      randomorder  - True if randomorder in use.
                   7960:      randompick   - True if randompick in use.
                   7961:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7962:                      for current line to question number used for same question
                   7963:                      in "Master Seqence" (as seen by Course Coordinator).
                   7964:      startline    - Reference to hash where key is question number (0 is first)
                   7965:                     and key is number of first bubble line for current student
                   7966:                     or code-based randompick and/or randomorder.
1.693     raeburn  7967: 
1.497     foxr     7968: =cut
                   7969: 
                   7970: 
                   7971: sub questions_to_line_list {
1.691     raeburn  7972:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7973:     my @lines;
                   7974: 
1.503     raeburn  7975:     foreach my $item (@{$questions}) {
                   7976:         my $question = $item;
                   7977:         my ($first,$count,$last);
                   7978:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7979:             $question = $1;
                   7980:             my $subquestion = $2;
1.691     raeburn  7981:             my $responsenum = $question-1;
                   7982:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7983:                 $responsenum = $respnumlookup->{$question-1};
                   7984:                 if (ref($startline) eq 'HASH') {
                   7985:                     $first = $startline->{$question-1} + 1;
                   7986:                 }
                   7987:             } else {
                   7988:                 $first = $first_bubble_line{$responsenum} + 1;
                   7989:             }
                   7990:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7991:             my $subcount = 1;
                   7992:             while ($subcount<$subquestion) {
                   7993:                 $first += $subans[$subcount-1];
                   7994:                 $subcount ++;
                   7995:             }
                   7996:             $count = $subans[$subquestion-1];
                   7997:         } else {
1.691     raeburn  7998:             my $responsenum = $question-1;
                   7999:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8000:                 $responsenum = $respnumlookup->{$question-1};
                   8001:                 if (ref($startline) eq 'HASH') {
                   8002:                     $first = $startline->{$question-1} + 1;
                   8003:                 }
                   8004:             } else {
                   8005:                 $first = $first_bubble_line{$responsenum} + 1;
                   8006:             }
                   8007: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8008:         }
1.506     raeburn  8009:         $last = $first+$count-1;
1.503     raeburn  8010:         push(@lines, ($first..$last));
1.497     foxr     8011:     }
                   8012:     return join(',', @lines);
                   8013: }
                   8014: 
                   8015: =pod 
                   8016: 
                   8017: =item prompt_for_corrections
                   8018: 
                   8019: Prompts for a potentially multiline correction to the
                   8020: user's bubbling (factors out common code from scantron_get_correction
                   8021: for multi and missing bubble cases).
                   8022: 
                   8023:  Arguments:
                   8024:    $r           - Apache request object.
                   8025:    $question    - The question number to prompt for.
                   8026:    $scan_config - The scantron file configuration hash.
                   8027:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8028:    $error       - Type of error
1.691     raeburn  8029:    $randomorder - True if randomorder in use.
                   8030:    $randompick  - True if randompick in use.
                   8031:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8032:                     for current line to question number used for same question
                   8033:                     in "Master Seqence" (as seen by Course Coordinator).
                   8034:    $startline   - Reference to hash where key is question number (0 is first)
                   8035:                   and value is number of first bubble line for current student
                   8036:                   or code-based randompick and/or randomorder.
                   8037: 
1.497     foxr     8038: 
                   8039:  Implicit inputs:
                   8040:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8041:                                   Numbered from 0 (but question numbers are from
                   8042:                                   1.
                   8043:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8044:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8045:                                   type problems render as separate sub-questions, 
1.503     raeburn  8046:                                   in exam mode. This hash contains a 
                   8047:                                   comma-separated list of the lines per 
                   8048:                                   sub-question.
1.510     raeburn  8049:    %responsetype_per_response   - essayresponse, formularesponse,
                   8050:                                   stringresponse, imageresponse, reactionresponse,
                   8051:                                   and organicresponse type problem parts can have
1.503     raeburn  8052:                                   multiple lines per response if the weight
                   8053:                                   assigned exceeds 10.  In this case, only
                   8054:                                   one bubble per line is permitted, but more 
                   8055:                                   than one line might contain bubbles, e.g.
                   8056:                                   bubbling of: line 1 - J, line 2 - J, 
                   8057:                                   line 3 - B would assign 22 points.  
1.497     foxr     8058: 
                   8059: =cut
                   8060: 
                   8061: sub prompt_for_corrections {
1.691     raeburn  8062:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8063:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8064:     my ($current_line,$lines);
                   8065:     my @linenums;
                   8066:     my $questionnum = $question;
1.691     raeburn  8067:     my ($first,$responsenum);
1.503     raeburn  8068:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8069:         $question = $1;
                   8070:         my $subquestion = $2;
1.691     raeburn  8071:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8072:             $responsenum = $respnumlookup->{$question-1};
                   8073:             if (ref($startline) eq 'HASH') {
                   8074:                 $first = $startline->{$question-1};
                   8075:             }
                   8076:         } else {
                   8077:             $responsenum = $question-1;
1.714     raeburn  8078:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8079:         }
                   8080:         $current_line = $first + 1 ;
                   8081:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8082:         my $subcount = 1;
                   8083:         while ($subcount<$subquestion) {
                   8084:             $current_line += $subans[$subcount-1];
                   8085:             $subcount ++;
                   8086:         }
                   8087:         $lines = $subans[$subquestion-1];
                   8088:     } else {
1.691     raeburn  8089:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8090:             $responsenum = $respnumlookup->{$question-1};
                   8091:             if (ref($startline) eq 'HASH') { 
                   8092:                 $first = $startline->{$question-1};
                   8093:             }
                   8094:         } else {
                   8095:             $responsenum = $question-1;
                   8096:             $first = $first_bubble_line{$responsenum};
                   8097:         }
                   8098:         $current_line = $first + 1;
                   8099:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8100:     }
1.497     foxr     8101:     if ($lines > 1) {
1.503     raeburn  8102:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8103:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8104:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8105:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8106:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8107:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8108:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8109:             $r->print(
                   8110:                 &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)
                   8111:                .'<br /><br />'
                   8112:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8113:                .'<br />'
                   8114:                .&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.')
                   8115:                .'<br />'
                   8116:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8117:                .'<br /><br />'
                   8118:             );
1.503     raeburn  8119:         } else {
                   8120:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8121:         }
1.497     foxr     8122:     }
                   8123:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8124:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8125: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8126: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8127:         push(@linenums,$current_line);
1.497     foxr     8128: 	$current_line++;
                   8129:     }
                   8130:     if ($lines > 1) {
                   8131: 	$r->print("<hr /><br />");
                   8132:     }
1.503     raeburn  8133:     return @linenums;
1.157     albertel 8134: }
1.423     albertel 8135: 
                   8136: =pod
                   8137: 
                   8138: =item scantron_bubble_selector
                   8139:   
                   8140:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8141:    possibly showing the existing the selected bubbles if known
1.423     albertel 8142: 
                   8143:  Arguments:
                   8144:     $r           - Apache request object
                   8145:     $scan_config - hash from &get_scantron_config()
1.497     foxr     8146:     $line        - Number of the line being displayed.
1.503     raeburn  8147:     $questionnum - Question number (may include subquestion)
                   8148:     $error       - Type of error.
1.497     foxr     8149:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8150: 
                   8151: =cut
                   8152: 
1.157     albertel 8153: sub scantron_bubble_selector {
1.503     raeburn  8154:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8155:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8156: 
                   8157:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8158:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8159:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8160:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8161:             $max=$$scan_config{'BubblesPerRow'};
                   8162:             if (($scmode eq 'number') && ($max > 10)) {
                   8163:                 $max = 10;
                   8164:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8165:                 $max = 26;
                   8166:             }
                   8167:         } else {
                   8168:             $max = 10;
                   8169:         }
                   8170:     }
1.274     albertel 8171: 
1.157     albertel 8172:     my @alphabet=('A'..'Z');
1.503     raeburn  8173:     $r->print(&Apache::loncommon::start_data_table().
                   8174:               &Apache::loncommon::start_data_table_row());
                   8175:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8176:     for (my $i=0;$i<$max+1;$i++) {
                   8177: 	$r->print("\n".'<td align="center">');
                   8178: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8179: 	else { $r->print('&nbsp;'); }
                   8180: 	$r->print('</td>');
                   8181:     }
1.503     raeburn  8182:     $r->print(&Apache::loncommon::end_data_table_row().
                   8183:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8184:     for (my $i=0;$i<$max;$i++) {
                   8185: 	$r->print("\n".
                   8186: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8187: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8188:     }
1.503     raeburn  8189:     my $nobub_checked = ' ';
                   8190:     if ($error eq 'missingbubble') {
                   8191:         $nobub_checked = ' checked = "checked" ';
                   8192:     }
                   8193:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8194: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8195:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8196:               $line.'" value="'.$questionnum.'" /></td>');
                   8197:     $r->print(&Apache::loncommon::end_data_table_row().
                   8198:               &Apache::loncommon::end_data_table());
1.157     albertel 8199: }
                   8200: 
1.423     albertel 8201: =pod
                   8202: 
                   8203: =item num_matches
                   8204: 
1.424     albertel 8205:    Counts the number of characters that are the same between the two arguments.
                   8206: 
                   8207:  Arguments:
                   8208:    $orig - CODE from the scanline
                   8209:    $code - CODE to match against
                   8210: 
                   8211:  Returns:
                   8212:    $count - integer count of the number of same characters between the
                   8213:             two arguments
                   8214: 
1.423     albertel 8215: =cut
                   8216: 
1.194     albertel 8217: sub num_matches {
                   8218:     my ($orig,$code) = @_;
                   8219:     my @code=split(//,$code);
                   8220:     my @orig=split(//,$orig);
                   8221:     my $same=0;
                   8222:     for (my $i=0;$i<scalar(@code);$i++) {
                   8223: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8224:     }
                   8225:     return $same;
                   8226: }
                   8227: 
1.423     albertel 8228: =pod
                   8229: 
                   8230: =item scantron_get_closely_matching_CODEs
                   8231: 
1.424     albertel 8232:    Cycles through all CODEs and finds the set that has the greatest
                   8233:    number of same characters as the provided CODE
                   8234: 
                   8235:  Arguments:
                   8236:    $allcodes - hash ref returned by &get_codes()
                   8237:    $CODE     - CODE from the current scanline
                   8238: 
                   8239:  Returns:
                   8240:    2 element list
                   8241:     - first elements is number of how closely matching the best fit is 
                   8242:       (5 means best set has 5 matching characters)
                   8243:     - second element is an arrary ref containing the set of valid CODEs
                   8244:       that best fit the passed in CODE
                   8245: 
1.423     albertel 8246: =cut
                   8247: 
1.194     albertel 8248: sub scantron_get_closely_matching_CODEs {
                   8249:     my ($allcodes,$CODE)=@_;
                   8250:     my @CODEs;
                   8251:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8252: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8253:     }
                   8254: 
                   8255:     return ($#CODEs,$CODEs[-1]);
                   8256: }
                   8257: 
1.423     albertel 8258: =pod
                   8259: 
                   8260: =item get_codes
                   8261: 
1.424     albertel 8262:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8263:    set of remembered CODEs.
                   8264: 
                   8265:  Arguments:
                   8266:   $old_name - name of the set of remembered CODEs
                   8267:   $cdom     - domain of the course
                   8268:   $cnum     - internal course name
                   8269: 
                   8270:  Returns:
                   8271:   %allcodes - keys are the valid CODEs, values are all 1
                   8272: 
1.423     albertel 8273: =cut
                   8274: 
1.194     albertel 8275: sub get_codes {
1.280     foxr     8276:     my ($old_name, $cdom, $cnum) = @_;
                   8277:     if (!$old_name) {
                   8278: 	$old_name=$env{'form.scantron_CODElist'};
                   8279:     }
                   8280:     if (!$cdom) {
                   8281: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8282:     }
                   8283:     if (!$cnum) {
                   8284: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8285:     }
1.278     albertel 8286:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8287: 				    $cdom,$cnum);
                   8288:     my %allcodes;
                   8289:     if ($result{"type\0$old_name"} eq 'number') {
                   8290: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8291:     } else {
                   8292: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8293:     }
1.194     albertel 8294:     return %allcodes;
                   8295: }
                   8296: 
1.423     albertel 8297: =pod
                   8298: 
                   8299: =item scantron_validate_CODE
                   8300: 
1.424     albertel 8301:    Validates all scanlines in the selected file to not have any
                   8302:    invalid or underspecified CODEs and that none of the codes are
                   8303:    duplicated if this was requested.
                   8304: 
1.423     albertel 8305: =cut
                   8306: 
1.157     albertel 8307: sub scantron_validate_CODE {
                   8308:     my ($r,$currentphase) = @_;
1.257     albertel 8309:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8310:     if ($scantron_config{'CODElocation'} &&
                   8311: 	$scantron_config{'CODEstart'} &&
                   8312: 	$scantron_config{'CODElength'}) {
1.257     albertel 8313: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8314: 	    &FIXME_blow_up()
                   8315: 	}
                   8316:     } else {
                   8317: 	return (0,$currentphase+1);
                   8318:     }
                   8319:     
                   8320:     my %usedCODEs;
                   8321: 
1.194     albertel 8322:     my %allcodes=&get_codes();
1.186     albertel 8323: 
1.582     raeburn  8324:     my $nav_error;
1.649     raeburn  8325:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8326:     if ($nav_error) {
                   8327:         $r->print(&navmap_errormsg());
                   8328:         return(1,$currentphase);
                   8329:     }
1.447     foxr     8330: 
1.186     albertel 8331:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8332:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8333: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8334: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8335: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8336: 						 $scan_data);
                   8337: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8338: 	my $error=0;
1.224     albertel 8339: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8340: 	    &scantron_get_correction($r,$i,$scan_record,
                   8341: 				     \%scantron_config,
                   8342: 				     $line,'incorrectCODE',\%allcodes);
                   8343: 	    return(1,$currentphase);
                   8344: 	}
1.221     albertel 8345: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8346: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8347: 	    &scantron_get_correction($r,$i,$scan_record,
                   8348: 				     \%scantron_config,
1.194     albertel 8349: 				     $line,'incorrectCODE',\%allcodes);
                   8350: 	    return(1,$currentphase);
1.186     albertel 8351: 	}
1.214     albertel 8352: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8353: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8354: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8355: 	    &scantron_get_correction($r,$i,$scan_record,
                   8356: 				     \%scantron_config,
1.194     albertel 8357: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8358: 	    return(1,$currentphase);
1.186     albertel 8359: 	}
1.524     raeburn  8360: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8361:     }
1.157     albertel 8362:     return (0,$currentphase+1);
                   8363: }
                   8364: 
1.423     albertel 8365: =pod
                   8366: 
                   8367: =item scantron_validate_doublebubble
                   8368: 
1.424     albertel 8369:    Validates all scanlines in the selected file to not have any
                   8370:    bubble lines with multiple bubbles marked.
                   8371: 
1.423     albertel 8372: =cut
                   8373: 
1.157     albertel 8374: sub scantron_validate_doublebubble {
                   8375:     my ($r,$currentphase) = @_;
                   8376:     #get student info
                   8377:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8378:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8379:     my (undef,undef,$sequence)=
                   8380:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8381: 
                   8382:     #get scantron line setup
1.257     albertel 8383:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8384:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8385: 
                   8386:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8387:     unless (ref($navmap)) {
                   8388:         $r->print(&navmap_errormsg());
                   8389:         return(1,$currentphase);
                   8390:     }
                   8391:     my $map=$navmap->getResourceByUrl($sequence);
                   8392:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8393:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8394:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8395:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8396: 
1.583     raeburn  8397:     my $nav_error;
1.691     raeburn  8398:     if (ref($map)) {
                   8399:         $randomorder = $map->randomorder();
                   8400:         $randompick = $map->randompick();
                   8401:         if ($randomorder || $randompick) {
                   8402:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8403:             if ($nav_error) {
                   8404:                 $r->print(&navmap_errormsg());
                   8405:                 return(1,$currentphase);
                   8406:             }
                   8407:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8408:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8409:         }
                   8410:     } else {
                   8411:         $r->print(&navmap_errormsg());
                   8412:         return(1,$currentphase);
                   8413:     }
                   8414: 
1.649     raeburn  8415:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8416:     if ($nav_error) {
                   8417:         $r->print(&navmap_errormsg());
                   8418:         return(1,$currentphase);
                   8419:     }
1.447     foxr     8420: 
1.157     albertel 8421:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8422: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8423: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8424: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8425: 						 $scan_data,undef,\%idmap,$randomorder,
                   8426:                                                  $randompick,$sequence,\@master_seq,
                   8427:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8428:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8429: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8430: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8431: 				 'doublebubble',
1.691     raeburn  8432: 				 $$scan_record{'scantron.doubleerror'},
                   8433:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8434:     	return (1,$currentphase);
                   8435:     }
                   8436:     return (0,$currentphase+1);
                   8437: }
                   8438: 
1.423     albertel 8439: 
1.503     raeburn  8440: sub scantron_get_maxbubble {
1.649     raeburn  8441:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8442:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8443: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8444: 	&restore_bubble_lines();
1.257     albertel 8445: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8446:     }
1.330     albertel 8447: 
1.447     foxr     8448:     my (undef, undef, $sequence) =
1.257     albertel 8449: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8450: 
1.447     foxr     8451:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8452:     unless (ref($navmap)) {
                   8453:         if (ref($nav_error)) {
                   8454:             $$nav_error = 1;
                   8455:         }
1.591     raeburn  8456:         return;
1.582     raeburn  8457:     }
1.191     albertel 8458:     my $map=$navmap->getResourceByUrl($sequence);
                   8459:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8460:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8461: 
                   8462:     &Apache::lonxml::clear_problem_counter();
                   8463: 
1.557     raeburn  8464:     my $uname       = $env{'user.name'};
                   8465:     my $udom        = $env{'user.domain'};
1.435     foxr     8466:     my $cid         = $env{'request.course.id'};
                   8467:     my $total_lines = 0;
                   8468:     %bubble_lines_per_response = ();
1.447     foxr     8469:     %first_bubble_line         = ();
1.503     raeburn  8470:     %subdivided_bubble_lines   = ();
                   8471:     %responsetype_per_response = ();
1.691     raeburn  8472:     %masterseq_id_responsenum  = ();
1.554     raeburn  8473: 
1.447     foxr     8474:     my $response_number = 0;
                   8475:     my $bubble_line     = 0;
1.191     albertel 8476:     foreach my $resource (@resources) {
1.691     raeburn  8477:         my $resid = $resource->id(); 
1.672     raeburn  8478:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8479:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8480:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8481: 	    foreach my $part_id (@{$parts}) {
                   8482:                 my $lines;
                   8483: 
                   8484: 	        # TODO - make this a persistent hash not an array.
                   8485: 
                   8486:                 # optionresponse, matchresponse and rankresponse type items 
                   8487:                 # render as separate sub-questions in exam mode.
                   8488:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8489:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8490:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8491:                     my ($numbub,$numshown);
                   8492:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8493:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8494:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8495:                         }
                   8496:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8497:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8498:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8499:                         }
                   8500:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8501:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8502:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8503:                         }
                   8504:                     }
                   8505:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8506:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8507:                     }
1.649     raeburn  8508:                     my $bubbles_per_row =
                   8509:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8510:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8511:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8512:                         $inner_bubble_lines++;
                   8513:                     }
                   8514:                     for (my $i=0; $i<$numshown; $i++) {
                   8515:                         $subdivided_bubble_lines{$response_number} .= 
                   8516:                             $inner_bubble_lines.',';
                   8517:                     }
                   8518:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8519:                     $lines = $numshown * $inner_bubble_lines;
                   8520:                 } else {
                   8521:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8522:                 }
1.542     raeburn  8523: 
                   8524:                 $first_bubble_line{$response_number} = $bubble_line;
                   8525: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8526:                 $responsetype_per_response{$response_number} = 
                   8527:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8528:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8529: 	        $response_number++;
                   8530: 
                   8531: 	        $bubble_line +=  $lines;
                   8532: 	        $total_lines +=  $lines;
                   8533: 	    }
                   8534:         }
                   8535:     }
1.552     raeburn  8536:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8537: 
                   8538:     &save_bubble_lines();
                   8539:     $env{'form.scantron_maxbubble'} =
                   8540: 	$total_lines;
                   8541:     return $env{'form.scantron_maxbubble'};
                   8542: }
1.523     raeburn  8543: 
1.649     raeburn  8544: sub bubblesheet_bubbles_per_row {
                   8545:     my ($scantron_config) = @_;
                   8546:     my $bubbles_per_row;
                   8547:     if (ref($scantron_config) eq 'HASH') {
                   8548:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8549:     }
                   8550:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8551:         $bubbles_per_row = 10;
                   8552:     }
                   8553:     return $bubbles_per_row;
                   8554: }
                   8555: 
1.157     albertel 8556: sub scantron_validate_missingbubbles {
                   8557:     my ($r,$currentphase) = @_;
                   8558:     #get student info
                   8559:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8560:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8561:     my (undef,undef,$sequence)=
                   8562:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8563: 
                   8564:     #get scantron line setup
1.257     albertel 8565:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8566:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8567: 
                   8568:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8569:     unless (ref($navmap)) {
                   8570:         $r->print(&navmap_errormsg());
                   8571:         return(1,$currentphase);
                   8572:     }
                   8573: 
                   8574:     my $map=$navmap->getResourceByUrl($sequence);
                   8575:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8576:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8577:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8578:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8579: 
1.582     raeburn  8580:     my $nav_error;
1.691     raeburn  8581:     if (ref($map)) {
                   8582:         $randomorder = $map->randomorder();
                   8583:         $randompick = $map->randompick();
                   8584:         if ($randomorder || $randompick) {
                   8585:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8586:             if ($nav_error) {
                   8587:                 $r->print(&navmap_errormsg());
                   8588:                 return(1,$currentphase);
                   8589:             }
                   8590:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8591:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8592:         }
                   8593:     } else {
                   8594:         $r->print(&navmap_errormsg());
                   8595:         return(1,$currentphase);
                   8596:     }
                   8597: 
                   8598: 
1.649     raeburn  8599:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8600:     if ($nav_error) {
1.691     raeburn  8601:         $r->print(&navmap_errormsg());
1.693     raeburn  8602:         return(1,$currentphase);
1.582     raeburn  8603:     }
1.691     raeburn  8604: 
1.157     albertel 8605:     if (!$max_bubble) { $max_bubble=2**31; }
                   8606:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8607: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8608: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8609: 	my $scan_record =
                   8610:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8611: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8612:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8613:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8614: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8615: 	my @to_correct;
1.470     foxr     8616: 	
                   8617: 	# Probably here's where the error is...
                   8618: 
1.157     albertel 8619: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8620:             my $lastbubble;
                   8621:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8622:                my $question = $1;
                   8623:                my $subquestion = $2;
1.691     raeburn  8624:                my ($first,$responsenum);
                   8625:                if ($randomorder || $randompick) {
                   8626:                    $responsenum = $respnumlookup{$question-1};
                   8627:                    $first = $startline{$question-1};
                   8628:                } else {
                   8629:                    $responsenum = $question-1; 
                   8630:                    $first = $first_bubble_line{$responsenum};
                   8631:                }
                   8632:                if (!defined($first)) { next; }
                   8633:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8634:                my $subcount = 1;
                   8635:                while ($subcount<$subquestion) {
                   8636:                    $first += $subans[$subcount-1];
                   8637:                    $subcount ++;
                   8638:                }
                   8639:                my $count = $subans[$subquestion-1];
                   8640:                $lastbubble = $first + $count;
                   8641:             } else {
1.691     raeburn  8642:                my ($first,$responsenum);
                   8643:                if ($randomorder || $randompick) {
                   8644:                    $responsenum = $respnumlookup{$missing-1};
                   8645:                    $first = $startline{$missing-1};
                   8646:                } else {
                   8647:                    $responsenum = $missing-1;
                   8648:                    $first = $first_bubble_line{$responsenum};
                   8649:                }
                   8650:                if (!defined($first)) { next; }
                   8651:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8652:             }
                   8653:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8654: 	    push(@to_correct,$missing);
                   8655: 	}
                   8656: 	if (@to_correct) {
                   8657: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8658: 				     $line,'missingbubble',\@to_correct,
                   8659:                                      $randomorder,$randompick,\%respnumlookup,
                   8660:                                      \%startline);
1.157     albertel 8661: 	    return (1,$currentphase);
                   8662: 	}
                   8663: 
                   8664:     }
                   8665:     return (0,$currentphase+1);
                   8666: }
                   8667: 
1.663     raeburn  8668: sub hand_bubble_option {
                   8669:     my (undef, undef, $sequence) =
                   8670:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8671:     return if ($sequence eq '');
                   8672:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8673:     unless (ref($navmap)) {
                   8674:         return;
                   8675:     }
                   8676:     my $needs_hand_bubbles;
                   8677:     my $map=$navmap->getResourceByUrl($sequence);
                   8678:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8679:     foreach my $res (@resources) {
                   8680:         if (ref($res)) {
                   8681:             if ($res->is_problem()) {
                   8682:                 my $partlist = $res->parts();
                   8683:                 foreach my $part (@{ $partlist }) {
                   8684:                     my @types = $res->responseType($part);
                   8685:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8686:                         $needs_hand_bubbles = 1;
                   8687:                         last;
                   8688:                     }
                   8689:                 }
                   8690:             }
                   8691:         }
                   8692:     }
                   8693:     if ($needs_hand_bubbles) {
                   8694:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8695:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8696:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8697:                &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 />').
                   8698:                '<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  8699:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8700:     }
                   8701:     return;
                   8702: }
1.423     albertel 8703: 
1.82      albertel 8704: sub scantron_process_students {
1.608     www      8705:     my ($r,$symb) = @_;
1.513     foxr     8706: 
1.257     albertel 8707:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8708:     if (!$symb) {
                   8709: 	return '';
                   8710:     }
1.324     albertel 8711:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8712: 
1.257     albertel 8713:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8714:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8715:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8716:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8717:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8718:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8719:     unless (ref($navmap)) {
                   8720:         $r->print(&navmap_errormsg());
                   8721:         return '';
1.691     raeburn  8722:     }
1.83      albertel 8723:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8724:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8725:         %grader_randomlists_by_symb);
1.677     raeburn  8726:     if (ref($map)) {
                   8727:         $randomorder = $map->randomorder();
1.689     raeburn  8728:         $randompick = $map->randompick();
1.691     raeburn  8729:     } else {
                   8730:         $r->print(&navmap_errormsg());
                   8731:         return '';
1.677     raeburn  8732:     }
1.691     raeburn  8733:     my $nav_error;
1.83      albertel 8734:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8735:     if ($randomorder || $randompick) {
                   8736:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8737:         if ($nav_error) {
                   8738:             $r->print(&navmap_errormsg());
                   8739:             return '';
                   8740:         }
                   8741:     }
1.557     raeburn  8742:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8743:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8744: 
1.554     raeburn  8745:     my ($uname,$udom);
1.82      albertel 8746:     my $result= <<SCANTRONFORM;
1.81      albertel 8747: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8748:   <input type="hidden" name="command" value="scantron_configphase" />
                   8749:   $default_form_data
                   8750: SCANTRONFORM
1.82      albertel 8751:     $r->print($result);
                   8752: 
                   8753:     my @delayqueue;
1.542     raeburn  8754:     my (%completedstudents,%scandata);
1.140     albertel 8755:     
1.520     www      8756:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8757:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8758:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8759:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8760:     $r->print('<br />');
1.140     albertel 8761:     my $start=&Time::HiRes::time();
1.158     albertel 8762:     my $i=-1;
1.542     raeburn  8763:     my $started;
1.447     foxr     8764: 
1.649     raeburn  8765:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8766:     if ($nav_error) {
                   8767:         $r->print(&navmap_errormsg());
                   8768:         return '';
                   8769:     }
                   8770: 
1.513     foxr     8771:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8772:     # the user and return.
                   8773: 
                   8774:     if ($ssi_error) {
                   8775: 	$r->print("</form>");
                   8776: 	&ssi_print_error($r);
1.520     www      8777:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8778: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8779:     }
1.447     foxr     8780: 
1.542     raeburn  8781:     my %lettdig = &letter_to_digits();
                   8782:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8783:     my %orderedforcode;
1.542     raeburn  8784: 
1.157     albertel 8785:     while ($i<$scanlines->{'count'}) {
                   8786:  	($uname,$udom)=('','');
                   8787:  	$i++;
1.200     albertel 8788:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8789:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8790: 	if ($started) {
1.667     www      8791: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8792: 	}
                   8793: 	$started=1;
1.691     raeburn  8794:         my %respnumlookup = ();
                   8795:         my %startline = ();
                   8796:         my $total;
1.157     albertel 8797:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8798:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8799:                                                  $randompick,$sequence,\@master_seq,
                   8800:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8801:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8802:                                                  \$total);
1.157     albertel 8803:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8804:  					      \%idmap,$i)) {
                   8805:   	    &scantron_add_delay(\@delayqueue,$line,
                   8806:  				'Unable to find a student that matches',1);
                   8807:  	    next;
                   8808:   	}
                   8809:  	if (exists $completedstudents{$uname}) {
                   8810:  	    &scantron_add_delay(\@delayqueue,$line,
                   8811:  				'Student '.$uname.' has multiple sheets',2);
                   8812:  	    next;
                   8813:  	}
1.677     raeburn  8814:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8815:         my $user = $uname.':'.$usec;
1.157     albertel 8816:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8817: 
1.677     raeburn  8818:         my $scancode;
                   8819:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8820:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8821:             $scancode = $scan_record->{'scantron.CODE'};
                   8822:         } else {
                   8823:             $scancode = '';
                   8824:         }
                   8825: 
                   8826:         my @mapresources = @resources;
1.689     raeburn  8827:         if ($randomorder || $randompick) {
1.678     raeburn  8828:             @mapresources = 
1.691     raeburn  8829:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8830:                              \%orderedforcode);
1.677     raeburn  8831:         }
1.586     raeburn  8832:         my (%partids_by_symb,$res_error);
1.677     raeburn  8833:         foreach my $resource (@mapresources) {
1.586     raeburn  8834:             my $ressymb;
                   8835:             if (ref($resource)) {
                   8836:                 $ressymb = $resource->symb();
                   8837:             } else {
                   8838:                 $res_error = 1;
                   8839:                 last;
                   8840:             }
1.557     raeburn  8841:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8842:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8843:                 my $currcode;
                   8844:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8845:                     $currcode = $scancode;
                   8846:                 }
1.557     raeburn  8847:                 my ($analysis,$parts) =
1.672     raeburn  8848:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8849:                                               $uname,$udom,undef,$bubbles_per_row,
                   8850:                                               $currcode);
1.557     raeburn  8851:                 $partids_by_symb{$ressymb} = $parts;
                   8852:             } else {
                   8853:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8854:             }
1.554     raeburn  8855:         }
                   8856: 
1.586     raeburn  8857:         if ($res_error) {
                   8858:             &scantron_add_delay(\@delayqueue,$line,
                   8859:                                 'An error occurred while grading student '.$uname,2);
                   8860:             next;
                   8861:         }
                   8862: 
1.330     albertel 8863: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8864:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8865: 
                   8866: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8867: 	    &scantron_putfile($scanlines,$scan_data);
                   8868: 	}
1.161     albertel 8869: 	
1.542     raeburn  8870:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8871:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8872:                                    $bubbles_per_row,$randomorder,$randompick,
                   8873:                                    \%respnumlookup,\%startline) 
                   8874:             eq 'ssi_error') {
1.542     raeburn  8875:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8876:             $r->print("</form>");
                   8877:             &ssi_print_error($r);
                   8878:             &Apache::lonnet::remove_lock($lock);
                   8879:             return '';      # Why return ''?  Beats me.
                   8880:         }
1.513     foxr     8881: 
1.692     raeburn  8882:         if (($scancode) && ($randomorder || $randompick)) {
                   8883:             my $parmresult =
                   8884:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8885:                                                        '0_examcode',2,$scancode,
                   8886:                                                        'string_examcode',$uname,
                   8887:                                                        $udom);
                   8888:         }
1.140     albertel 8889: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8890:         if ($env{'form.verifyrecord'}) {
                   8891:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8892:             if ($randompick) {
                   8893:                 if ($total) {
                   8894:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8895:                 }
                   8896:             }
                   8897: 
1.542     raeburn  8898:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8899:             chomp($studentdata);
                   8900:             $studentdata =~ s/\r$//;
                   8901:             my $studentrecord = '';
                   8902:             my $counter = -1;
1.677     raeburn  8903:             foreach my $resource (@mapresources) {
1.554     raeburn  8904:                 my $ressymb = $resource->symb();
1.542     raeburn  8905:                 ($counter,my $recording) =
                   8906:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8907:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8908:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8909:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8910:                 $studentrecord .= $recording;
                   8911:             }
                   8912:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8913:                 &Apache::lonxml::clear_problem_counter();
                   8914:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8915:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8916:                                            $bubbles_per_row,$randomorder,$randompick,
                   8917:                                            \%respnumlookup,\%startline) 
                   8918:                     eq 'ssi_error') {
1.554     raeburn  8919:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8920:                     $r->print("</form>");
                   8921:                     &ssi_print_error($r);
                   8922:                     &Apache::lonnet::remove_lock($lock);
                   8923:                     delete($completedstudents{$uname});
                   8924:                     return '';
                   8925:                 }
1.542     raeburn  8926:                 $counter = -1;
                   8927:                 $studentrecord = '';
1.677     raeburn  8928:                 foreach my $resource (@mapresources) {
1.554     raeburn  8929:                     my $ressymb = $resource->symb();
1.542     raeburn  8930:                     ($counter,my $recording) =
                   8931:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8932:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8933:                                                  \%scantron_config,\%lettdig,$numletts,
                   8934:                                                  $randomorder,$randompick,\%respnumlookup,
                   8935:                                                  \%startline);
1.542     raeburn  8936:                     $studentrecord .= $recording;
                   8937:                 }
                   8938:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8939:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8940:                     if ($scancode eq '') {
1.658     bisitz   8941:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8942:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8943:                     } else {
1.658     bisitz   8944:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8945:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8946:                     }
                   8947:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8948:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8949:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8950:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8951:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8952:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8953:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8954:                               &Apache::loncommon::end_data_table_row().
                   8955:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8956:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8957:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8958:                               &Apache::loncommon::end_data_table_row().
                   8959:                               &Apache::loncommon::end_data_table().'</p>');
                   8960:                 } else {
                   8961:                     $r->print('<br /><span class="LC_warning">'.
                   8962:                              &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 />'.
                   8963:                              &mt("As a consequence, this user's submission history records two tries.").
                   8964:                                  '</span><br />');
                   8965:                 }
                   8966:             }
                   8967:         }
1.543     raeburn  8968:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8969:     } continue {
1.330     albertel 8970: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8971: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8972:     }
1.140     albertel 8973:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8974:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8975: #    my $lasttime = &Time::HiRes::time()-$start;
                   8976: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8977: 
1.200     albertel 8978:     $r->print("</form>");
1.157     albertel 8979:     return '';
1.75      albertel 8980: }
1.157     albertel 8981: 
1.557     raeburn  8982: sub graders_resources_pass {
1.649     raeburn  8983:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8984:         $bubbles_per_row) = @_;
1.557     raeburn  8985:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8986:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8987:         foreach my $resource (@{$resources}) {
                   8988:             my $ressymb = $resource->symb();
                   8989:             my ($analysis,$parts) =
                   8990:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8991:                                           $env{'user.name'},$env{'user.domain'},
                   8992:                                           1,$bubbles_per_row);
1.557     raeburn  8993:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8994:             if (ref($analysis) eq 'HASH') {
                   8995:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8996:                     $grader_randomlists_by_symb->{$ressymb} =
                   8997:                         $analysis->{'parts_withrandomlist'};
                   8998:                 }
                   8999:             }
                   9000:         }
                   9001:     }
                   9002:     return;
                   9003: }
                   9004: 
1.678     raeburn  9005: =pod
                   9006: 
                   9007: =item users_order
                   9008: 
                   9009:   Returns array of resources in current map, ordered based on either CODE,
                   9010:   if this is a CODEd exam, or based on student's identity if this is a 
                   9011:   "NAMEd" exam.
                   9012: 
1.691     raeburn  9013:   Should be used when randomorder and/or randompick applied when the 
                   9014:   corresponding exam was printed, prior to students completing bubblesheets 
                   9015:   for the version of the exam the student received.
1.678     raeburn  9016: 
                   9017: =cut
                   9018: 
                   9019: sub users_order  {
1.691     raeburn  9020:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9021:     my @mapresources;
1.691     raeburn  9022:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9023:         return @mapresources;
1.691     raeburn  9024:     }
                   9025:     if ($scancode) {
                   9026:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9027:             @mapresources = @{$orderedforcode->{$scancode}};
                   9028:         } else {
                   9029:             $env{'form.CODE'} = $scancode;
                   9030:             my $actual_seq =
                   9031:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9032:                                                                $master_seq,
                   9033:                                                                $user,$scancode,1);
                   9034:             if (ref($actual_seq) eq 'ARRAY') {
                   9035:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9036:                 if (ref($orderedforcode) eq 'HASH') {
                   9037:                     if (@mapresources > 0) { 
                   9038:                         $orderedforcode->{$scancode} = \@mapresources;
                   9039:                     }
                   9040:                 }
                   9041:             }
                   9042:             delete($env{'form.CODE'});
1.678     raeburn  9043:         }
                   9044:     } else {
                   9045:         my $actual_seq =
                   9046:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9047:                                                            $master_seq,
1.688     raeburn  9048:                                                            $user,undef,1);
1.678     raeburn  9049:         if (ref($actual_seq) eq 'ARRAY') {
                   9050:             @mapresources = 
                   9051:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9052:         }
1.691     raeburn  9053:     }
                   9054:     return @mapresources;
1.678     raeburn  9055: }
                   9056: 
1.542     raeburn  9057: sub grade_student_bubbles {
1.691     raeburn  9058:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9059:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9060:     my $uselookup = 0;
                   9061:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9062:         (ref($startline) eq 'HASH')) {
                   9063:         $uselookup = 1;
                   9064:     }
                   9065: 
1.554     raeburn  9066:     if (ref($resources) eq 'ARRAY') {
                   9067:         my $count = 0;
                   9068:         foreach my $resource (@{$resources}) {
                   9069:             my $ressymb = $resource->symb();
                   9070:             my %form = ('submitted'      => 'scantron',
                   9071:                         'grade_target'   => 'grade',
                   9072:                         'grade_username' => $uname,
                   9073:                         'grade_domain'   => $udom,
                   9074:                         'grade_courseid' => $env{'request.course.id'},
                   9075:                         'grade_symb'     => $ressymb,
                   9076:                         'CODE'           => $scancode
                   9077:                        );
1.649     raeburn  9078:             if ($bubbles_per_row ne '') {
                   9079:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9080:             }
1.663     raeburn  9081:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9082:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9083:             }
1.554     raeburn  9084:             if (ref($parts) eq 'HASH') {
                   9085:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9086:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9087:                         if ($uselookup) {
                   9088:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9089:                         } else {
                   9090:                             $form{'scantron_questnum_start.'.$part} =
                   9091:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9092:                         }
1.554     raeburn  9093:                         $count++;
                   9094:                     }
                   9095:                 }
                   9096:             }
                   9097:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9098:             return 'ssi_error' if ($ssi_error);
                   9099:             last if (&Apache::loncommon::connection_aborted($r));
                   9100:         }
1.542     raeburn  9101:     }
                   9102:     return;
                   9103: }
                   9104: 
1.157     albertel 9105: sub scantron_upload_scantron_data {
1.608     www      9106:     my ($r,$symb)=@_;
1.565     raeburn  9107:     my $dom = $env{'request.role.domain'};
                   9108:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9109:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9110:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9111: 							  'domainid',
1.565     raeburn  9112: 							  'coursename',$dom);
                   9113:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9114:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9115:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9116:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9117:     &js_escape(\$nofile_alert);
1.579     raeburn  9118:     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  9119:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9120:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9121:     function checkUpload(formname) {
                   9122: 	if (formname.upfile.value == "") {
1.579     raeburn  9123: 	    alert("'.$nofile_alert.'");
1.157     albertel 9124: 	    return false;
                   9125: 	}
1.565     raeburn  9126:         if (formname.courseid.value == "") {
1.579     raeburn  9127:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9128:             return false;
                   9129:         }
1.157     albertel 9130: 	formname.submit();
                   9131:     }
1.565     raeburn  9132: 
                   9133:     function ToSyllabus() {
                   9134:         var cdom = '."'$dom'".';
                   9135:         var cnum = document.rules.courseid.value;
                   9136:         if (cdom == "" || cdom == null) {
                   9137:             return;
                   9138:         }
                   9139:         if (cnum == "" || cnum == null) {
                   9140:            return;
                   9141:         }
                   9142:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9143:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9144:         return;
                   9145:     }
                   9146: 
1.597     wenzelju 9147: '));
                   9148:     $r->print('
1.648     bisitz   9149: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9150: 
1.492     albertel 9151: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9152: '.$default_form_data.
                   9153:   &Apache::lonhtmlcommon::start_pick_box().
                   9154:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9155:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9156:   &Apache::lonhtmlcommon::row_closure().
                   9157:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9158:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9159:   &Apache::lonhtmlcommon::row_closure().
                   9160:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9161:   '<input name="domainid" type="hidden" />'.$domdesc.
                   9162:   &Apache::lonhtmlcommon::row_closure().
                   9163:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9164:   '<input type="file" name="upfile" size="50" />'.
                   9165:   &Apache::lonhtmlcommon::row_closure(1).
                   9166:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9167: 
1.492     albertel 9168: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9169: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9170: </form>
1.492     albertel 9171: ');
1.157     albertel 9172:     return '';
                   9173: }
                   9174: 
1.423     albertel 9175: 
1.157     albertel 9176: sub scantron_upload_scantron_data_save {
1.608     www      9177:     my($r,$symb)=@_;
1.182     albertel 9178:     my $doanotherupload=
                   9179: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9180: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9181: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9182: 	'</form>'."\n";
1.257     albertel 9183:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9184: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9185: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9186: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9187: 	unless ($symb) {
1.182     albertel 9188: 	    $r->print($doanotherupload);
                   9189: 	}
1.162     albertel 9190: 	return '';
                   9191:     }
1.257     albertel 9192:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9193:     my $uploadedfile;
1.710     bisitz   9194:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9195:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9196:         $r->print(
                   9197:             &Apache::lonhtmlcommon::confirm_success(
                   9198:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9199:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9200:     } else {
1.568     raeburn  9201:         my $result = 
                   9202:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   9203:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9204:         if ($result =~ m{^/uploaded/}) {
                   9205:             $r->print(
                   9206:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9207:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9208:                         (length($env{'form.upfile'})-1),
                   9209:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9210:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9211:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9212:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   9213:         } else {
                   9214:             $r->print(
                   9215:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9216:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9217:                           $result,
1.568     raeburn  9218: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9219: 	}
                   9220:     }
1.174     albertel 9221:     if ($symb) {
1.612     www      9222: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9223:     } else {
1.182     albertel 9224: 	$r->print($doanotherupload);
1.174     albertel 9225:     }
1.157     albertel 9226:     return '';
                   9227: }
                   9228: 
1.567     raeburn  9229: sub validate_uploaded_scantron_file {
                   9230:     my ($cdom,$cname,$fname) = @_;
                   9231:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9232:     my @lines;
                   9233:     if ($scanlines ne '-1') {
                   9234:         @lines=split("\n",$scanlines,-1);
                   9235:     }
                   9236:     my $output;
                   9237:     if (@lines) {
                   9238:         my (%counts,$max_match_format);
1.710     bisitz   9239:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9240:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9241:         my %idmap = &username_to_idmap($classlist);
                   9242:         foreach my $key (keys(%idmap)) {
                   9243:             my $lckey = lc($key);
                   9244:             $idmap{$lckey} = $idmap{$key};
                   9245:         }
                   9246:         my %unique_formats;
                   9247:         my @formatlines = &get_scantronformat_file();
                   9248:         foreach my $line (@formatlines) {
                   9249:             chomp($line);
                   9250:             my @config = split(/:/,$line);
                   9251:             my $idstart = $config[5];
                   9252:             my $idlength = $config[6];
                   9253:             if (($idstart ne '') && ($idlength > 0)) {
                   9254:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9255:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9256:                 } else {
                   9257:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9258:                 }
                   9259:             }
                   9260:         }
                   9261:         foreach my $key (keys(%unique_formats)) {
                   9262:             my ($idstart,$idlength) = split(':',$key);
                   9263:             %{$counts{$key}} = (
                   9264:                                'found'   => 0,
                   9265:                                'total'   => 0,
                   9266:                               );
                   9267:             foreach my $line (@lines) {
                   9268:                 next if ($line =~ /^#/);
                   9269:                 next if ($line =~ /^[\s\cz]*$/);
                   9270:                 my $id = substr($line,$idstart-1,$idlength);
                   9271:                 $id = lc($id);
                   9272:                 if (exists($idmap{$id})) {
                   9273:                     $counts{$key}{'found'} ++;
                   9274:                 }
                   9275:                 $counts{$key}{'total'} ++;
                   9276:             }
                   9277:             if ($counts{$key}{'total'}) {
                   9278:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9279:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9280:                     $max_match_pct = $percent_match;
                   9281:                     $max_match_format = $key;
1.710     bisitz   9282:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9283:                     $max_match_count = $counts{$key}{'total'};
                   9284:                 }
                   9285:             }
                   9286:         }
                   9287:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9288:             my $format_descs;
                   9289:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9290:             for (my $i=0; $i<$numwithformat; $i++) {
                   9291:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9292:                 if ($i<$numwithformat-2) {
                   9293:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9294:                 } elsif ($i==$numwithformat-2) {
                   9295:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9296:                 } elsif ($i==$numwithformat-1) {
                   9297:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9298:                 }
                   9299:             }
                   9300:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9301:             $output .= '<br />';
                   9302:             if ($found_match_count == $max_match_count) {
                   9303:                 # 100% matching entries
                   9304:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9305:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9306:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9307:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9308:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9309:                     ' in the file (for the format defined for [_3]).',
                   9310:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9311:             } else {
                   9312:                 # Not all entries matching? -> Show warning and additional info
                   9313:                 $output .=
                   9314:                     &Apache::lonhtmlcommon::confirm_success(
                   9315:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9316:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9317:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9318:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9319:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9320:                         ' in the file (for the format defined for [_3]).',
                   9321:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9322:                     '<p class="LC_info">'.
                   9323:                     &mt('A low percentage of matches results from one of the following:').
                   9324:                     '</p><ul>'.
                   9325:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9326:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9327:                                '<i>'.$cdom.'</i>').'</li>'.
                   9328:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9329:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9330:                     '</ul>';
                   9331:             }
1.567     raeburn  9332:         }
                   9333:     } else {
1.710     bisitz   9334:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9335:     }
                   9336:     return $output;
                   9337: }
                   9338: 
1.202     albertel 9339: sub valid_file {
                   9340:     my ($requested_file)=@_;
                   9341:     foreach my $filename (sort(&scantron_filenames())) {
                   9342: 	if ($requested_file eq $filename) { return 1; }
                   9343:     }
                   9344:     return 0;
                   9345: }
                   9346: 
                   9347: sub scantron_download_scantron_data {
1.608     www      9348:     my ($r,$symb)=@_;
                   9349:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9350:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9351:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9352:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9353:     if (! &valid_file($file)) {
1.492     albertel 9354: 	$r->print('
1.202     albertel 9355: 	<p>
1.686     bisitz   9356: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9357:         </p>
1.492     albertel 9358: ');
1.202     albertel 9359: 	return;
                   9360:     }
                   9361:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9362:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9363:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9364:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9365:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9366:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9367:     $r->print('
1.202     albertel 9368:     <p>
1.723     raeburn  9369: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9370: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9371:     </p>
                   9372:     <p>
1.492     albertel 9373: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9374: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9375:     </p>
                   9376:     <p>
1.492     albertel 9377: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9378: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9379:     </p>
1.492     albertel 9380: ');
1.202     albertel 9381:     return '';
                   9382: }
1.157     albertel 9383: 
1.523     raeburn  9384: sub checkscantron_results {
1.608     www      9385:     my ($r,$symb) = @_;
1.523     raeburn  9386:     if (!$symb) {return '';}
                   9387:     my $cid = $env{'request.course.id'};
1.542     raeburn  9388:     my %lettdig = &letter_to_digits();
1.523     raeburn  9389:     my $numletts = scalar(keys(%lettdig));
                   9390:     my $cnum = $env{'course.'.$cid.'.num'};
                   9391:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9392:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9393:     my %record;
                   9394:     my %scantron_config =
                   9395:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9396:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9397:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9398:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9399:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9400:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9401:     unless (ref($navmap)) {
                   9402:         $r->print(&navmap_errormsg());
                   9403:         return '';
                   9404:     }
1.523     raeburn  9405:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9406:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9407:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9408:     if (ref($map)) { 
                   9409:         $randomorder=$map->randomorder();
1.689     raeburn  9410:         $randompick=$map->randompick();
1.677     raeburn  9411:     }
1.557     raeburn  9412:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9413:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9414:     if ($nav_error) {
                   9415:         $r->print(&navmap_errormsg());
                   9416:         return '';
1.678     raeburn  9417:     }
1.673     raeburn  9418:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9419:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9420:     my ($uname,$udom);
1.523     raeburn  9421:     my (%scandata,%lastname,%bylast);
                   9422:     $r->print('
                   9423: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9424: 
                   9425:     my @delayqueue;
                   9426:     my %completedstudents;
                   9427: 
1.691     raeburn  9428:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9429:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9430:     my ($username,$domain,$started);
1.649     raeburn  9431:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9432:     if ($nav_error) {
                   9433:         $r->print(&navmap_errormsg());
                   9434:         return '';
                   9435:     }
1.523     raeburn  9436: 
1.667     www      9437:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9438:     my $start=&Time::HiRes::time();
                   9439:     my $i=-1;
                   9440: 
                   9441:     while ($i<$scanlines->{'count'}) {
                   9442:         ($username,$domain,$uname)=('','','');
                   9443:         $i++;
                   9444:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9445:         if ($line=~/^[\s\cz]*$/) { next; }
                   9446:         if ($started) {
1.667     www      9447:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9448:         }
                   9449:         $started=1;
                   9450:         my $scan_record=
                   9451:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9452:                                                      $scan_data);
1.693     raeburn  9453:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9454:                                               \%idmap,$i)) {
1.523     raeburn  9455:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9456:                                 'Unable to find a student that matches',1);
                   9457:             next;
                   9458:         }
                   9459:         if (exists $completedstudents{$uname}) {
                   9460:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9461:                                 'Student '.$uname.' has multiple sheets',2);
                   9462:             next;
                   9463:         }
                   9464:         my $pid = $scan_record->{'scantron.ID'};
                   9465:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9466:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9467:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9468:         my $user = $uname.':'.$usec;
1.523     raeburn  9469:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9470: 
1.678     raeburn  9471:         my $scancode;
1.677     raeburn  9472:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9473:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9474:             $scancode = $scan_record->{'scantron.CODE'};
                   9475:         } else {
                   9476:             $scancode = '';
                   9477:         }
                   9478: 
                   9479:         my @mapresources = @resources;
1.691     raeburn  9480:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9481:         my %respnumlookup=();
                   9482:         my %startline=();
1.689     raeburn  9483:         if ($randomorder || $randompick) {
1.678     raeburn  9484:             @mapresources =
1.691     raeburn  9485:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9486:                              \%orderedforcode);
                   9487:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9488:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9489:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9490:                                              \%respnumlookup,\%startline);
                   9491:             if ($randompick && $total) {
                   9492:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9493:             }
1.677     raeburn  9494:         }
1.691     raeburn  9495:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9496:         chomp($scandata{$pid});
                   9497:         $scandata{$pid} =~ s/\r$//;
                   9498: 
1.523     raeburn  9499:         my $counter = -1;
1.677     raeburn  9500:         foreach my $resource (@mapresources) {
1.557     raeburn  9501:             my $parts;
1.554     raeburn  9502:             my $ressymb = $resource->symb();
1.557     raeburn  9503:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9504:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9505:                 my $currcode;
                   9506:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9507:                     $currcode = $scancode;
                   9508:                 }
1.557     raeburn  9509:                 (my $analysis,$parts) =
1.672     raeburn  9510:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9511:                                               $username,$domain,undef,
1.741     raeburn  9512:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9513:             } else {
                   9514:                 $parts = $grader_partids_by_symb{$ressymb};
                   9515:             }
1.542     raeburn  9516:             ($counter,my $recording) =
                   9517:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9518:                                          $scandata{$pid},$parts,
1.691     raeburn  9519:                                          \%scantron_config,\%lettdig,$numletts,
                   9520:                                          $randomorder,$randompick,
                   9521:                                          \%respnumlookup,\%startline);
1.542     raeburn  9522:             $record{$pid} .= $recording;
1.523     raeburn  9523:         }
                   9524:     }
                   9525:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9526:     $r->print('<br />');
                   9527:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9528:     $passed = 0;
                   9529:     $failed = 0;
                   9530:     $numstudents = 0;
                   9531:     foreach my $last (sort(keys(%bylast))) {
                   9532:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9533:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9534:                 my $showscandata = $scandata{$pid};
                   9535:                 my $showrecord = $record{$pid};
                   9536:                 $showscandata =~ s/\s/&nbsp;/g;
                   9537:                 $showrecord =~ s/\s/&nbsp;/g;
                   9538:                 if ($scandata{$pid} eq $record{$pid}) {
                   9539:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9540:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9541: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9542: '</tr>'."\n".
                   9543: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9544: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9545:                     $passed ++;
                   9546:                 } else {
                   9547:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9548:                     $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  9549: '</tr>'."\n".
                   9550: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9551: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9552: '</tr>'."\n";
                   9553:                     $failed ++;
                   9554:                 }
                   9555:                 $numstudents ++;
                   9556:             }
                   9557:         }
                   9558:     }
1.648     bisitz   9559:     $r->print(
                   9560:         '<p>'
                   9561:        .&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).',
                   9562:             '<b>',
                   9563:             $numstudents,
                   9564:             '</b>',
                   9565:             $env{'form.scantron_maxbubble'})
                   9566:        .'</p>'
                   9567:     );
1.682     raeburn  9568:     $r->print('<p>'
1.683     raeburn  9569:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9570:              .'<br />'
                   9571:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9572:              .'</p>'
                   9573:     );
1.523     raeburn  9574:     if ($passed) {
1.572     www      9575:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9576:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9577:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9578:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9579:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9580:                  $okstudents."\n".
                   9581:                  &Apache::loncommon::end_data_table().'<br />');
                   9582:     }
                   9583:     if ($failed) {
1.572     www      9584:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9585:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9586:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9587:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9588:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9589:                  $badstudents."\n".
                   9590:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9591:                  &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  9592:     }
1.614     www      9593:     $r->print('</form><br />');
1.523     raeburn  9594:     return;
                   9595: }
                   9596: 
1.542     raeburn  9597: sub verify_scantron_grading {
1.554     raeburn  9598:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9599:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9600:         $respnumlookup,$startline) = @_;
1.542     raeburn  9601:     my ($record,%expected,%startpos);
                   9602:     return ($counter,$record) if (!ref($resource));
                   9603:     return ($counter,$record) if (!$resource->is_problem());
                   9604:     my $symb = $resource->symb();
1.554     raeburn  9605:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9606:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9607:         $counter ++;
                   9608:         $expected{$part_id} = 0;
1.691     raeburn  9609:         my $respnum = $counter;
                   9610:         if ($randomorder || $randompick) {
                   9611:             $respnum = $respnumlookup->{$counter};
                   9612:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9613:         } else {
                   9614:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9615:         }
                   9616:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9617:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9618:             foreach my $item (@sub_lines) {
                   9619:                 $expected{$part_id} += $item;
                   9620:             }
                   9621:         } else {
1.691     raeburn  9622:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9623:         }
                   9624:     }
                   9625:     if ($symb) {
                   9626:         my %recorded;
                   9627:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9628:         if ($returnhash{'version'}) {
                   9629:             my %lasthash=();
                   9630:             my $version;
                   9631:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9632:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9633:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9634:                 }
                   9635:             }
                   9636:             foreach my $key (keys(%lasthash)) {
                   9637:                 if ($key =~ /\.scantron$/) {
                   9638:                     my $value = &unescape($lasthash{$key});
                   9639:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9640:                     if ($value eq '') {
                   9641:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9642:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9643:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9644:                             }
                   9645:                         }
                   9646:                     } else {
                   9647:                         my @tocheck;
                   9648:                         my @items = split(//,$value);
                   9649:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9650:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9651:                             if (@items < $expected{$part_id}) {
                   9652:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9653:                                 my @singles = split(//,$fragment);
                   9654:                                 foreach my $pos (@singles) {
                   9655:                                     if ($pos eq ' ') {
                   9656:                                         push(@tocheck,$pos);
                   9657:                                     } else {
                   9658:                                         my $next = shift(@items);
                   9659:                                         push(@tocheck,$next);
                   9660:                                     }
                   9661:                                 }
                   9662:                             } else {
                   9663:                                 @tocheck = @items;
                   9664:                             }
                   9665:                             foreach my $letter (@tocheck) {
                   9666:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9667:                                     if ($letter !~ /^[A-J]$/) {
                   9668:                                         $letter = $scantron_config->{'Qoff'};
                   9669:                                     }
                   9670:                                     $recorded{$part_id} .= $letter;
                   9671:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9672:                                     my $digit;
                   9673:                                     if ($letter !~ /^[A-J]$/) {
                   9674:                                         $digit = $scantron_config->{'Qoff'};
                   9675:                                     } else {
                   9676:                                         $digit = $lettdig->{$letter};
                   9677:                                     }
                   9678:                                     $recorded{$part_id} .= $digit;
                   9679:                                 }
                   9680:                             }
                   9681:                         } else {
                   9682:                             @tocheck = @items;
                   9683:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9684:                                 my $curr_sub = shift(@tocheck);
                   9685:                                 my $digit;
                   9686:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9687:                                     $digit = $lettdig->{$curr_sub}-1;
                   9688:                                 }
                   9689:                                 if ($curr_sub eq 'J') {
                   9690:                                     $digit += scalar($numletts);
                   9691:                                 }
                   9692:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9693:                                     if ($j == $digit) {
                   9694:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9695:                                     } else {
                   9696:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9697:                                     }
                   9698:                                 }
                   9699:                             }
                   9700:                         }
                   9701:                     }
                   9702:                 }
                   9703:             }
                   9704:         }
1.554     raeburn  9705:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9706:             if ($recorded{$part_id} eq '') {
                   9707:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9708:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9709:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9710:                     }
                   9711:                 }
                   9712:             }
                   9713:             $record .= $recorded{$part_id};
                   9714:         }
                   9715:     }
                   9716:     return ($counter,$record);
                   9717: }
                   9718: 
1.691     raeburn  9719: sub letter_to_digits {
1.542     raeburn  9720:     my %lettdig = (
                   9721:                     A => 1,
                   9722:                     B => 2,
                   9723:                     C => 3,
                   9724:                     D => 4,
                   9725:                     E => 5,
                   9726:                     F => 6,
                   9727:                     G => 7,
                   9728:                     H => 8,
                   9729:                     I => 9,
                   9730:                     J => 0,
                   9731:                   );
                   9732:     return %lettdig;
                   9733: }
                   9734: 
1.423     albertel 9735: 
1.75      albertel 9736: #-------- end of section for handling grading scantron forms -------
                   9737: #
                   9738: #-------------------------------------------------------------------
                   9739: 
1.72      ng       9740: #-------------------------- Menu interface -------------------------
                   9741: #
1.614     www      9742: #--- Href with symb and command ---
                   9743: 
                   9744: sub href_symb_cmd {
                   9745:     my ($symb,$cmd)=@_;
1.669     raeburn  9746:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9747: }
                   9748: 
1.443     banghart 9749: sub grading_menu {
1.608     www      9750:     my ($request,$symb) = @_;
1.443     banghart 9751:     if (!$symb) {return '';}
                   9752: 
                   9753:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9754:                   'command'=>'individual');
1.538     schulted 9755:     
1.598     www      9756:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9757: 
                   9758:     $fields{'command'}='ungraded';
                   9759:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9760: 
                   9761:     $fields{'command'}='table';
                   9762:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9763: 
                   9764:     $fields{'command'}='all_for_one';
                   9765:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9766: 
1.621     www      9767:     $fields{'command'}='downloadfilesselect';
                   9768:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9769: 
1.443     banghart 9770:     $fields{'command'} = 'csvform';
1.538     schulted 9771:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9772:     
1.443     banghart 9773:     $fields{'command'} = 'processclicker';
1.538     schulted 9774:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9775:     
1.443     banghart 9776:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9777:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9778: 
                   9779:     $fields{'command'} = 'initialverifyreceipt';
                   9780:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9781:     
1.598     www      9782:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9783:             items =>[
1.598     www      9784:                         {	linktext => 'Select individual students to grade',
                   9785:                     		url => $url1a,
1.538     schulted 9786:                     		permission => 'F',
1.636     wenzelju 9787:                     		icon => 'grade_students.png',
1.598     www      9788:                     		linktitle => 'Grade current resource for a selection of students.'
                   9789:                         }, 
                   9790:                         {       linktext => 'Grade ungraded submissions.',
                   9791:                                 url => $url1b,
                   9792:                                 permission => 'F',
1.636     wenzelju 9793:                                 icon => 'ungrade_sub.png',
1.598     www      9794:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9795:                         },
1.598     www      9796: 
                   9797:                         {       linktext => 'Grading table',
                   9798:                                 url => $url1c,
                   9799:                                 permission => 'F',
1.636     wenzelju 9800:                                 icon => 'grading_table.png',
1.598     www      9801:                                 linktitle => 'Grade current resource for all students.'
                   9802:                         },
1.615     www      9803:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9804:                                 url => $url1d,
                   9805:                                 permission => 'F',
1.636     wenzelju 9806:                                 icon => 'grade_PageFolder.png',
1.598     www      9807:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9808:                         },
                   9809:                         {       linktext => 'Download submissions',
                   9810:                                 url => $url1e,
                   9811:                                 permission => 'F',
1.636     wenzelju 9812:                                 icon => 'download_sub.png',
1.621     www      9813:                                 linktitle => 'Download all students submissions.'
1.598     www      9814:                         }]},
                   9815:                          { categorytitle=>'Automated Grading',
                   9816:                items =>[
                   9817: 
1.538     schulted 9818:                 	    {	linktext => 'Upload Scores',
                   9819:                     		url => $url2,
                   9820:                     		permission => 'F',
                   9821:                     		icon => 'uploadscores.png',
                   9822:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9823:                 	    },
                   9824:                 	    {	linktext => 'Process Clicker',
                   9825:                     		url => $url3,
                   9826:                     		permission => 'F',
                   9827:                     		icon => 'addClickerInfoFile.png',
                   9828:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9829:                 	    },
1.587     raeburn  9830:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9831:                     		url => $url4,
                   9832:                     		permission => 'F',
1.636     wenzelju 9833:                     		icon => 'bubblesheet.png',
1.648     bisitz   9834:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9835:                 	    },
1.616     www      9836:                             {   linktext => 'Verify Receipt Number',
1.602     www      9837:                                 url => $url5,
                   9838:                                 permission => 'F',
1.636     wenzelju 9839:                                 icon => 'receipt_number.png',
1.602     www      9840:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9841:                             }
                   9842: 
1.538     schulted 9843:                     ]
                   9844:             });
                   9845: 
1.443     banghart 9846:     # Create the menu
                   9847:     my $Str;
1.445     banghart 9848:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9849:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9850:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9851: 
1.602     www      9852:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9853:     return $Str;    
                   9854: }
                   9855: 
1.598     www      9856: 
                   9857: sub ungraded {
                   9858:     my ($request)=@_;
                   9859:     &submit_options($request);
                   9860: }
                   9861: 
1.599     www      9862: sub submit_options_sequence {
1.608     www      9863:     my ($request,$symb) = @_;
1.599     www      9864:     if (!$symb) {return '';}
1.600     www      9865:     &commonJSfunctions($request);
                   9866:     my $result;
1.599     www      9867: 
1.600     www      9868:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9869:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9870:     $result.=&selectfield(0).
1.601     www      9871:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9872:             <div>
                   9873:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9874:             </div>
                   9875:         </div>
                   9876:   </form>';
                   9877:     return $result;
                   9878: }
                   9879: 
                   9880: sub submit_options_table {
1.608     www      9881:     my ($request,$symb) = @_;
1.600     www      9882:     if (!$symb) {return '';}
1.599     www      9883:     &commonJSfunctions($request);
1.746     raeburn  9884:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      9885:     my $result;
                   9886: 
                   9887:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9888:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9889: 
1.745     raeburn  9890:     $result.=&selectfield(1,$is_tool).
1.601     www      9891:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9892:             <div>
                   9893:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9894:             </div>
                   9895:         </div>
                   9896:   </form>';
                   9897:     return $result;
                   9898: }
1.443     banghart 9899: 
1.621     www      9900: sub submit_options_download {
                   9901:     my ($request,$symb) = @_;
                   9902:     if (!$symb) {return '';}
                   9903: 
1.746     raeburn  9904:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      9905:     &commonJSfunctions($request);
                   9906: 
                   9907:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9908:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9909:     $result.='
                   9910: <h2>
1.750   ! raeburn  9911:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  9912: </h2>'.&selectfield(1,$is_tool).'
1.621     www      9913:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9914:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9915:             </div>
                   9916:           </div>
1.600     www      9917: 
                   9918: 
1.621     www      9919:   </form>';
                   9920:     return $result;
                   9921: }
                   9922: 
1.443     banghart 9923: #--- Displays the submissions first page -------
                   9924: sub submit_options {
1.608     www      9925:     my ($request,$symb) = @_;
1.72      ng       9926:     if (!$symb) {return '';}
                   9927: 
1.746     raeburn  9928:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       9929:     &commonJSfunctions($request);
1.473     albertel 9930:     my $result;
1.533     bisitz   9931: 
1.72      ng       9932:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9933: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  9934:     $result.=&selectfield(1,$is_tool).'
1.601     www      9935:                 <input type="hidden" name="command" value="submission" /> 
                   9936: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9937:             </div>
                   9938:           </div>
                   9939: 
                   9940: 
                   9941:   </form>';
                   9942:     return $result;
                   9943: }
1.533     bisitz   9944: 
1.601     www      9945: sub selectfield {
1.745     raeburn  9946:    my ($full,$is_tool)=@_;
                   9947:    my %options;
                   9948:    if ($is_tool) {
                   9949:        %options =
                   9950:            (&transtatus_options,
                   9951:             'select_form_order' => ['yes','incorrect','all']);
                   9952:    } else {
                   9953:        %options = 
                   9954:            (&substatus_options,
                   9955:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   9956:    }
1.601     www      9957:    my $result='<div class="LC_columnSection">
1.537     harmsja  9958:   
1.533     bisitz   9959:     <fieldset>
                   9960:       <legend>
                   9961:        '.&mt('Sections').'
                   9962:       </legend>
1.601     www      9963:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9964:     </fieldset>
1.537     harmsja  9965:   
1.533     bisitz   9966:     <fieldset>
                   9967:       <legend>
                   9968:         '.&mt('Groups').'
                   9969:       </legend>
                   9970:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9971:     </fieldset>
1.537     harmsja  9972:   
1.533     bisitz   9973:     <fieldset>
                   9974:       <legend>
                   9975:         '.&mt('Access Status').'
                   9976:       </legend>
1.601     www      9977:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9978:     </fieldset>';
                   9979:     if ($full) {
1.745     raeburn  9980:         my $heading = &mt('Submission Status');
                   9981:         if ($is_tool) {
                   9982:             $heading = &mt('Transaction Status');
                   9983:         }
                   9984:         $result.='
1.533     bisitz   9985:     <fieldset>
                   9986:       <legend>
1.745     raeburn  9987:         '.$heading.'
1.601     www      9988:       </legend>'.
1.635     raeburn  9989:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9990:    '</fieldset>';
                   9991:     }
                   9992:     $result.='</div><br />';
1.44      ng       9993:     return $result;
1.2       albertel 9994: }
                   9995: 
1.738     raeburn  9996: sub substatus_options {
                   9997:     return &Apache::lonlocal::texthash(
                   9998:                                       'yes'       => 'with submissions',
                   9999:                                       'queued'    => 'in grading queue',
                   10000:                                       'graded'    => 'with ungraded submissions',
                   10001:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10002:                                       'all'       => 'with any status',
                   10003:                                       );
1.738     raeburn  10004: }
                   10005: 
1.745     raeburn  10006: sub transtatus_options {
                   10007:     return &Apache::lonlocal::texthash(
                   10008:                                        'yes'       => 'with score transactions',
                   10009:                                        'incorrect' => 'with less than full credit',
                   10010:                                        'all'       => 'with any status',
                   10011:                                       );
                   10012: }
                   10013: 
1.285     albertel 10014: sub reset_perm {
                   10015:     undef(%perm);
                   10016: }
                   10017: 
                   10018: sub init_perm {
                   10019:     &reset_perm();
1.300     albertel 10020:     foreach my $test_perm ('vgr','mgr','opa') {
                   10021: 
                   10022: 	my $scope = $env{'request.course.id'};
                   10023: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10024: 
                   10025: 	    $scope .= '/'.$env{'request.course.sec'};
                   10026: 	    if ( $perm{$test_perm}=
                   10027: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10028: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10029: 	    } else {
                   10030: 		delete($perm{$test_perm});
                   10031: 	    }
1.285     albertel 10032: 	}
                   10033:     }
                   10034: }
                   10035: 
1.674     raeburn  10036: sub init_old_essays {
                   10037:     my ($symb,$apath,$adom,$aname) = @_;
                   10038:     if ($symb ne '') {
                   10039:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10040:         if (keys(%essays) > 0) {
                   10041:             $old_essays{$symb} = \%essays;
                   10042:         }
                   10043:     }
                   10044:     return;
                   10045: }
                   10046: 
                   10047: sub reset_old_essays {
                   10048:     undef(%old_essays);
                   10049: }
                   10050: 
1.400     www      10051: sub gather_clicker_ids {
1.408     albertel 10052:     my %clicker_ids;
1.400     www      10053: 
                   10054:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10055: 
                   10056:     # Set up a couple variables.
1.407     albertel 10057:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10058:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10059:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10060: 
1.407     albertel 10061:     foreach my $student (keys(%$classlist)) {
1.438     www      10062:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10063:         my $username = $classlist->{$student}->[$username_idx];
                   10064:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10065:         my $clickers =
1.408     albertel 10066: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10067:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10068:             $id=~s/^[\#0]+//;
1.421     www      10069:             $id=~s/[\-\:]//g;
1.407     albertel 10070:             if (exists($clicker_ids{$id})) {
1.408     albertel 10071: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10072:             } else {
1.408     albertel 10073: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10074:             }
                   10075:         }
                   10076:     }
1.407     albertel 10077:     return %clicker_ids;
1.400     www      10078: }
                   10079: 
1.402     www      10080: sub gather_adv_clicker_ids {
1.408     albertel 10081:     my %clicker_ids;
1.402     www      10082:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10083:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10084:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10085:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10086:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10087:             my ($puname,$pudom)=split(/\:/,$person);
                   10088:             my $clickers =
1.408     albertel 10089: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10090:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10091: 		$id=~s/^[\#0]+//;
1.421     www      10092:                 $id=~s/[\-\:]//g;
1.408     albertel 10093: 		if (exists($clicker_ids{$id})) {
                   10094: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10095: 		} else {
                   10096: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10097: 		}
1.405     www      10098:             }
1.402     www      10099:         }
                   10100:     }
1.407     albertel 10101:     return %clicker_ids;
1.402     www      10102: }
                   10103: 
1.413     www      10104: sub clicker_grading_parameters {
                   10105:     return ('gradingmechanism' => 'scalar',
                   10106:             'upfiletype' => 'scalar',
                   10107:             'specificid' => 'scalar',
                   10108:             'pcorrect' => 'scalar',
                   10109:             'pincorrect' => 'scalar');
                   10110: }
                   10111: 
1.400     www      10112: sub process_clicker {
1.608     www      10113:     my ($r,$symb)=@_;
1.400     www      10114:     if (!$symb) {return '';}
                   10115:     my $result=&checkforfile_js();
1.632     www      10116:     $result.=&Apache::loncommon::start_data_table().
                   10117:              &Apache::loncommon::start_data_table_header_row().
                   10118:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10119:              &Apache::loncommon::end_data_table_header_row().
                   10120:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10121: # Attempt to restore parameters from last session, set defaults if not present
                   10122:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10123:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10124:                                                  \%Saveable_Parameters);
                   10125:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10126:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10127:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10128:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10129: 
                   10130:     my %checked;
1.521     www      10131:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10132:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10133:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10134:        }
                   10135:     }
                   10136: 
1.632     www      10137:     my $upload=&mt("Evaluate File");
1.400     www      10138:     my $type=&mt("Type");
1.402     www      10139:     my $attendance=&mt("Award points just for participation");
                   10140:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10141:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10142:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10143:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10144:     my $pcorrect=&mt("Percentage points for correct solution");
                   10145:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10146:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10147: 						   {'iclicker' => 'i>clicker',
1.666     www      10148:                                                     'interwrite' => 'interwrite PRS',
                   10149:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10150:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10151:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10152: function sanitycheck() {
                   10153: // Accept only integer percentages
                   10154:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10155:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10156: // Find out grading choice
                   10157:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10158:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10159:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10160:       }
                   10161:    }
                   10162: // By default, new choice equals user selection
                   10163:    newgradingchoice=gradingchoice;
                   10164: // Not good to give more points for false answers than correct ones
                   10165:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10166:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10167:    }
                   10168: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10169:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10170:       document.forms.gradesupload.pcorrect.value=100;
                   10171:       document.forms.gradesupload.pincorrect.value=100;
                   10172:    }
                   10173: // If the values are different, cannot be attendance only
                   10174:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10175:        (gradingchoice=='attendance')) {
                   10176:        newgradingchoice='personnel';
                   10177:    }
                   10178: // Change grading choice to new one
                   10179:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10180:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10181:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10182:       } else {
                   10183:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10184:       }
                   10185:    }
                   10186: // Remember the old state
                   10187:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10188: }
1.597     wenzelju 10189: ENDUPFORM
                   10190:     $result.= <<ENDUPFORM;
1.400     www      10191: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10192: <input type="hidden" name="symb" value="$symb" />
                   10193: <input type="hidden" name="command" value="processclickerfile" />
                   10194: <input type="file" name="upfile" size="50" />
                   10195: <br /><label>$type: $selectform</label>
1.632     www      10196: ENDUPFORM
                   10197:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10198:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10199:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10200: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10201: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10202: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10203: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10204: <br />&nbsp;&nbsp;&nbsp;
                   10205: <input type="text" name="givenanswer" size="50" />
1.413     www      10206: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10207: ENDGRADINGFORM
                   10208:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10209:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10210:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10211: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10212: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 10213: </form>'
1.632     www      10214: ENDPERCFORM
                   10215:     $result.='</td>'.
                   10216:              &Apache::loncommon::end_data_table_row().
                   10217:              &Apache::loncommon::end_data_table();
1.400     www      10218:     return $result;
                   10219: }
                   10220: 
                   10221: sub process_clicker_file {
1.608     www      10222:     my ($r,$symb)=@_;
1.400     www      10223:     if (!$symb) {return '';}
1.413     www      10224: 
                   10225:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10226:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10227:                                               \%Saveable_Parameters);
1.598     www      10228:     my $result='';
1.404     www      10229:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10230: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10231: 	return $result;
1.404     www      10232:     }
1.522     www      10233:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10234:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10235:         return $result;
1.521     www      10236:     }
1.522     www      10237:     my $foundgiven=0;
1.521     www      10238:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10239:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10240:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10241:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10242:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10243:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10244:         $foundgiven=$#answers+1;
1.521     www      10245:     }
1.407     albertel 10246:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10247:     my %correct_ids;
1.404     www      10248:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10249: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10250:     }
                   10251:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10252: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10253: 	   $correct_id=~tr/a-z/A-Z/;
                   10254: 	   $correct_id=~s/\s//gs;
                   10255: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10256:            $correct_id=~s/[\-\:]//g;
1.414     www      10257:            if ($correct_id) {
                   10258: 	      $correct_ids{$correct_id}='specified';
                   10259:            }
                   10260:         }
1.400     www      10261:     }
1.404     www      10262:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10263: 	$result.=&mt('Score based on attendance only');
1.521     www      10264:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10265:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10266:     } else {
1.408     albertel 10267: 	my $number=0;
1.411     www      10268: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10269: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10270: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10271: 	    if ($correct_ids{$id} eq 'specified') {
                   10272: 		$result.=&mt('specified');
                   10273: 	    } else {
                   10274: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10275: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10276: 	    }
                   10277: 	    $number++;
                   10278: 	}
1.411     www      10279:         $result.="</p>\n";
1.710     bisitz   10280:         if ($number==0) {
                   10281:             $result .=
                   10282:                  &Apache::lonhtmlcommon::confirm_success(
                   10283:                      &mt('No IDs found to determine correct answer'),1);
                   10284:             return $result;
                   10285:         }
1.404     www      10286:     }
1.405     www      10287:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10288:         $result .=
                   10289:             &Apache::lonhtmlcommon::confirm_success(
                   10290:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10291:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10292:         return $result;
1.405     www      10293:     }
1.410     www      10294: 
                   10295: # Were able to get all the info needed, now analyze the file
                   10296: 
1.411     www      10297:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10298:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10299:     $result.=&Apache::loncommon::start_data_table().
                   10300:              &Apache::loncommon::start_data_table_header_row().
                   10301:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10302:              &Apache::loncommon::end_data_table_header_row().
                   10303:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10304: <td>
1.410     www      10305: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10306: <input type="hidden" name="symb" value="$symb" />
                   10307: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10308: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10309: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10310: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10311: ENDHEADER
1.522     www      10312:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10313:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10314:     } 
1.408     albertel 10315:     my %responses;
                   10316:     my @questiontitles;
1.405     www      10317:     my $errormsg='';
                   10318:     my $number=0;
                   10319:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10320: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10321:     }
1.419     www      10322:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10323:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10324:     }
1.666     www      10325:     if ($env{'form.upfiletype'} eq 'turning') {
                   10326:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10327:     }
1.411     www      10328:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10329:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10330:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10331:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10332:              '<br />';
1.522     www      10333:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10334:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10335:        return $result;
1.522     www      10336:     } 
1.414     www      10337: # Remember Question Titles
                   10338: # FIXME: Possibly need delimiter other than ":"
                   10339:     for (my $i=0;$i<$number;$i++) {
                   10340:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10341:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10342:     }
1.411     www      10343:     my $correct_count=0;
                   10344:     my $student_count=0;
                   10345:     my $unknown_count=0;
1.414     www      10346: # Match answers with usernames
                   10347: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10348:     foreach my $id (keys(%responses)) {
1.410     www      10349:        if ($correct_ids{$id}) {
1.414     www      10350:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10351:           $correct_count++;
1.410     www      10352:        } elsif ($clicker_ids{$id}) {
1.437     www      10353:           if ($clicker_ids{$id}=~/\,/) {
                   10354: # More than one user with the same clicker!
1.632     www      10355:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10356:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10357:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10358:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10359:                            "<select name='multi".$id."'>";
                   10360:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10361:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10362:              }
                   10363:              $result.='</select>';
                   10364:              $unknown_count++;
                   10365:           } else {
                   10366: # Good: found one and only one user with the right clicker
                   10367:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10368:              $student_count++;
                   10369:           }
1.410     www      10370:        } else {
1.632     www      10371:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10372:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10373:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10374:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10375:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10376:                    "\n".&mt("Domain").": ".
                   10377:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      10378:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10379:           $unknown_count++;
1.410     www      10380:        }
1.405     www      10381:     }
1.412     www      10382:     $result.='<hr />'.
                   10383:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10384:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10385:        if ($correct_count==0) {
1.696     bisitz   10386:           $errormsg.="Found no correct answers for grading!";
1.412     www      10387:        } elsif ($correct_count>1) {
1.414     www      10388:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10389:        }
                   10390:     }
1.428     www      10391:     if ($number<1) {
                   10392:        $errormsg.="Found no questions.";
                   10393:     }
1.412     www      10394:     if ($errormsg) {
                   10395:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10396:     } else {
                   10397:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10398:     }
1.632     www      10399:     $result.='</form></td>'.
                   10400:              &Apache::loncommon::end_data_table_row().
                   10401:              &Apache::loncommon::end_data_table();
1.614     www      10402:     return $result;
1.400     www      10403: }
                   10404: 
1.405     www      10405: sub iclicker_eval {
1.406     www      10406:     my ($questiontitles,$responses)=@_;
1.405     www      10407:     my $number=0;
                   10408:     my $errormsg='';
                   10409:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10410:         my %components=&Apache::loncommon::record_sep($line);
                   10411:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10412: 	if ($entries[0] eq 'Question') {
                   10413: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10414: 		$$questiontitles[$number]=$entries[$i];
                   10415: 		$number++;
                   10416: 	    }
                   10417: 	}
                   10418: 	if ($entries[0]=~/^\#/) {
                   10419: 	    my $id=$entries[0];
                   10420: 	    my @idresponses;
                   10421: 	    $id=~s/^[\#0]+//;
                   10422: 	    for (my $i=0;$i<$number;$i++) {
                   10423: 		my $idx=3+$i*6;
1.644     www      10424:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10425: 		push(@idresponses,$entries[$idx]);
                   10426: 	    }
                   10427: 	    $$responses{$id}=join(',',@idresponses);
                   10428: 	}
1.405     www      10429:     }
                   10430:     return ($errormsg,$number);
                   10431: }
                   10432: 
1.419     www      10433: sub interwrite_eval {
                   10434:     my ($questiontitles,$responses)=@_;
                   10435:     my $number=0;
                   10436:     my $errormsg='';
1.420     www      10437:     my $skipline=1;
                   10438:     my $questionnumber=0;
                   10439:     my %idresponses=();
1.419     www      10440:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10441:         my %components=&Apache::loncommon::record_sep($line);
                   10442:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10443:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10444:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10445:         next if $skipline;
                   10446:         if ($entries[0]!=$questionnumber) {
                   10447:            $questionnumber=$entries[0];
                   10448:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10449:            $number++;
1.419     www      10450:         }
1.420     www      10451:         my $id=$entries[4];
                   10452:         $id=~s/^[\#0]+//;
1.421     www      10453:         $id=~s/^v\d*\://i;
                   10454:         $id=~s/[\-\:]//g;
1.420     www      10455:         $idresponses{$id}[$number]=$entries[6];
                   10456:     }
1.524     raeburn  10457:     foreach my $id (keys(%idresponses)) {
1.420     www      10458:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10459:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10460:     }
                   10461:     return ($errormsg,$number);
                   10462: }
                   10463: 
1.666     www      10464: sub turning_eval {
                   10465:     my ($questiontitles,$responses)=@_;
                   10466:     my $number=0;
                   10467:     my $errormsg='';
                   10468:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10469:         my %components=&Apache::loncommon::record_sep($line);
                   10470:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10471:         if ($#entries>$number) { $number=$#entries; }
                   10472:         my $id=$entries[0];
                   10473:         my @idresponses;
                   10474:         $id=~s/^[\#0]+//;
                   10475:         unless ($id) { next; }
                   10476:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10477:             $entries[$idx]=~s/\,/\;/g;
                   10478:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10479:             push(@idresponses,$entries[$idx]);
                   10480:         }
                   10481:         $$responses{$id}=join(',',@idresponses);
                   10482:     }
                   10483:     for (my $i=1; $i<=$number; $i++) {
                   10484:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10485:     }
                   10486:     return ($errormsg,$number);
                   10487: }
                   10488: 
                   10489: 
1.414     www      10490: sub assign_clicker_grades {
1.608     www      10491:     my ($r,$symb)=@_;
1.414     www      10492:     if (!$symb) {return '';}
1.416     www      10493: # See which part we are saving to
1.582     raeburn  10494:     my $res_error;
                   10495:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10496:     if ($res_error) {
                   10497:         return &navmap_errormsg();
                   10498:     }
1.416     www      10499: # FIXME: This should probably look for the first handgradeable part
                   10500:     my $part=$$partlist[0];
                   10501: # Start screen output
1.632     www      10502:     my $result=&Apache::loncommon::start_data_table().
                   10503:              &Apache::loncommon::start_data_table_header_row().
                   10504:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10505:              &Apache::loncommon::end_data_table_header_row().
                   10506:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10507: # Get correct result
                   10508: # FIXME: Possibly need delimiter other than ":"
                   10509:     my @correct=();
1.415     www      10510:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10511:     my $number=$env{'form.number'};
                   10512:     if ($gradingmechanism ne 'attendance') {
1.414     www      10513:        foreach my $key (keys(%env)) {
                   10514:           if ($key=~/^form\.correct\:/) {
                   10515:              my @input=split(/\,/,$env{$key});
                   10516:              for (my $i=0;$i<=$#input;$i++) {
                   10517:                  if (($correct[$i]) && ($input[$i]) &&
                   10518:                      ($correct[$i] ne $input[$i])) {
                   10519:                     $result.='<br /><span class="LC_warning">'.
                   10520:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10521:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10522:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10523:                     $correct[$i]=$input[$i];
                   10524:                  }
                   10525:              }
                   10526:           }
                   10527:        }
1.415     www      10528:        for (my $i=0;$i<$number;$i++) {
1.644     www      10529:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10530:              $result.='<br /><span class="LC_error">'.
                   10531:                       &mt('No correct result given for question "[_1]"!',
                   10532:                           $env{'form.question:'.$i}).'</span>';
                   10533:           }
                   10534:        }
1.644     www      10535:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10536:     }
                   10537: # Start grading
1.415     www      10538:     my $pcorrect=$env{'form.pcorrect'};
                   10539:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10540:     my $storecount=0;
1.632     www      10541:     my %users=();
1.415     www      10542:     foreach my $key (keys(%env)) {
1.420     www      10543:        my $user='';
1.415     www      10544:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10545:           $user=$1;
                   10546:        }
                   10547:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10548:           my $id=$1;
                   10549:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10550:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10551:           } elsif ($env{'form.multi'.$id}) {
                   10552:              $user=$env{'form.multi'.$id};
1.420     www      10553:           }
                   10554:        }
1.632     www      10555:        if ($user) {
                   10556:           if ($users{$user}) {
                   10557:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10558:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10559:                       '</span><br />';
                   10560:           }
                   10561:           $users{$user}=1; 
1.415     www      10562:           my @answer=split(/\,/,$env{$key});
                   10563:           my $sum=0;
1.522     www      10564:           my $realnumber=$number;
1.415     www      10565:           for (my $i=0;$i<$number;$i++) {
1.576     www      10566:              if  ($correct[$i] eq '-') {
                   10567:                 $realnumber--;
1.644     www      10568:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10569:                 if ($gradingmechanism eq 'attendance') {
                   10570:                    $sum+=$pcorrect;
1.576     www      10571:                 } elsif ($correct[$i] eq '*') {
1.522     www      10572:                    $sum+=$pcorrect;
1.415     www      10573:                 } else {
1.644     www      10574: # We actually grade if correct or not
                   10575:                    my $increment=$pincorrect;
                   10576: # Special case: numerical answer "0"
                   10577:                    if ($correct[$i] eq '0') {
                   10578:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10579:                          $increment=$pcorrect;
                   10580:                       }
                   10581: # General numerical answer, both evaluate to something non-zero
                   10582:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10583:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10584:                          $increment=$pcorrect;
                   10585:                       }
                   10586: # Must be just alphanumeric
                   10587:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10588:                       $increment=$pcorrect;
1.415     www      10589:                    }
1.644     www      10590:                    $sum+=$increment;
1.415     www      10591:                 }
                   10592:              }
                   10593:           }
1.522     www      10594:           my $ave=$sum/(100*$realnumber);
1.416     www      10595: # Store
                   10596:           my ($username,$domain)=split(/\:/,$user);
                   10597:           my %grades=();
                   10598:           $grades{"resource.$part.solved"}='correct_by_override';
                   10599:           $grades{"resource.$part.awarded"}=$ave;
                   10600:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10601:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10602:                                                  $env{'request.course.id'},
                   10603:                                                  $domain,$username);
                   10604:           if ($returncode ne 'ok') {
                   10605:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10606:           } else {
                   10607:              $storecount++;
                   10608:           }
1.415     www      10609:        }
                   10610:     }
                   10611: # We are done
1.549     hauer    10612:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10613:              '</td>'.
                   10614:              &Apache::loncommon::end_data_table_row().
                   10615:              &Apache::loncommon::end_data_table();
1.614     www      10616:     return $result;
1.414     www      10617: }
                   10618: 
1.582     raeburn  10619: sub navmap_errormsg {
                   10620:     return '<div class="LC_error">'.
                   10621:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10622:            &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  10623:            '</div>';
                   10624: }
1.607     droeschl 10625: 
1.609     www      10626: sub startpage {
1.671     raeburn  10627:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10628:     if ($nomenu) {
                   10629:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10630:     } else {
                   10631:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10632:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10633:                                                  {'bread_crumbs' => $crumbs}));
                   10634:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10635:     }
1.613     www      10636:     unless ($nodisplayflag) {
1.671     raeburn  10637:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10638:     }
1.607     droeschl 10639: }
1.582     raeburn  10640: 
1.622     www      10641: sub select_problem {
                   10642:     my ($r)=@_;
1.632     www      10643:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.745     raeburn  10644:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
1.622     www      10645:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10646:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10647: }
                   10648: 
1.1       albertel 10649: sub handler {
1.41      ng       10650:     my $request=$_[0];
1.434     albertel 10651:     &reset_caches();
1.646     raeburn  10652:     if ($request->header_only) {
                   10653:         &Apache::loncommon::content_type($request,'text/html');
                   10654:         $request->send_http_header;
                   10655:         return OK;
                   10656:     }
                   10657:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10658: 
1.664     raeburn  10659: # see what command we need to execute
                   10660: 
                   10661:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10662:     my $command=$commands[0];
                   10663: 
1.646     raeburn  10664:     &init_perm();
                   10665:     if (!$env{'request.course.id'}) {
1.664     raeburn  10666:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10667:                 ($command =~ /^scantronupload/)) {
                   10668:             # Not in a course.
                   10669:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10670:             return HTTP_NOT_ACCEPTABLE;
                   10671:         }
1.646     raeburn  10672:     } elsif (!%perm) {
                   10673:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10674:         return OK;
1.41      ng       10675:     }
1.646     raeburn  10676:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10677:     $request->send_http_header;
1.646     raeburn  10678: 
1.160     albertel 10679:     if ($#commands > 0) {
                   10680: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10681:     }
1.608     www      10682: 
                   10683: # see what the symb is
                   10684: 
                   10685:     my $symb=$env{'form.symb'};
                   10686:     unless ($symb) {
                   10687:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10688:        $symb=&Apache::lonnet::symbread($url);
                   10689:     }
1.646     raeburn  10690:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10691: 
1.513     foxr     10692:     $ssi_error = 0;
1.637     www      10693:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10694: #
1.637     www      10695: # Not called from a resource, but inside a course
1.601     www      10696: #    
1.622     www      10697:         &startpage($request,undef,[],1,1);
                   10698:         &select_problem($request);
1.41      ng       10699:     } else {
1.104     albertel 10700: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10701:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10702:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10703:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10704:                     &choose_task_version_form($symb,$env{'form.student'},
                   10705:                                               $env{'form.userdom'});
                   10706:             }
                   10707:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10708:             if ($versionform) {
                   10709:                 $request->print($versionform);
                   10710:             }
                   10711:             $request->print('<br clear="all" />');
1.611     www      10712: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10713:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10714:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10715:                 &choose_task_version_form($symb,$env{'form.student'},
                   10716:                                           $env{'form.userdom'},
                   10717:                                           $env{'form.inhibitmenu'});
                   10718:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10719:             if ($versionform) {
                   10720:                 $request->print($versionform);
                   10721:             }
                   10722:             $request->print('<br clear="all" />');
                   10723:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10724: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10725:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10726:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10727: 	    &pickStudentPage($request,$symb);
1.103     albertel 10728: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10729:             &startpage($request,$symb,
                   10730:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10731:                                        {href=>'',text=>'Select student'},
                   10732:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10733: 	    &displayPage($request,$symb);
1.104     albertel 10734: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10735:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10736:                                        {href=>'',text=>'Select student'},
                   10737:                                        {href=>'',text=>'Grade student'},
                   10738:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10739: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10740: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10741:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10742:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10743: 	    &processGroup($request,$symb);
1.104     albertel 10744: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10745:             &startpage($request,$symb);
                   10746: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10747: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10748:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10749: 	    $request->print(&submit_options($request,$symb));
1.598     www      10750:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10751:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10752:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10753:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10754:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10755:             $request->print(&submit_options_table($request,$symb));
1.598     www      10756:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10757:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10758:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10759: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10760:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10761: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10762: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10763:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10764:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10765: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10766: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10767:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10768:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10769:                                                                              text=>"Modify grades"},
                   10770:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10771: 	    $request->print(&editgrades($request,$symb));
1.602     www      10772:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10773:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10774:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10775: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10776:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10777:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10778: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10779:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10780:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10781:             $request->print(&process_clicker($request,$symb));
1.400     www      10782:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10783:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10784:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10785:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10786:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10787:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10788:                                        {href=>'', text=>'Process clicker file'},
                   10789:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10790:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10791: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10792:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10793: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10794: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10795:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10796: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10797: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10798:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10799: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10800: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10801: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10802:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10803: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10804: 	    } else {
1.257     albertel 10805: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10806: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10807: 		} else {
1.257     albertel 10808: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10809: 		}
1.627     www      10810:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10811: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10812: 	    }
1.246     albertel 10813: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10814:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10815: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10816: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10817:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10818: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10819:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10820:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10821:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10822: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10823:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10824: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10825: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10826:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10827: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10828:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10829:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10830: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10831:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10832:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10833:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10834:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10835: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10836:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10837:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10838:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10839: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10840:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10841:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10842:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10843:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10844:             $request->print(&checkscantron_results($request,$symb));
                   10845:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10846:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10847:             $request->print(&submit_options_download($request,$symb));
                   10848:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10849:             &startpage($request,$symb,
                   10850:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.750   ! raeburn  10851:     {href=>'', text=>'Download submitted files'}]);
1.621     www      10852:             &submit_download_link($request,$symb);
1.106     albertel 10853: 	} elsif ($command) {
1.620     www      10854:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10855: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10856: 	}
1.2       albertel 10857:     }
1.513     foxr     10858:     if ($ssi_error) {
                   10859: 	&ssi_print_error($request);
                   10860:     }
1.671     raeburn  10861:     if ($env{'form.inhibitmenu'}) {
                   10862:         $request->print(&Apache::loncommon::end_page());
                   10863:     } else {
                   10864:         &Apache::lonquickgrades::endGradeScreen($request);
                   10865:     }
1.434     albertel 10866:     &reset_caches();
1.646     raeburn  10867:     return OK;
1.44      ng       10868: }
                   10869: 
1.1       albertel 10870: 1;
                   10871: 
1.13      albertel 10872: __END__;
1.531     jms      10873: 
                   10874: 
                   10875: =head1 NAME
                   10876: 
                   10877: Apache::grades
                   10878: 
                   10879: =head1 SYNOPSIS
                   10880: 
                   10881: Handles the viewing of grades.
                   10882: 
                   10883: This is part of the LearningOnline Network with CAPA project
                   10884: described at http://www.lon-capa.org.
                   10885: 
                   10886: =head1 OVERVIEW
                   10887: 
                   10888: Do an ssi with retries:
1.715     bisitz   10889: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10890: 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
                   10891: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10892: 
                   10893: At least the logic that drives this has been pulled out into loncommon.
                   10894: 
                   10895: 
                   10896: 
                   10897: ssi_with_retries - Does the server side include of a resource.
                   10898:                      if the ssi call returns an error we'll retry it up to
                   10899:                      the number of times requested by the caller.
1.715     bisitz   10900:                      If we still have a problem, no text is appended to the
1.531     jms      10901:                      output and we set some global variables.
                   10902:                      to indicate to the caller an SSI error occurred.  
                   10903:                      All of this is supposed to deal with the issues described
1.715     bisitz   10904:                      in LON-CAPA BZ 5631 see:
1.531     jms      10905:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10906:                      by informing the user that this happened.
                   10907: 
                   10908: Parameters:
                   10909:   resource   - The resource to include.  This is passed directly, without
                   10910:                interpretation to lonnet::ssi.
                   10911:   form       - The form hash parameters that guide the interpretation of the resource
                   10912:                
                   10913:   retries    - Number of retries allowed before giving up completely.
                   10914: Returns:
                   10915:   On success, returns the rendered resource identified by the resource parameter.
                   10916: Side Effects:
                   10917:   The following global variables can be set:
                   10918:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10919:                               It is up to the caller to initialize this to false
                   10920:                               if desired.
                   10921:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10922:                               of the resource that could not be rendered by the ssi
                   10923:                               call.
                   10924:    ssi_error_message   - The error string fetched from the ssi response
                   10925:                               in the event of an error.
                   10926: 
                   10927: 
                   10928: =head1 HANDLER SUBROUTINE
                   10929: 
                   10930: ssi_with_retries()
                   10931: 
                   10932: =head1 SUBROUTINES
                   10933: 
                   10934: =over
                   10935: 
1.671     raeburn  10936: =head1 Routines to display previous version of a Task for a specific student
                   10937: 
                   10938: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10939: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10940: requires a proctor to check-in the student, a new version of the Task will
                   10941: be created when the student is checked in to the new opportunity.
                   10942: 
                   10943: If a particular student has tried two or more versions of a particular task,
                   10944: the submission screen provides a user with vgr privileges (e.g., a Course
                   10945: Coordinator) the ability to display a previous version worked on by the
                   10946: student.  By default, the current version is displayed. If a previous version
                   10947: has been selected for display, submission data are only shown that pertain
                   10948: to that particular version, and the interface to submit grades is not shown.
                   10949: 
                   10950: =over 4
                   10951: 
                   10952: =item show_previous_task_version()
                   10953: 
                   10954: Displays a specified version of a student's Task, as the student sees it.
                   10955: 
                   10956: Inputs: 2
                   10957:         request - request object
                   10958:         symb    - unique symb for current instance of resource
                   10959: 
                   10960: Output: None.
                   10961: 
                   10962: Side Effects: calls &show_problem() to print version of Task, with
                   10963:               version contained in form item: $env{'form.previousversion'}
                   10964: 
                   10965: =item choose_task_version_form()
                   10966: 
                   10967: Displays a web form used to select which version of a student's view of a
                   10968: Task should be displayed.  Either launches a pop-up window, or replaces
                   10969: content in existing pop-up, or replaces page in main window.
                   10970: 
                   10971: Inputs: 4
                   10972:         symb    - unique symb for current instance of resource
                   10973:         uname   - username of student
                   10974:         udom    - domain of student
                   10975:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10976:                   breadcrumbs etc., are displayed
                   10977: 
                   10978: Output: 4
                   10979:         current   - student's current version
                   10980:         displayed - student's version being displayed
                   10981:         result    - scalar containing HTML for web form used to switch to
                   10982:                     a different version (or a link to close window, if pop-up).
                   10983:         js        - javascript for processing selection in versions web form
                   10984: 
                   10985: Side Effects: None.
                   10986: 
                   10987: =item previous_display_javascript()
                   10988: 
                   10989: Inputs: 2
                   10990:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10991:                   breadcrumbs etc., are displayed.
                   10992:         current - student's current version number.
                   10993: 
                   10994: Output: 1
                   10995:         js      - javascript for processing selection in versions web form.
                   10996: 
                   10997: Side Effects: None.
                   10998: 
                   10999: =back
                   11000: 
                   11001: =head1 Routines to process bubblesheet data.
                   11002: 
                   11003: =over 4
                   11004: 
1.531     jms      11005: =item scantron_get_correction() : 
                   11006: 
                   11007:    Builds the interface screen to interact with the operator to fix a
                   11008:    specific error condition in a specific scanline
                   11009: 
                   11010:  Arguments:
                   11011:     $r           - Apache request object
                   11012:     $i           - number of the current scanline
                   11013:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   11014:     $scan_config - hash ref as returned from &get_scantron_config()
                   11015:     $line        - full contents of the current scanline
                   11016:     $error       - error condition, valid values are
                   11017:                    'incorrectCODE', 'duplicateCODE',
                   11018:                    'doublebubble', 'missingbubble',
                   11019:                    'duplicateID', 'incorrectID'
                   11020:     $arg         - extra information needed
                   11021:        For errors:
                   11022:          - duplicateID   - paper number that this studentID was seen before on
                   11023:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11024:                            seen on before
                   11025:          - incorrectCODE - current incorrect CODE 
                   11026:          - doublebubble  - array ref of the bubble lines that have double
                   11027:                            bubble errors
                   11028:          - missingbubble - array ref of the bubble lines that have missing
                   11029:                            bubble errors
                   11030: 
1.691     raeburn  11031:    $randomorder - True if exam folder has randomorder set
                   11032:    $randompick  - True if exam folder has randompick set
                   11033:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11034:                      for current line to question number used for same question
                   11035:                      in "Master Seqence" (as seen by Course Coordinator).
                   11036:    $startline   - Reference to hash where key is question number (0 is first)
                   11037:                   and value is number of first bubble line for current student
                   11038:                   or code-based randompick and/or randomorder.
                   11039: 
                   11040: 
                   11041: 
1.531     jms      11042: =item  scantron_get_maxbubble() : 
                   11043: 
1.582     raeburn  11044:    Arguments:
                   11045:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11046:                       failure to retrieve a navmap object.
                   11047:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11048:        calling routine should trap the error condition and display the warning
                   11049:        found in &navmap_errormsg().
                   11050: 
1.649     raeburn  11051:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11052: 
1.531     jms      11053:    Returns the maximum number of bubble lines that are expected to
                   11054:    occur. Does this by walking the selected sequence rendering the
                   11055:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11056:    for what the current value of the problem counter is.
                   11057: 
                   11058:    Caches the results to $env{'form.scantron_maxbubble'},
                   11059:    $env{'form.scantron.bubble_lines.n'}, 
                   11060:    $env{'form.scantron.first_bubble_line.n'} and
                   11061:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11062:    which are the total number of bubble lines, the number of bubble
1.531     jms      11063:    lines for response n and number of the first bubble line for response n,
                   11064:    and a comma separated list of numbers of bubble lines for sub-questions
                   11065:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11066: 
                   11067: 
                   11068: =item  scantron_validate_missingbubbles() : 
                   11069: 
                   11070:    Validates all scanlines in the selected file to not have any
                   11071:     answers that don't have bubbles that have not been verified
                   11072:     to be bubble free.
                   11073: 
                   11074: =item  scantron_process_students() : 
                   11075: 
1.659     raeburn  11076:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11077: 
                   11078:    The parsed scanline hash is added to %env 
                   11079: 
                   11080:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11081:    foreach resource , with the form data of
                   11082: 
                   11083: 	'submitted'     =>'scantron' 
                   11084: 	'grade_target'  =>'grade',
                   11085: 	'grade_username'=> username of student
                   11086: 	'grade_domain'  => domain of student
                   11087: 	'grade_courseid'=> of course
                   11088: 	'grade_symb'    => symb of resource to grade
                   11089: 
                   11090:     This triggers a grading pass. The problem grading code takes care
                   11091:     of converting the bubbled letter information (now in %env) into a
                   11092:     valid submission.
                   11093: 
                   11094: =item  scantron_upload_scantron_data() :
                   11095: 
1.659     raeburn  11096:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11097: 
                   11098: =item  scantron_upload_scantron_data_save() : 
                   11099: 
                   11100:    Adds a provided bubble information data file to the course if user
                   11101:    has the correct privileges to do so. 
                   11102: 
                   11103: =item  valid_file() :
                   11104: 
                   11105:    Validates that the requested bubble data file exists in the course.
                   11106: 
                   11107: =item  scantron_download_scantron_data() : 
                   11108: 
                   11109:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11110:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11111:    course.
                   11112: 
                   11113: =item  scantron_validate_ID() : 
                   11114: 
                   11115:    Validates all scanlines in the selected file to not have any
1.556     weissno  11116:    invalid or underspecified student/employee IDs
1.531     jms      11117: 
1.582     raeburn  11118: =item navmap_errormsg() :
                   11119: 
                   11120:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11121:    Should be called whenever the request to instantiate a navmap object fails.
                   11122: 
                   11123: =back
1.582     raeburn  11124: 
1.531     jms      11125: =back
                   11126: 
                   11127: =cut

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