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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.751   ! raeburn     4: # $Id: grades.pm,v 1.750 2018/05/04 15:15:05 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.751   ! raeburn   420:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     421: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     422: 
1.268     albertel  423:     } elsif ( $response eq 'organic') {
1.721     bisitz    424:         my $result=&mt('Smile representation: [_1]',
                    425:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  426: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    427: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    428: 	return $result;
1.335     albertel  429:     } elsif ( $response eq 'Task') {
                    430: 	if ( $answer eq 'SUBMITTED') {
                    431: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  432: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  433: 	    return $result;
                    434: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    435: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    436: 			       keys(%{$record}));
                    437: 	    return join('<br />',($version,@matches));
                    438: 			       
                    439: 			       
                    440: 	} else {
                    441: 	    my $result =
                    442: 		'<p>'
                    443: 		.&mt('Overall result: [_1]',
                    444: 		     $record->{$version."resource.$respid.$partid.status"})
                    445: 		.'</p>';
                    446: 	    
                    447: 	    $result .= '<ul>';
                    448: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    449: 			     keys(%{$record}));
                    450: 	    foreach my $grade (sort(@grade)) {
                    451: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    452: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    453: 				     $dim, $record->{$grade}).
                    454: 			  '</li>';
                    455: 	    }
                    456: 	    $result.='</ul>';
                    457: 	    return $result;
                    458: 	}
1.716     bisitz    459:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    460:         # Respect multiple input fields, see Bug #5409
1.440     albertel  461: 	$answer = 
                    462: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    463: 							      $answer);
1.720     kruse     464: 	return $answer;
1.122     ng        465:     }
1.720     kruse     466:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        467: }
                    468: 
                    469: #-- A couple of common js functions
                    470: sub commonJSfunctions {
                    471:     my $request = shift;
1.597     wenzelju  472:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        473:     function radioSelection(radioButton) {
                    474: 	var selection=null;
                    475: 	if (radioButton.length > 1) {
                    476: 	    for (var i=0; i<radioButton.length; i++) {
                    477: 		if (radioButton[i].checked) {
                    478: 		    return radioButton[i].value;
                    479: 		}
                    480: 	    }
                    481: 	} else {
                    482: 	    if (radioButton.checked) return radioButton.value;
                    483: 	}
                    484: 	return selection;
                    485:     }
                    486: 
                    487:     function pullDownSelection(selectOne) {
                    488: 	var selection="";
                    489: 	if (selectOne.length > 1) {
                    490: 	    for (var i=0; i<selectOne.length; i++) {
                    491: 		if (selectOne[i].selected) {
                    492: 		    return selectOne[i].value;
                    493: 		}
                    494: 	    }
                    495: 	} else {
1.138     albertel  496:             // only one value it must be the selected one
                    497: 	    return selectOne.value;
1.118     ng        498: 	}
                    499:     }
                    500: COMMONJSFUNCTIONS
                    501: }
                    502: 
1.44      ng        503: #--- Dumps the class list with usernames,list of sections,
                    504: #--- section, ids and fullnames for each user.
                    505: sub getclasslist {
1.750     raeburn   506:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  507:     my @getsec;
1.450     banghart  508:     my @getgroup;
1.442     banghart  509:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  510:     if (!ref($getsec)) {
                    511: 	if ($getsec ne '' && $getsec ne 'all') {
                    512: 	    @getsec=($getsec);
                    513: 	}
                    514:     } else {
                    515: 	@getsec=@{$getsec};
                    516:     }
                    517:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  518:     if (!ref($getgroup)) {
                    519: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    520: 	    @getgroup=($getgroup);
                    521: 	}
                    522:     } else {
                    523: 	@getgroup=@{$getgroup};
                    524:     }
                    525:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  526: 
1.449     banghart  527:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  528:     # Bail out if we were unable to get the classlist
1.56      matthew   529:     return if (! defined($classlist));
1.449     banghart  530:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   531:     #
                    532:     my %sections;
                    533:     my %fullnames;
1.750     raeburn   534:     my ($cdom,$cnum,$partlist);
                    535:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    536:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    537:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    538:         my $res_error;
                    539:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
                    540:     }
1.205     matthew   541:     foreach my $student (keys(%$classlist)) {
                    542:         my $end      = 
                    543:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    544:         my $start    = 
                    545:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    546:         my $id       = 
                    547:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    548:         my $section  = 
                    549:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    550:         my $fullname = 
                    551:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    552:         my $status   = 
                    553:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  554:         my $group   = 
                    555:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        556: 	# filter students according to status selected
1.750     raeburn   557: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  558: 	    if (!($stu_status =~ $status)) {
1.450     banghart  559: 		delete($classlist->{$student});
1.76      ng        560: 		next;
                    561: 	    }
                    562: 	}
1.450     banghart  563: 	# filter students according to groups selected
1.453     banghart  564: 	my @stu_groups = split(/,/,$group);
1.450     banghart  565: 	if (@getgroup) {
                    566: 	    my $exclude = 1;
1.454     banghart  567: 	    foreach my $grp (@getgroup) {
                    568: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  569: 	            if ($stu_group eq $grp) {
                    570: 	                $exclude = 0;
                    571:     	            } 
1.450     banghart  572: 	        }
1.453     banghart  573:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   574:         	    $exclude = 0;
1.453     banghart  575:         	}
1.450     banghart  576: 	    }
                    577: 	    if ($exclude) {
                    578: 	        delete($classlist->{$student});
1.750     raeburn   579: 		next;
1.450     banghart  580: 	    }
                    581: 	}
1.750     raeburn   582:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    583:             my $udom =
                    584:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    585:             my $uname =
                    586:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    587:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    588:                 if ($submitonly eq 'queued') {
                    589:                     my %queue_status =
                    590:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    591:                                                                 $udom,$uname);
                    592:                     if (!defined($queue_status{'gradingqueue'})) {
                    593:                         delete($classlist->{$student});
                    594:                         next;
                    595:                     }
                    596:                 } else {
                    597:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    598:                     my $submitted = 0;
                    599:                     my $graded = 0;
                    600:                     my $incorrect = 0;
                    601:                     foreach (keys(%status)) {
                    602:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    603:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    604:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    605: 
                    606:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    607:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    608:                             $submitted = 0;
                    609:                         }
                    610:                     }
                    611:                     if (!$submitted && ($submitonly eq 'yes' ||
                    612:                                         $submitonly eq 'incorrect' ||
                    613:                                         $submitonly eq 'graded')) {
                    614:                         delete($classlist->{$student});
                    615:                         next;
                    616:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    617:                         delete($classlist->{$student});
                    618:                         next;
                    619:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    620:                         delete($classlist->{$student});
                    621:                         next;
                    622:                     }
                    623:                 }
                    624:             }
                    625:         }
1.205     matthew   626: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  627: 	if (&canview($section)) {
1.291     albertel  628: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  629: 		$sections{$section}++;
1.450     banghart  630: 		if ($classlist->{$student}) {
                    631: 		    $fullnames{$student}=$fullname;
                    632: 		}
1.103     albertel  633: 	    } else {
1.205     matthew   634: 		delete($classlist->{$student});
1.103     albertel  635: 	    }
                    636: 	} else {
1.205     matthew   637: 	    delete($classlist->{$student});
1.103     albertel  638: 	}
1.44      ng        639:     }
1.56      matthew   640:     my @sections = sort(keys(%sections));
                    641:     return ($classlist,\@sections,\%fullnames);
1.44      ng        642: }
                    643: 
1.103     albertel  644: sub canmodify {
                    645:     my ($sec)=@_;
                    646:     if ($perm{'mgr'}) {
                    647: 	if (!defined($perm{'mgr_section'})) {
                    648: 	    # can modify whole class
                    649: 	    return 1;
                    650: 	} else {
                    651: 	    if ($sec eq $perm{'mgr_section'}) {
                    652: 		#can modify the requested section
                    653: 		return 1;
                    654: 	    } else {
                    655: 		# can't modify the request section
                    656: 		return 0;
                    657: 	    }
                    658: 	}
                    659:     }
                    660:     #can't modify
                    661:     return 0;
                    662: }
                    663: 
                    664: sub canview {
                    665:     my ($sec)=@_;
                    666:     if ($perm{'vgr'}) {
                    667: 	if (!defined($perm{'vgr_section'})) {
                    668: 	    # can modify whole class
                    669: 	    return 1;
                    670: 	} else {
                    671: 	    if ($sec eq $perm{'vgr_section'}) {
                    672: 		#can modify the requested section
                    673: 		return 1;
                    674: 	    } else {
                    675: 		# can't modify the request section
                    676: 		return 0;
                    677: 	    }
                    678: 	}
                    679:     }
                    680:     #can't modify
                    681:     return 0;
                    682: }
                    683: 
1.44      ng        684: #--- Retrieve the grade status of a student for all the parts
                    685: sub student_gradeStatus {
1.324     albertel  686:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  687:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        688:     my %partstatus = ();
                    689:     foreach (@$partlist) {
1.128     ng        690: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        691: 	$status              = 'nothing' if ($status eq '');
                    692: 	$partstatus{$_}      = $status;
                    693: 	my $subkey           = "resource.$_.submitted_by";
                    694: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    695:     }
                    696:     return %partstatus;
                    697: }
                    698: 
1.45      ng        699: # hidden form and javascript that calls the form
                    700: # Use by verifyscript and viewgrades
                    701: # Shows a student's view of problem and submission
                    702: sub jscriptNform {
1.324     albertel  703:     my ($symb) = @_;
1.442     banghart  704:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  705:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        706: 	'    function viewOneStudent(user,domain) {'."\n".
                    707: 	'	document.onestudent.student.value = user;'."\n".
                    708: 	'	document.onestudent.userdom.value = domain;'."\n".
                    709: 	'	document.onestudent.submit();'."\n".
                    710: 	'    }'."\n".
1.597     wenzelju  711: 	"\n");
1.45      ng        712:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  713: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  714: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        715: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    716: 	'<input type="hidden" name="student" value="" />'."\n".
                    717: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    718: 	'</form>'."\n";
                    719:     return $jscript;
                    720: }
1.39      ng        721: 
1.447     foxr      722: 
                    723: 
1.315     bowersj2  724: # Given the score (as a number [0-1] and the weight) what is the final
                    725: # point value? This function will round to the nearest tenth, third,
                    726: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  727: sub compute_points {
1.315     bowersj2  728:     my ($score, $weight) = @_;
                    729:     
                    730:     my $tolerance = .00001;
                    731:     my $points = $score * $weight;
                    732: 
                    733:     # Check for nearness to 1/x.
                    734:     my $check_for_nearness = sub {
                    735:         my ($factor) = @_;
                    736:         my $num = ($points * $factor) + $tolerance;
                    737:         my $floored_num = floor($num);
1.316     albertel  738:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  739:             return $floored_num / $factor;
                    740:         }
                    741:         return $points;
                    742:     };
                    743: 
                    744:     $points = $check_for_nearness->(10);
                    745:     $points = $check_for_nearness->(3);
                    746:     $points = $check_for_nearness->(4);
                    747:     
                    748:     return $points;
                    749: }
                    750: 
1.44      ng        751: #------------------ End of general use routines --------------------
1.87      www       752: 
                    753: #
                    754: # Find most similar essay
                    755: #
                    756: 
                    757: sub most_similar {
1.674     raeburn   758:     my ($uname,$udom,$symb,$uessay)=@_;
                    759: 
                    760:     unless ($symb) { return ''; }
                    761: 
                    762:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       763: 
                    764: # ignore spaces and punctuation
                    765: 
                    766:     $uessay=~s/\W+/ /gs;
                    767: 
1.282     www       768: # ignore empty submissions (occuring when only files are sent)
                    769: 
1.598     www       770:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       771: 
1.87      www       772: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       773:     my $limit=0.6;
1.87      www       774:     my $sname='';
                    775:     my $sdom='';
                    776:     my $scrsid='';
                    777:     my $sessay='';
                    778: # go through all essays ...
1.674     raeburn   779:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  780: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       781: # ... except the same student
1.426     albertel  782:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   783: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  784: 	$tessay=~s/\W+/ /gs;
1.87      www       785: # String similarity gives up if not even limit
1.426     albertel  786: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       787: # Found one
1.426     albertel  788: 	if ($tsimilar>$limit) {
                    789: 	    $limit=$tsimilar;
                    790: 	    $sname=$tname;
                    791: 	    $sdom=$tdom;
                    792: 	    $scrsid=$tcrsid;
1.674     raeburn   793: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  794: 	}
1.87      www       795:     }
1.88      www       796:     if ($limit>0.6) {
1.87      www       797:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    798:     } else {
                    799:        return ('','','','',0);
                    800:     }
                    801: }
                    802: 
1.44      ng        803: #-------------------------------------------------------------------
                    804: 
                    805: #------------------------------------ Receipt Verification Routines
1.45      ng        806: #
1.602     www       807: 
                    808: sub initialverifyreceipt {
1.608     www       809:    my ($request,$symb) = @_;
1.602     www       810:    &commonJSfunctions($request);
1.694     bisitz    811:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       812:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    813:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       814:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    815:         '<input type="hidden" name="command" value="verify" />'.
                    816:         "</form>\n";
1.602     www       817: }
                    818: 
1.44      ng        819: #--- Check whether a receipt number is valid.---
                    820: sub verifyreceipt {
1.608     www       821:     my ($request,$symb)  = @_;
1.44      ng        822: 
1.257     albertel  823:     my $courseid = $env{'request.course.id'};
1.184     www       824:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  825: 	$env{'form.receipt'};
1.44      ng        826:     $receipt     =~ s/[^\-\d]//g;
                    827: 
1.487     albertel  828:     my $title.=
                    829: 	'<h3><span class="LC_info">'.
1.605     www       830: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    831: 	'</span></h3>'."\n";
1.44      ng        832: 
                    833:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   834:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  835:     
                    836:     my $receiptparts=0;
1.390     albertel  837:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    838: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  839:     my $parts=['0'];
1.582     raeburn   840:     if ($receiptparts) {
                    841:         my $res_error; 
                    842:         ($parts)=&response_type($symb,\$res_error);
                    843:         if ($res_error) {
                    844:             return &navmap_errormsg();
                    845:         } 
                    846:     }
1.486     albertel  847:     
                    848:     my $header = 
                    849: 	&Apache::loncommon::start_data_table().
                    850: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  851: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    852: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    853: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  854:     if ($receiptparts) {
1.487     albertel  855: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  856:     }
                    857:     $header.=
                    858: 	&Apache::loncommon::end_data_table_header_row();
                    859: 
1.294     albertel  860:     foreach (sort 
                    861: 	     {
                    862: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    863: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    864: 		 }
                    865: 		 return $a cmp $b;
                    866: 	     } (keys(%$fullname))) {
1.44      ng        867: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  868: 	foreach my $part (@$parts) {
                    869: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  870: 		$contents.=
                    871: 		    &Apache::loncommon::start_data_table_row().
                    872: 		    '<td>&nbsp;'."\n".
1.177     albertel  873: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  874: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  875: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    876: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    877: 		if ($receiptparts) {
                    878: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    879: 		}
1.486     albertel  880: 		$contents.= 
                    881: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  882: 		
                    883: 		$matches++;
                    884: 	    }
1.44      ng        885: 	}
                    886:     }
                    887:     if ($matches == 0) {
1.584     bisitz    888:         $string = $title
                    889:                  .'<p class="LC_warning">'
                    890:                  .&mt('No match found for the above receipt number.')
                    891:                  .'</p>';
1.44      ng        892:     } else {
1.324     albertel  893: 	$string = &jscriptNform($symb).$title.
1.487     albertel  894: 	    '<p>'.
1.584     bisitz    895: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  896: 	    '</p>'.
1.486     albertel  897: 	    $header.
                    898: 	    $contents.
                    899: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        900:     }
1.614     www       901:     return $string;
1.44      ng        902: }
                    903: 
                    904: #--- This is called by a number of programs.
                    905: #--- Called from the Grading Menu - View/Grade an individual student
                    906: #--- Also called directly when one clicks on the subm button 
                    907: #    on the problem page.
1.30      ng        908: sub listStudents {
1.617     www       909:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  910: 
1.747     raeburn   911:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel  912:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    913:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    914:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  915:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       916:     unless ($submitonly) {
                    917:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    918:     }
1.49      albertel  919: 
1.632     www       920:     my $result='';
1.623     www       921:     my $res_error;
                    922:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  923: 
1.736     damieng   924:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   925: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    926: 		'single'   => 'Please select the student before clicking on the Next button.',
                    927: 	     );
1.736     damieng   928:     &js_escape(\%js_lt);
1.597     wenzelju  929:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        930:     function checkSelect(checkBox) {
                    931: 	var ctr=0;
                    932: 	var sense="";
                    933: 	if (checkBox.length > 1) {
                    934: 	    for (var i=0; i<checkBox.length; i++) {
                    935: 		if (checkBox[i].checked) {
                    936: 		    ctr++;
                    937: 		}
                    938: 	    }
1.736     damieng   939: 	    sense = '$js_lt{'multiple'}';
1.110     ng        940: 	} else {
                    941: 	    if (checkBox.checked) {
                    942: 		ctr = 1;
                    943: 	    }
1.736     damieng   944: 	    sense = '$js_lt{'single'}';
1.110     ng        945: 	}
                    946: 	if (ctr == 0) {
1.485     albertel  947: 	    alert(sense);
1.110     ng        948: 	    return false;
                    949: 	}
                    950: 	document.gradesub.submit();
                    951:     }
                    952: 
                    953:     function reLoadList(formname) {
1.112     ng        954: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        955: 	formname.command.value = 'submission';
                    956: 	formname.submit();
                    957:     }
1.45      ng        958: LISTJAVASCRIPT
                    959: 
1.118     ng        960:     &commonJSfunctions($request);
1.41      ng        961:     $request->print($result);
1.39      ng        962: 
1.154     albertel  963:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       964: 	"\n";
1.485     albertel  965: 	
1.561     bisitz    966:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn   967:     unless ($is_tool) {
                    968:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    969:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    970:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    971:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    972:                       .&Apache::lonhtmlcommon::row_closure();
                    973:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    974:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    975:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    976:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    977:                       .&Apache::lonhtmlcommon::row_closure();
                    978:     }
1.485     albertel  979: 
                    980:     my $submission_options;
1.442     banghart  981:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    982:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  983:     $env{'form.Status'} = $saveStatus;
1.745     raeburn   984:     my %optiontext;
                    985:     if ($is_tool) {
                    986:         %optiontext = &Apache::lonlocal::texthash (
                    987:                           lastonly => 'last transaction',
                    988:                           last     => 'last transaction with details',
                    989:                           datesub  => 'all transactions',
                    990:                           all      => 'all transactions with details',
                    991:                       );
                    992:     } else {
                    993:         %optiontext = &Apache::lonlocal::texthash (
                    994:                           lastonly => 'last submission',
                    995:                           last     => 'last submission with details',
                    996:                           datesub  => 'all submissions',
                    997:                           all      => 'all submissions with details',
                    998:                       );
                    999:     }
1.485     albertel 1000:     $submission_options.=
1.592     bisitz   1001:         '<span class="LC_nobreak">'.
1.624     www      1002:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1003:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1004:         '<span class="LC_nobreak">'.
                   1005:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1006:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1007:         '<span class="LC_nobreak">'.
1.628     www      1008:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1009:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1010:         '<span class="LC_nobreak">'.
                   1011:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1012:         $optiontext{'all'}.'</label></span>';
                   1013:     my $viewtitle;
                   1014:     if ($is_tool) {
                   1015:         $viewtitle = &mt('View Transactions');
                   1016:     } else {
                   1017:         $viewtitle = &mt('View Submissions');
                   1018:     }
                   1019:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1020:                   .$submission_options
                   1021:                   .&Apache::lonhtmlcommon::row_closure();
                   1022: 
1.745     raeburn  1023:     my $closure;
                   1024:     if (($is_tool) && (exists($env{'form.Status'}))) {
                   1025:         $closure = 1;
                   1026:     }
1.561     bisitz   1027:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1028:                   .'<select name="increment">'
                   1029:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1030:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1031:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1032:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1033:                   .'</select>'
1.745     raeburn  1034:                   .&Apache::lonhtmlcommon::row_closure($closure);
1.485     albertel 1035: 
                   1036:     $gradeTable .= 
1.432     banghart 1037:         &build_section_inputs().
1.45      ng       1038: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1039: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1040: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1041: 
1.618     www      1042:     if (exists($env{'form.Status'})) {
1.561     bisitz   1043: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1044:     } else {
1.745     raeburn  1045:         if ($is_tool) {
                   1046:             $closure = 1;
                   1047:         }
1.561     bisitz   1048:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1049:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1050:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1.745     raeburn  1051:                       .&Apache::lonhtmlcommon::row_closure($closure);
1.124     ng       1052:     }
1.112     ng       1053: 
1.745     raeburn  1054:     unless ($is_tool) {
                   1055:         $closure = 1;
                   1056:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1057:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1058:                       .&Apache::lonhtmlcommon::row_closure($closure);
                   1059:     }
                   1060:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
                   1061:     my $regrademsg;
                   1062:     if ($is_tool) {
                   1063:         $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.");
                   1064:     } else {
                   1065:         $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.");
                   1066:     }
1.561     bisitz   1067:     $gradeTable .= '<p>'
1.745     raeburn  1068:                   .$regrademsg."\n"
1.561     bisitz   1069:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1070:                   .'</p>';
1.249     albertel 1071: 
                   1072: # checkall buttons
                   1073:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1074:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1075:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1076:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1077:     $gradeTable.=&check_buttons();
1.450     banghart 1078:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1079:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1080: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1081:     my $loop = 0;
                   1082:     while ($loop < 2) {
1.485     albertel 1083: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1084: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1085: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1086: 	    foreach my $part (sort(@$partlist)) {
                   1087: 		my $display_part=
                   1088: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1089: 		$gradeTable.=
                   1090: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1091: 	    }
1.301     albertel 1092: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1093: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1094: 	}
                   1095: 	$loop++;
1.126     ng       1096: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1097:     }
1.474     albertel 1098:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1099: 
1.45      ng       1100:     my $ctr = 0;
1.294     albertel 1101:     foreach my $student (sort 
                   1102: 			 {
                   1103: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1104: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1105: 			     }
                   1106: 			     return $a cmp $b;
                   1107: 			 }
                   1108: 			 (keys(%$fullname))) {
1.41      ng       1109: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1110: 
1.110     ng       1111: 	my %status = ();
1.301     albertel 1112: 
                   1113: 	if ($submitonly eq 'queued') {
                   1114: 	    my %queue_status = 
                   1115: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1116: 							$udom,$uname);
                   1117: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1118: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1119: 	}
                   1120: 
1.618     www      1121: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1122: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1123: 	    my $submitted = 0;
1.164     albertel 1124: 	    my $graded = 0;
1.248     albertel 1125: 	    my $incorrect = 0;
1.110     ng       1126: 	    foreach (keys(%status)) {
1.145     albertel 1127: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1128: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1129: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1130: 		
1.110     ng       1131: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1132: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1133: 		    $submitted = 0;
1.150     albertel 1134: 		    my ($part)=split(/\./,$partid);
1.110     ng       1135: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1136: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1137: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1138: 		}
1.41      ng       1139: 	    }
1.248     albertel 1140: 	    
1.156     albertel 1141: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1142: 				     $submitonly eq 'incorrect' ||
                   1143: 				     $submitonly eq 'graded'));
1.248     albertel 1144: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1145: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1146: 	}
1.34      ng       1147: 
1.45      ng       1148: 	$ctr++;
1.249     albertel 1149: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1150:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1151: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1152: 	    if ($ctr%2 ==1) {
                   1153: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1154: 	    }
1.126     ng       1155: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1156:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1157:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1158: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1159: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1160: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1161: 
1.618     www      1162: 	    if ($submitonly ne 'all') {
1.524     raeburn  1163: 		foreach (sort(keys(%status))) {
1.485     albertel 1164: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1165: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1166: 		}
1.41      ng       1167: 	    }
1.126     ng       1168: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1169: 	    if ($ctr%2 ==0) {
                   1170: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1171: 	    }
1.41      ng       1172: 	}
                   1173:     }
1.110     ng       1174:     if ($ctr%2 ==1) {
1.126     ng       1175: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1176: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1177: 		foreach (@$partlist) {
                   1178: 		    $gradeTable.='<td>&nbsp;</td>';
                   1179: 		}
1.301     albertel 1180: 	    } elsif ($submitonly eq 'queued') {
                   1181: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1182: 	    }
1.474     albertel 1183: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1184:     }
                   1185: 
1.474     albertel 1186:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1187:         '<input type="button" '.
                   1188:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1189:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1190:     if ($ctr == 0) {
1.96      albertel 1191: 	my $num_students=(scalar(keys(%$fullname)));
                   1192: 	if ($num_students eq 0) {
1.485     albertel 1193: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1194: 	} else {
1.171     albertel 1195: 	    my $submissions='submissions';
                   1196: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1197: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1198: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1199: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1200: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1201: 		    $num_students).
                   1202: 		'</span><br />';
1.96      albertel 1203: 	}
1.46      ng       1204:     } elsif ($ctr == 1) {
1.474     albertel 1205: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1206:     }
                   1207:     $request->print($gradeTable);
1.44      ng       1208:     return '';
1.10      ng       1209: }
                   1210: 
1.44      ng       1211: #---- Called from the listStudents routine
1.249     albertel 1212: 
                   1213: sub check_script {
                   1214:     my ($form, $type)=@_;
1.597     wenzelju 1215:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1216:     function checkall() {
                   1217:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1218:             ele = document.forms.'.$form.'.elements[i];
                   1219:             if (ele.name == "'.$type.'") {
                   1220:             document.forms.'.$form.'.elements[i].checked=true;
                   1221:                                        }
                   1222:         }
                   1223:     }
                   1224: 
                   1225:     function checksec() {
                   1226:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1227:             ele = document.forms.'.$form.'.elements[i];
                   1228:            string = document.forms.'.$form.'.chksec.value;
                   1229:            if
                   1230:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1231:               document.forms.'.$form.'.elements[i].checked=true;
                   1232:             }
                   1233:         }
                   1234:     }
                   1235: 
                   1236: 
                   1237:     function uncheckall() {
                   1238:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1239:             ele = document.forms.'.$form.'.elements[i];
                   1240:             if (ele.name == "'.$type.'") {
                   1241:             document.forms.'.$form.'.elements[i].checked=false;
                   1242:                                        }
                   1243:         }
                   1244:     }
                   1245: 
1.597     wenzelju 1246: '."\n");
1.249     albertel 1247:     return $chkallscript;
                   1248: }
                   1249: 
                   1250: sub check_buttons {
1.485     albertel 1251:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1252:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1253:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1254:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1255:     return $buttons;
                   1256: }
                   1257: 
1.44      ng       1258: #     Displays the submissions for one student or a group of students
1.34      ng       1259: sub processGroup {
1.619     www      1260:     my ($request,$symb)  = @_;
1.41      ng       1261:     my $ctr        = 0;
1.155     albertel 1262:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1263:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1264: 
1.396     banghart 1265:     foreach my $student (@stuchecked) {
                   1266: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1267: 	$env{'form.student'}        = $uname;
                   1268: 	$env{'form.userdom'}        = $udom;
                   1269: 	$env{'form.fullname'}       = $fullname;
1.619     www      1270: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1271: 	$ctr++;
                   1272:     }
                   1273:     return '';
1.35      ng       1274: }
1.34      ng       1275: 
1.44      ng       1276: #------------------------------------------------------------------------------------
                   1277: #
                   1278: #-------------------------- Next few routines handles grading by student, essentially
                   1279: #                           handles essay response type problem/part
                   1280: #
                   1281: #--- Javascript to handle the submission page functionality ---
                   1282: sub sub_page_js {
                   1283:     my $request = shift;
1.736     damieng  1284:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1285:     &js_escape(\$alertmsg);
1.597     wenzelju 1286:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1287:     function updateRadio(formname,id,weight) {
1.125     ng       1288: 	var gradeBox = formname["GD_BOX"+id];
                   1289: 	var radioButton = formname["RADVAL"+id];
                   1290: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1291: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1292: 	gradeBox.value = pts;
                   1293: 	var resetbox = false;
                   1294: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1295: 	    alert("$alertmsg"+pts);
1.71      ng       1296: 	    for (var i=0; i<radioButton.length; i++) {
                   1297: 		if (radioButton[i].checked) {
                   1298: 		    gradeBox.value = i;
                   1299: 		    resetbox = true;
                   1300: 		}
                   1301: 	    }
                   1302: 	    if (!resetbox) {
                   1303: 		formtextbox.value = "";
                   1304: 	    }
                   1305: 	    return;
1.44      ng       1306: 	}
1.71      ng       1307: 
                   1308: 	if (pts > weight) {
                   1309: 	    var resp = confirm("You entered a value ("+pts+
                   1310: 			       ") greater than the weight for the part. Accept?");
                   1311: 	    if (resp == false) {
1.125     ng       1312: 		gradeBox.value = oldpts;
1.71      ng       1313: 		return;
                   1314: 	    }
1.44      ng       1315: 	}
1.13      albertel 1316: 
1.71      ng       1317: 	for (var i=0; i<radioButton.length; i++) {
                   1318: 	    radioButton[i].checked=false;
                   1319: 	    if (pts == i && pts != "") {
                   1320: 		radioButton[i].checked=true;
                   1321: 	    }
                   1322: 	}
                   1323: 	updateSelect(formname,id);
1.125     ng       1324: 	formname["stores"+id].value = "0";
1.41      ng       1325:     }
1.5       albertel 1326: 
1.72      ng       1327:     function writeBox(formname,id,pts) {
1.125     ng       1328: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1329: 	if (checkSolved(formname,id) == 'update') {
                   1330: 	    gradeBox.value = pts;
                   1331: 	} else {
1.125     ng       1332: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1333: 	    gradeBox.value = oldpts;
1.125     ng       1334: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1335: 	    for (var i=0; i<radioButton.length; i++) {
                   1336: 		radioButton[i].checked=false;
1.72      ng       1337: 		if (i == oldpts) {
1.71      ng       1338: 		    radioButton[i].checked=true;
                   1339: 		}
                   1340: 	    }
1.41      ng       1341: 	}
1.125     ng       1342: 	formname["stores"+id].value = "0";
1.71      ng       1343: 	updateSelect(formname,id);
                   1344: 	return;
1.41      ng       1345:     }
1.44      ng       1346: 
1.71      ng       1347:     function clearRadBox(formname,id) {
                   1348: 	if (checkSolved(formname,id) == 'noupdate') {
                   1349: 	    updateSelect(formname,id);
                   1350: 	    return;
                   1351: 	}
1.125     ng       1352: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1353: 	for (var i=0; i<gradeSelect.length; i++) {
                   1354: 	    if (gradeSelect[i].selected) {
                   1355: 		var selectx=i;
                   1356: 	    }
                   1357: 	}
1.125     ng       1358: 	var stores = formname["stores"+id];
1.71      ng       1359: 	if (selectx == stores.value) { return };
1.125     ng       1360: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1361: 	gradeBox.value = "";
1.125     ng       1362: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1363: 	for (var i=0; i<radioButton.length; i++) {
                   1364: 	    radioButton[i].checked=false;
                   1365: 	}
                   1366: 	stores.value = selectx;
                   1367:     }
1.5       albertel 1368: 
1.71      ng       1369:     function checkSolved(formname,id) {
1.125     ng       1370: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1371: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1372: 	    if (!reply) {return "noupdate";}
1.120     ng       1373: 	    formname.overRideScore.value = 'yes';
1.41      ng       1374: 	}
1.71      ng       1375: 	return "update";
1.13      albertel 1376:     }
1.71      ng       1377: 
                   1378:     function updateSelect(formname,id) {
1.125     ng       1379: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1380: 	return;
1.41      ng       1381:     }
1.33      ng       1382: 
1.121     ng       1383: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1384:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1385: 	formname.gradeOpt.value = val;
1.71      ng       1386: 	if (val == "Save & Next") {
                   1387: 	    for (i=0;i<=total;i++) {
                   1388: 		for (j=0;j<parttot;j++) {
1.125     ng       1389: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1390: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1391: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1392: 			if (points == "") {
1.125     ng       1393: 			    var name = formname["name"+i].value;
1.129     ng       1394: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1395: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1396: 					       ", part "+partid+". Continue?");
1.71      ng       1397: 			    if (resp == false) {
1.125     ng       1398: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1399: 				return false;
                   1400: 			    }
                   1401: 			}
                   1402: 		    }
                   1403: 		}
                   1404: 	    }
                   1405: 	}
1.120     ng       1406: 	formname.submit();
                   1407:     }
                   1408: 
1.71      ng       1409: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1410:     function checkSubmitPage(formname,total) {
                   1411: 	noscore = new Array(100);
                   1412: 	var ptr = 0;
                   1413: 	for (i=1;i<total;i++) {
1.125     ng       1414: 	    var partid = formname["q_"+i].value;
1.127     ng       1415: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1416: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1417: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1418: 		if (points == "" && status != "correct_by_student") {
                   1419: 		    noscore[ptr] = i;
                   1420: 		    ptr++;
                   1421: 		}
                   1422: 	    }
                   1423: 	}
                   1424: 	if (ptr != 0) {
                   1425: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1426: 	    var prolist = "";
                   1427: 	    if (ptr == 1) {
                   1428: 		prolist = noscore[0];
                   1429: 	    } else {
                   1430: 		var i = 0;
                   1431: 		while (i < ptr-1) {
                   1432: 		    prolist += noscore[i]+", ";
                   1433: 		    i++;
                   1434: 		}
                   1435: 		prolist += "and "+noscore[i];
                   1436: 	    }
                   1437: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1438: 	    if (resp == false) {
                   1439: 		return false;
                   1440: 	    }
                   1441: 	}
1.45      ng       1442: 
1.71      ng       1443: 	formname.submit();
                   1444:     }
                   1445: SUBJAVASCRIPT
                   1446: }
1.45      ng       1447: 
1.71      ng       1448: #--- javascript for essay type problem --
                   1449: sub sub_page_kw_js {
                   1450:     my $request = shift;
1.80      ng       1451:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1452:     &commonJSfunctions($request);
1.350     albertel 1453: 
1.629     www      1454:     my $inner_js_msg_central= (<<INNERJS);
                   1455: <script type="text/javascript">
1.350     albertel 1456:     function checkInput() {
                   1457:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1458:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1459:       var usrctr = document.msgcenter.usrctr.value;
                   1460:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1461:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1462: 
                   1463:       var msgchk = "";
                   1464:       if (document.msgcenter.subchk.checked) {
                   1465:          msgchk = "msgsub,";
                   1466:       }
                   1467:       var includemsg = 0;
                   1468:       for (var i=1; i<=nmsg; i++) {
                   1469:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1470:           var frmmsg = document.msgcenter["msg"+i];
                   1471:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1472:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1473:           showflg.value = "1";
                   1474:           var chkbox = document.msgcenter["msgn"+i];
                   1475:           if (chkbox.checked) {
                   1476:              msgchk += "savemsg"+i+",";
                   1477:              includemsg = 1;
                   1478:           }
                   1479:       }
                   1480:       if (document.msgcenter.newmsgchk.checked) {
                   1481:          msgchk += "newmsg"+usrctr;
                   1482:          includemsg = 1;
                   1483:       }
                   1484:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1485:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1486:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1487:       includemsg.value = msgchk;
                   1488: 
                   1489:       self.close()
                   1490: 
                   1491:     }
1.629     www      1492: </script>
1.350     albertel 1493: INNERJS
                   1494: 
1.629     www      1495:     my $inner_js_highlight_central= (<<INNERJS);
                   1496: <script type="text/javascript">
1.351     albertel 1497:     function updateChoice(flag) {
                   1498:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1499:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1500:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1501:       opener.document.SCORE.refresh.value = "on";
                   1502:       if (opener.document.SCORE.keywords.value!=""){
                   1503:          opener.document.SCORE.submit();
                   1504:       }
                   1505:       self.close()
                   1506:     }
1.629     www      1507: </script>
1.351     albertel 1508: INNERJS
                   1509: 
                   1510:     my $start_page_msg_central = 
                   1511:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1512: 				       {'js_ready'  => 1,
                   1513: 					'only_body' => 1,
                   1514: 					'bgcolor'   =>'#FFFFFF',});
                   1515:     my $end_page_msg_central = 
                   1516: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1517: 
                   1518: 
                   1519:     my $start_page_highlight_central = 
                   1520:         &Apache::loncommon::start_page('Highlight Central',
                   1521: 				       $inner_js_highlight_central,
1.350     albertel 1522: 				       {'js_ready'  => 1,
                   1523: 					'only_body' => 1,
                   1524: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1525:     my $end_page_highlight_central = 
1.350     albertel 1526: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1527: 
1.219     www      1528:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1529:     $docopen=~s/^document\.//;
1.736     damieng  1530:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1531:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1532:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1533:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1534:                 col1 => 'red',
                   1535:                 col2 => 'green',
                   1536:                 col3 => 'blue',
                   1537:                 siz1 => 'normal',
                   1538:                 siz2 => '+1',
                   1539:                 siz3 => '+2',
                   1540:                 sty1 => 'normal',
                   1541:                 sty2 => 'italic',
                   1542:                 sty3 => 'bold',
                   1543:              );
                   1544:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1545:                 comp => 'Compose Message for: ',
                   1546:                 incl => 'Include',
1.656     raeburn  1547:                 type => 'Type',
1.652     raeburn  1548:                 subj => 'Subject',
                   1549:                 mesa => 'Message',
                   1550:                 new  => 'New',
                   1551:                 save => 'Save',
                   1552:                 canc => 'Cancel',
                   1553:                 kehi => 'Keyword Highlight Options',
                   1554:                 txtc => 'Text Color',
                   1555:                 font => 'Font Size',
1.656     raeburn  1556:                 fnst => 'Font Style',
1.652     raeburn  1557:              );
1.736     damieng  1558:     &js_escape(\%js_lt);
                   1559:     &html_escape(\%html_js_lt);
                   1560:     &js_escape(\%html_js_lt);
1.597     wenzelju 1561:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1562: 
1.44      ng       1563: //===================== Show list of keywords ====================
1.122     ng       1564:   function keywords(formname) {
1.736     damieng  1565:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1566:     if (nret==null) return;
1.122     ng       1567:     formname.keywords.value = nret;
1.44      ng       1568: 
1.122     ng       1569:     if (formname.keywords.value != "") {
1.128     ng       1570: 	formname.refresh.value = "on";
1.122     ng       1571: 	formname.submit();
1.44      ng       1572:     }
                   1573:     return;
                   1574:   }
                   1575: 
                   1576: //===================== Script to view submitted by ==================
                   1577:   function viewSubmitter(submitter) {
                   1578:     document.SCORE.refresh.value = "on";
                   1579:     document.SCORE.NCT.value = "1";
                   1580:     document.SCORE.unamedom0.value = submitter;
                   1581:     document.SCORE.submit();
                   1582:     return;
                   1583:   }
                   1584: 
                   1585: //===================== Script to add keyword(s) ==================
                   1586:   function getSel() {
                   1587:     if (document.getSelection) txt = document.getSelection();
                   1588:     else if (document.selection) txt = document.selection.createRange().text;
                   1589:     else return;
                   1590:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1591:     if (cleantxt=="") {
1.736     damieng  1592: 	alert("$js_lt{'plse'}");
1.44      ng       1593: 	return;
                   1594:     }
1.736     damieng  1595:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1596:     if (nret==null) return;
1.127     ng       1597:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1598:     if (document.SCORE.keywords.value != "") {
1.127     ng       1599: 	document.SCORE.refresh.value = "on";
1.44      ng       1600: 	document.SCORE.submit();
                   1601:     }
                   1602:     return;
                   1603:   }
                   1604: 
                   1605: //====================== Script for composing message ==============
1.80      ng       1606:    // preload images
                   1607:    img1 = new Image();
                   1608:    img1.src = "$iconpath/mailbkgrd.gif";
                   1609:    img2 = new Image();
                   1610:    img2.src = "$iconpath/mailto.gif";
                   1611: 
1.44      ng       1612:   function msgCenter(msgform,usrctr,fullname) {
                   1613:     var Nmsg  = msgform.savemsgN.value;
                   1614:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1615:     var subject = msgform.msgsub.value;
1.127     ng       1616:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1617:     re = /msgsub/;
                   1618:     var shwsel = "";
                   1619:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1620:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1621:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1622:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1623: 	var testmsg = "savemsg"+i+",";
                   1624: 	re = new RegExp(testmsg,"g");
1.44      ng       1625: 	shwsel = "";
                   1626: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1627: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1628: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1629: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1630: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1631:     }
1.125     ng       1632:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1633:     shwsel = "";
                   1634:     re = /newmsg/;
                   1635:     if (re.test(msgchk)) { shwsel = "checked" }
                   1636:     newMsg(newmsg,shwsel);
                   1637:     msgTail(); 
                   1638:     return;
                   1639:   }
                   1640: 
1.123     ng       1641:   function checkEntities(strx) {
                   1642:     if (strx.length == 0) return strx;
                   1643:     var orgStr = ["&", "<", ">", '"']; 
                   1644:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1645:     var counter = 0;
                   1646:     while (counter < 4) {
                   1647: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1648: 	counter++;
                   1649:     }
                   1650:     return strx;
                   1651:   }
                   1652: 
                   1653:   function strReplace(strx, orgStr, newStr) {
                   1654:     return strx.split(orgStr).join(newStr);
                   1655:   }
                   1656: 
1.44      ng       1657:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1658:     var height = 70*Nmsg+250;
1.44      ng       1659:     if (height > 600) {
                   1660: 	height = 600;
                   1661:     }
1.118     ng       1662:     var xpos = (screen.width-600)/2;
                   1663:     xpos = (xpos < 0) ? '0' : xpos;
                   1664:     var ypos = (screen.height-height)/2-30;
                   1665:     ypos = (ypos < 0) ? '0' : ypos;
                   1666: 
1.668     www      1667:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1668:     pWin.focus();
                   1669:     pDoc = pWin.document;
1.219     www      1670:     pDoc.$docopen;
1.351     albertel 1671:     pDoc.write('$start_page_msg_central');
1.76      ng       1672: 
                   1673:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1674:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1675:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1676: 
1.676     golterma 1677:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1678:     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       1679: }
                   1680:     function displaySubject(msg,shwsel) {
1.76      ng       1681:     pDoc = pWin.document;
1.676     golterma 1682:     pDoc.write("<tr>");
                   1683:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1684:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1685:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1686: }
                   1687: 
1.72      ng       1688:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1689:     pDoc = pWin.document;
1.676     golterma 1690:     pDoc.write("<tr>");
                   1691:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1692:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1693:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1694: }
                   1695: 
                   1696:   function newMsg(newmsg,shwsel) {
1.76      ng       1697:     pDoc = pWin.document;
1.676     golterma 1698:     pDoc.write("<tr>");
                   1699:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1700:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1701:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1702: }
                   1703: 
                   1704:   function msgTail() {
1.76      ng       1705:     pDoc = pWin.document;
1.676     golterma 1706:     //pDoc.write("<\\/table>");
1.465     albertel 1707:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1708:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1709:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1710:     pDoc.write("<\\/form>");
1.351     albertel 1711:     pDoc.write('$end_page_msg_central');
1.128     ng       1712:     pDoc.close();
1.44      ng       1713: }
                   1714: 
                   1715: //====================== Script for keyword highlight options ==============
                   1716:   function kwhighlight() {
                   1717:     var kwclr    = document.SCORE.kwclr.value;
                   1718:     var kwsize   = document.SCORE.kwsize.value;
                   1719:     var kwstyle  = document.SCORE.kwstyle.value;
                   1720:     var redsel = "";
                   1721:     var grnsel = "";
                   1722:     var blusel = "";
1.736     damieng  1723:     var txtcol1 = "$js_lt{'col1'}";
                   1724:     var txtcol2 = "$js_lt{'col2'}";
                   1725:     var txtcol3 = "$js_lt{'col3'}";
                   1726:     var txtsiz1 = "$js_lt{'siz1'}";
                   1727:     var txtsiz2 = "$js_lt{'siz2'}";
                   1728:     var txtsiz3 = "$js_lt{'siz3'}";
                   1729:     var txtsty1 = "$js_lt{'sty1'}";
                   1730:     var txtsty2 = "$js_lt{'sty2'}";
                   1731:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1732:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1733:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1734:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1735:     var sznsel = "";
                   1736:     var sz1sel = "";
                   1737:     var sz2sel = "";
1.718     bisitz   1738:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1739:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1740:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1741:     var synsel = "";
                   1742:     var syisel = "";
                   1743:     var sybsel = "";
1.718     bisitz   1744:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1745:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1746:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1747:     highlightCentral();
1.718     bisitz   1748:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1749:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1750:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1751:     highlightend();
                   1752:     return;
                   1753:   }
                   1754: 
                   1755:   function highlightCentral() {
1.76      ng       1756: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1757:     var xpos = (screen.width-400)/2;
                   1758:     xpos = (xpos < 0) ? '0' : xpos;
                   1759:     var ypos = (screen.height-330)/2-30;
                   1760:     ypos = (ypos < 0) ? '0' : ypos;
                   1761: 
1.206     albertel 1762:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1763:     hwdWin.focus();
                   1764:     var hDoc = hwdWin.document;
1.219     www      1765:     hDoc.$docopen;
1.351     albertel 1766:     hDoc.write('$start_page_highlight_central');
1.76      ng       1767:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1768:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1769: 
1.718     bisitz   1770:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1771:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1772:   }
                   1773: 
                   1774:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1775:     var hDoc = hwdWin.document;
1.718     bisitz   1776:     hDoc.write("<tr>");
1.76      ng       1777:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1778:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1779:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1780:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1781:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1782:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1783:     hDoc.write("<\\/tr>");
1.44      ng       1784:   }
                   1785: 
                   1786:   function highlightend() { 
1.76      ng       1787:     var hDoc = hwdWin.document;
1.718     bisitz   1788:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1789:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1790:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1791:     hDoc.write("<\\/form>");
1.351     albertel 1792:     hDoc.write('$end_page_highlight_central');
1.128     ng       1793:     hDoc.close();
1.44      ng       1794:   }
                   1795: 
                   1796: SUBJAVASCRIPT
                   1797: }
                   1798: 
1.349     albertel 1799: sub get_increment {
1.348     bowersj2 1800:     my $increment = $env{'form.increment'};
                   1801:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1802:         $increment != .1) {
                   1803:         $increment = 1;
                   1804:     }
                   1805:     return $increment;
                   1806: }
                   1807: 
1.585     bisitz   1808: sub gradeBox_start {
                   1809:     return (
                   1810:         &Apache::loncommon::start_data_table()
                   1811:        .&Apache::loncommon::start_data_table_header_row()
                   1812:        .'<th>'.&mt('Part').'</th>'
                   1813:        .'<th>'.&mt('Points').'</th>'
                   1814:        .'<th>&nbsp;</th>'
                   1815:        .'<th>'.&mt('Assign Grade').'</th>'
                   1816:        .'<th>'.&mt('Weight').'</th>'
                   1817:        .'<th>'.&mt('Grade Status').'</th>'
                   1818:        .&Apache::loncommon::end_data_table_header_row()
                   1819:     );
                   1820: }
                   1821: 
                   1822: sub gradeBox_end {
                   1823:     return (
                   1824:         &Apache::loncommon::end_data_table()
                   1825:     );
                   1826: }
1.71      ng       1827: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1828: sub gradeBox {
1.322     albertel 1829:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1830:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1831: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1832:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1833:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1834:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1835:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1836:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1837: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1838:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1839:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1840:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1841: 				       [$partid]);
                   1842:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1843:     if ($last_resets{$partid}) {
                   1844:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1845:     }
1.695     bisitz   1846:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1847:     my $ctr = 0;
1.348     bowersj2 1848:     my $thisweight = 0;
1.349     albertel 1849:     my $increment = &get_increment();
1.485     albertel 1850: 
                   1851:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1852:     while ($thisweight<=$wgt) {
1.532     bisitz   1853: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1854:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1855: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1856: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1857: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1858:         $thisweight += $increment;
1.71      ng       1859: 	$ctr++;
                   1860:     }
1.485     albertel 1861:     $radio.='</tr></table>';
                   1862: 
                   1863:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1864: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1865: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1866: 	$wgt.')" /></td>'."\n";
1.485     albertel 1867:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1868: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1869: 	' </td>'."\n";
                   1870:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1871: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1872:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1873: 	$line.='<option></option>'.
                   1874: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1875:     } else {
1.485     albertel 1876: 	$line.='<option selected="selected"></option>'.
                   1877: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1878:     }
1.485     albertel 1879:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1880: 
                   1881: 
                   1882:     $result .= 
1.695     bisitz   1883: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1884:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1885:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1886:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1887: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1888: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1889: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1890:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1891:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1892:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1893:         $aggtries.'" />'."\n";
1.582     raeburn  1894:     my $res_error;
                   1895:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1896:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1897:     if ($res_error) {
                   1898:         return &navmap_errormsg();
                   1899:     }
1.318     banghart 1900:     return $result;
                   1901: }
1.322     albertel 1902: 
                   1903: sub handback_box {
1.623     www      1904:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1905:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1906:     my (@respids);
1.652     raeburn  1907:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1908:     foreach my $part_response_id (@part_response_id) {
                   1909:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1910:         if ($part eq $partid) {
1.375     albertel 1911:             push(@respids,$resp);
1.323     banghart 1912:         }
                   1913:     }
1.318     banghart 1914:     my $result;
1.323     banghart 1915:     foreach my $respid (@respids) {
1.322     albertel 1916: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1917: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1918: 	next if (!@$files);
1.654     raeburn  1919: 	my $file_counter = 0;
1.313     banghart 1920: 	foreach my $file (@$files) {
1.368     banghart 1921: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1922:                 $file_counter++;
1.368     banghart 1923:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1924:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1925:     	        $file_disp = "$name.$ext";
                   1926:     	        $file = $file_path.$file_disp;
                   1927:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1928:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1929:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1930:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1931: 	    }
1.322     albertel 1932: 	}
1.654     raeburn  1933:         if ($file_counter) {
                   1934:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1935:                        '<span class="LC_info">'.
                   1936:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1937:         }
1.313     banghart 1938:     }
1.318     banghart 1939:     return $result;    
1.71      ng       1940: }
1.44      ng       1941: 
1.58      albertel 1942: sub show_problem {
1.382     albertel 1943:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1944:     my $rendered;
1.382     albertel 1945:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1946:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1947:     if ($mode eq 'both' or $mode eq 'text') {
                   1948: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1949: 						       $env{'request.course.id'},
                   1950: 						       undef,\%form);
1.144     albertel 1951:     }
1.58      albertel 1952:     if ($removeform) {
                   1953: 	$rendered=~s|<form(.*?)>||g;
                   1954: 	$rendered=~s|</form>||g;
1.374     albertel 1955: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1956:     }
1.144     albertel 1957:     my $companswer;
                   1958:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1959: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1960: 	$companswer=
                   1961: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1962: 						    $env{'request.course.id'},
                   1963: 						    %form);
1.144     albertel 1964:     }
1.58      albertel 1965:     if ($removeform) {
                   1966: 	$companswer=~s|<form(.*?)>||g;
                   1967: 	$companswer=~s|</form>||g;
1.144     albertel 1968: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1969:     }
1.671     raeburn  1970:     my $renderheading = &mt('View of the problem');
                   1971:     my $answerheading = &mt('Correct answer');
                   1972:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1973:         my $stu_fullname = $env{'form.fullname'};
                   1974:         if ($stu_fullname eq '') {
                   1975:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1976:         }
                   1977:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1978:         if ($forwhom ne '') {
                   1979:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1980:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1981:         }
                   1982:     }
1.468     albertel 1983:     $rendered=
1.588     bisitz   1984:         '<div class="LC_Box">'
1.671     raeburn  1985:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1986:        .$rendered
                   1987:        .'</div>';
1.468     albertel 1988:     $companswer=
1.588     bisitz   1989:         '<div class="LC_Box">'
1.671     raeburn  1990:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1991:        .$companswer
                   1992:        .'</div>';
1.468     albertel 1993:     my $result;
1.144     albertel 1994:     if ($mode eq 'both') {
1.588     bisitz   1995:         $result=$rendered.$companswer;
1.144     albertel 1996:     } elsif ($mode eq 'text') {
1.588     bisitz   1997:         $result=$rendered;
1.144     albertel 1998:     } elsif ($mode eq 'answer') {
1.588     bisitz   1999:         $result=$companswer;
1.144     albertel 2000:     }
1.71      ng       2001:     return $result;
1.58      albertel 2002: }
1.397     albertel 2003: 
1.396     banghart 2004: sub files_exist {
                   2005:     my ($r, $symb) = @_;
                   2006:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2007:     foreach my $student (@students) {
                   2008:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2009:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2010: 					      $udom,$uname);
1.396     banghart 2011:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2012:         foreach my $submission (@$string) {
                   2013:             my ($partid,$respid) =
                   2014: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2015:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2016: 					   \%record);
                   2017:             return 1 if (@$files);
1.396     banghart 2018:         }
                   2019:     }
1.397     albertel 2020:     return 0;
1.396     banghart 2021: }
1.397     albertel 2022: 
1.394     banghart 2023: sub download_all_link {
                   2024:     my ($r,$symb) = @_;
1.621     www      2025:     unless (&files_exist($r, $symb)) {
                   2026:        $r->print(&mt('There are currently no submitted documents.'));
                   2027:        return;
                   2028:     }
1.395     albertel 2029:     my $all_students = 
                   2030: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2031: 
                   2032:     my $parts =
                   2033: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2034: 
1.394     banghart 2035:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2036:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2037:                              'cgi.'.$identifier.'.symb' => $symb,
                   2038:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2039:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2040: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2041:     return;
                   2042: }
                   2043: 
                   2044: sub submit_download_link {
                   2045:     my ($request,$symb) = @_;
                   2046:     if (!$symb) { return ''; }
                   2047: #FIXME: Figure out which type of problem this is and provide appropriate download
1.750     raeburn  2048:     my $res_error;
                   2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                   2050:     if (ref($res_error)) {
                   2051:         if ($$res_error) {
                   2052:             $request->print(&mt('An error occurred retrieving response types'));
                   2053:             return;
                   2054:         }
                   2055:     }
                   2056:     my ($numupload,$numessay) = (0,0);
                   2057:     if (ref($responseType) eq 'HASH') {
                   2058:         foreach my $part (sort(keys(%$responseType))) {
                   2059:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
                   2060:                 my $responsetype = $responseType->{$part}->{$id};
                   2061:                 if ($responsetype eq 'essay') {
                   2062:                     my $uploadedfiletypes =
                   2063:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
                   2064:                     if ($uploadedfiletypes) {
                   2065:                         $numupload++;
                   2066:                     } else {
                   2067:                         $numessay++;
                   2068:                     }
                   2069:                 }
                   2070:             }
                   2071:         }
                   2072:     }
                   2073:     if (($numupload) || ($numessay)) {
                   2074:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2075:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2076:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2077:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2078:         if (ref($fullname) eq 'HASH') {
                   2079:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2080:             if (@students) {
                   2081:                 @{$env{'form.stuinfo'}} = @students;
                   2082:                 if ($numupload) {
                   2083:                     &download_all_link($request,$symb);
                   2084:                 }
                   2085: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
                   2086: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2087:             } else {
                   2088:                 $request->print(&mt('No students match the criteria you selected'));
                   2089:             }
                   2090:         } else {
                   2091:             $request->print(&mt('Could not retrieve student information'));
                   2092:         }
                   2093:     } else {
                   2094:         $request->print(&mt('No essayresponse items found'));
                   2095:     }
                   2096:     return;
1.394     banghart 2097: }
1.395     albertel 2098: 
1.432     banghart 2099: sub build_section_inputs {
                   2100:     my $section_inputs;
                   2101:     if ($env{'form.section'} eq '') {
                   2102:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2103:     } else {
                   2104:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2105:         foreach my $section (@sections) {
1.432     banghart 2106:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2107:         }
                   2108:     }
                   2109:     return $section_inputs;
                   2110: }
                   2111: 
1.44      ng       2112: # --------------------------- show submissions of a student, option to grade 
                   2113: sub submission {
1.608     www      2114:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2115:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2116:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2117:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2118:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2119: 
1.605     www      2120:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2121:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2122:     my $is_tool = ($symb =~ /ext\.tool$/);
1.104     albertel 2123: 
                   2124:     if (!&canview($usec)) {
1.712     bisitz   2125:         $request->print(
                   2126:             '<span class="LC_warning">'.
1.713     bisitz   2127:             &mt('Unable to view requested student.').
1.712     bisitz   2128:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2129:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2130:             '</span>');
1.104     albertel 2131: 	return;
                   2132:     }
                   2133: 
1.257     albertel 2134:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2135:     unless ($is_tool) { 
                   2136:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2137:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2138:     }
1.257     albertel 2139:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2140:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2141: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2142: 	'/check.gif" height="16" border="0" />';
1.41      ng       2143: 
                   2144:     # header info
                   2145:     if ($counter == 0) {
                   2146: 	&sub_page_js($request);
1.621     www      2147: 	&sub_page_kw_js($request);
1.118     ng       2148: 
1.44      ng       2149: 	# option to display problem, only once else it cause problems 
                   2150:         # with the form later since the problem has a form.
1.257     albertel 2151: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2152: 	    my $mode;
1.257     albertel 2153: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2154: 		$mode='both';
1.257     albertel 2155: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2156: 		$mode='text';
1.257     albertel 2157: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2158: 		$mode='answer';
                   2159: 	    }
1.329     albertel 2160: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2161: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2162: 	}
1.441     www      2163: 
1.704     raeburn  2164: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2165:         # if this subroutine has been called once.
1.41      ng       2166: 	my %keyhash = ();
1.624     www      2167: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2168:         if (1) {
1.41      ng       2169: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2170: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2171: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2172: 
1.257     albertel 2173: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2174: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2175: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2176: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2177: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2178: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2179: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2180: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2181: 	}
1.257     albertel 2182: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2183: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2184: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2185: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2186: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2187: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2188: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2189: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2190: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2191: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2192: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2193: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2194: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2195: 			&build_section_inputs().
1.326     albertel 2196: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2197: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2198: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2199: #	if ($env{'form.handgrade'} eq 'yes') {
                   2200:         if (1) {
1.257     albertel 2201: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2202: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2203: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2204: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2205: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2206: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2207: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2208: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2209: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2210: 	    }
1.123     ng       2211: 	}
1.41      ng       2212: 	
                   2213: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2214: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2215: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2216: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2217: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2218: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2219: 		'" />'."\n".
                   2220: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2221: 	    $cts++;
                   2222: 	}
                   2223: 	$request->print($prnmsg);
1.32      ng       2224: 
1.624     www      2225: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2226:         unless ($is_tool) {
1.652     raeburn  2227: 
                   2228:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2229:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2230:                           keyw => 'Keyword Options',
1.655     raeburn  2231:                           list => 'List',
1.652     raeburn  2232:                           past => 'Paste Selection to List',
1.661     www      2233:                           high => 'Highlight Attribute',
1.652     raeburn  2234:                      );    
1.88      www      2235: #
                   2236: # Print out the keyword options line
                   2237: #
1.718     bisitz   2238: 	    $request->print(
                   2239:                 '<div class="LC_columnSection">'
                   2240:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2241:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2242:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2243:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2244:  class="page">'.$lt{'past'}.'</a>',
                   2245:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2246:                     {legend => $lt{'keyw'}})
                   2247:                .'</fieldset></div>'
                   2248:             );
                   2249: 
1.88      www      2250: #
                   2251: # Load the other essays for similarity check
                   2252: #
1.324     albertel 2253:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2254: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2255: 	    $apath=&escape($apath);
1.88      www      2256: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2257:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2258:         }
                   2259:     }
1.44      ng       2260: 
1.441     www      2261: # This is where output for one specific student would start
1.592     bisitz   2262:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2263:     $request->print(
                   2264:         "\n\n"
                   2265:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2266:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2267:        ."\n"
                   2268:     );
1.441     www      2269: 
1.592     bisitz   2270:     # Show additional functions if allowed
                   2271:     if ($perm{'vgr'}) {
                   2272:         $request->print(
                   2273:             &Apache::loncommon::track_student_link(
1.708     bisitz   2274:                 'View recent activity',
1.592     bisitz   2275:                 $uname,$udom,'check')
                   2276:            .' '
                   2277:         );
                   2278:     }
                   2279:     if ($perm{'opa'}) {
                   2280:         $request->print(
                   2281:             &Apache::loncommon::pprmlink(
                   2282:                 &mt('Set/Change parameters'),
                   2283:                 $uname,$udom,$symb,'check'));
                   2284:     }
                   2285: 
                   2286:     # Show Problem
1.257     albertel 2287:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2288: 	my $mode;
1.257     albertel 2289: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2290: 	    $mode='both';
1.257     albertel 2291: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2292: 	    $mode='text';
1.257     albertel 2293: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2294: 	    $mode='answer';
                   2295: 	}
1.329     albertel 2296: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2297: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2298:     }
1.144     albertel 2299: 
1.257     albertel 2300:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2301:     my $res_error;
                   2302:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2303:     if ($res_error) {
                   2304:         $request->print(&navmap_errormsg());
                   2305:         return;
                   2306:     }
1.41      ng       2307: 
1.44      ng       2308:     # Display student info
1.41      ng       2309:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2310: 
1.745     raeburn  2311:     my $boxtitle = &mt('Submissions');
                   2312:     if ($is_tool) {
                   2313:         $boxtitle = &mt('Transactions')
                   2314:     }
1.590     bisitz   2315:     my $result='<div class="LC_Box">'
1.745     raeburn  2316:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2317:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2318:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2319: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2320:     unless ($is_tool) {
1.588     bisitz   2321:         $result.='<p class="LC_info">'
                   2322:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2323:                 ."</p>\n";
1.469     albertel 2324:     }
                   2325: 
1.118     ng       2326:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2327:     my $fullname;
                   2328:     my $col_fullnames = [];
1.624     www      2329: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2330:     unless ($is_tool) {
1.464     albertel 2331: 	(my $sub_result,$fullname,$col_fullnames)=
                   2332: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2333: 				 $counter);
                   2334: 	$result.=$sub_result;
1.41      ng       2335:     }
1.44      ng       2336:     $request->print($result."\n");
1.702     kruse    2337:     
1.44      ng       2338:     # print student answer/submission
1.588     bisitz   2339:     # Options are (1) Handgraded submission only
1.44      ng       2340:     #             (2) Last submission, includes submission that is not handgraded 
                   2341:     #                  (for multi-response type part)
                   2342:     #             (3) Last submission plus the parts info
                   2343:     #             (4) The whole record for this student
1.702     kruse    2344:     
1.745     raeburn  2345:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2346: 	
1.702     kruse    2347:     my $lastsubonly;
1.468     albertel 2348: 
1.702     kruse    2349:     if ($$timestamp eq '') {
                   2350:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2351:     } elsif ($is_tool) {
                   2352:         $lastsubonly =
                   2353:             '<div class="LC_grade_submissions_body">'
                   2354:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2355:     } else {
                   2356:         $lastsubonly =
                   2357:             '<div class="LC_grade_submissions_body">'
                   2358:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2359: 
                   2360: 	my %seenparts;
                   2361: 	my @part_response_id = &flatten_responseType($responseType);
                   2362: 	foreach my $part (@part_response_id) {
                   2363: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2364: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2365: 
1.702     kruse    2366: 	    my ($partid,$respid) = @{ $part };
                   2367: 	    my $display_part=&get_display_part($partid,$symb);
                   2368: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2369: 		if (exists($seenparts{$partid})) { next; }
                   2370: 		$seenparts{$partid}=1;
                   2371:                 $request->print(
                   2372:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2373:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2374:                                '<a href="javascript:viewSubmitter(\''.
                   2375:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2376:                                '\');" target="_self">'.
                   2377:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2378:                     '<br />');
                   2379: 		next;
                   2380: 		}
                   2381: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2382: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2383:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2384:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2385:                     ' <span class="LC_internal_info">'.
                   2386:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2387:                     '</span>&nbsp; &nbsp;'.
                   2388: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2389: 		next;
                   2390: 	    }
                   2391: 	    foreach my $submission (@$string) {
                   2392: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2393: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2394: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2395: 		# Similarity check
                   2396:                 my $similar='';
                   2397:                 my ($type,$trial,$rndseed);
                   2398:                 if ($hide eq 'rand') {
                   2399:                     $type = 'randomizetry';
                   2400:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2401:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2402:                 }
                   2403: 	        if ($env{'form.checkPlag'}) {
                   2404:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2405: 		        &most_similar($uname,$udom,$symb,$subval);
                   2406: 		    if ($osim) {
                   2407: 			$osim=int($osim*100.0);
                   2408: 			my %old_course_desc = 
                   2409: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2410: 							{'one_time' => 1});
                   2411: 
                   2412:                         if ($hide eq 'anon') {
                   2413:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2414:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2415:                         } else {
                   2416: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2417: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2418: 				    $osim,
                   2419: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2420: 				        $old_course_desc{'description'},
                   2421: 				        $old_course_desc{'num'},
                   2422: 				        $old_course_desc{'domain'}).
                   2423: 				    '</span></h3><blockquote><i>'.
                   2424: 				    &keywords_highlight($oessay).
                   2425: 				    '</i></blockquote><hr />';
1.702     kruse    2426:                         }
                   2427: 	            }
                   2428: 		}
                   2429: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2430:                                      undef,$type,$trial,$rndseed);
                   2431:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2432: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2433: 		    my $display_part=&get_display_part($partid,$symb);
                   2434:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2435:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2436:                         ' <span class="LC_internal_info">'.
                   2437:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2438:                         '</span>&nbsp; &nbsp;';
                   2439: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2440:                         
                   2441: 		    if (@$files) {
                   2442:                         if ($hide eq 'anon') {
                   2443:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2444:                         } else {
                   2445:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2446:                                         .'<br /><span class="LC_warning">';
                   2447:                             if(@$files == 1) {
                   2448:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2449:                             } else {
1.702     kruse    2450:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2451:                             }
                   2452:                             $lastsubonly .= '</span>';                         
                   2453:                             foreach my $file (@$files) {
                   2454:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2455:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2456:                             }
                   2457:                         }
1.702     kruse    2458: 			$lastsubonly.='<br />';
                   2459:                     }
                   2460:                     if ($hide eq 'anon') {
                   2461:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2462:                     } else {
1.724     raeburn  2463:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2464:                         if ($draft) {
                   2465:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2466:                         }
                   2467:                         $subval =
1.702     kruse    2468: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2469: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2470:                         if ($responsetype eq 'essay') {
                   2471:                             $subval =~ s{\n}{<br />}g;
                   2472:                         }
                   2473:                         $lastsubonly.=$subval."\n";
1.702     kruse    2474:                     }
                   2475: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2476: 		    $lastsubonly.='</div>';
1.41      ng       2477: 		}
1.702     kruse    2478:             }
1.151     albertel 2479: 	}
1.702     kruse    2480: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2481:     }
                   2482:     $request->print($lastsubonly);
                   2483:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2484:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2485: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2486:   
1.702     kruse    2487:     } 
                   2488:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2489:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2490:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2491: 								 $env{'request.course.id'},
1.44      ng       2492: 								 $last,'.submission',
1.726     raeburn  2493: 								 'Apache::grades::keywords_highlight',
                   2494:                                                                  $usec,$identifier));
1.41      ng       2495:     }
1.121     ng       2496:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2497: 	.$udom.'" />'."\n");
1.44      ng       2498:     # return if view submission with no grading option
1.618     www      2499:     if (!&canmodify($usec)) {
1.633     www      2500: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2501: 	return;
1.180     albertel 2502:     } else {
1.468     albertel 2503: 	$request->print('</div>'."\n");
1.41      ng       2504:     }
1.33      ng       2505: 
1.121     ng       2506:     # essay grading message center
1.624     www      2507: #    if ($env{'form.handgrade'} eq 'yes') {
                   2508:     if (1) {
1.468     albertel 2509: 	my $result='<div class="LC_grade_message_center">';
                   2510:     
                   2511: 	$result.='<div class="LC_grade_message_center_header">'.
                   2512: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2513: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2514: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2515: 	if (scalar(@$col_fullnames) > 0) {
                   2516: 	    my $lastone = pop(@$col_fullnames);
                   2517: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2518: 	}
                   2519: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2520: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2521: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2522: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2523: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2524: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2525: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2526: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2527: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2528: 	    '<br />&nbsp;('.
1.468     albertel 2529: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2530: 	$result.='</div></div>';
1.121     ng       2531: 	$request->print($result);
1.118     ng       2532:     }
1.41      ng       2533: 
                   2534:     my %seen = ();
                   2535:     my @partlist;
1.129     ng       2536:     my @gradePartRespid;
1.745     raeburn  2537:     my @part_response_id;
                   2538:     if ($is_tool) {
                   2539:         @part_response_id = ([0,'']);
                   2540:     } else {
                   2541:         @part_response_id = &flatten_responseType($responseType);
                   2542:     }
1.585     bisitz   2543:     $request->print(
1.588     bisitz   2544:         '<div class="LC_Box">'
                   2545:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2546:     );
1.592     bisitz   2547:     $request->print(&gradeBox_start());
1.375     albertel 2548:     foreach my $part_response_id (@part_response_id) {
                   2549:     	my ($partid,$respid) = @{ $part_response_id };
                   2550: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2551: 	next if ($seen{$partid} > 0);
1.41      ng       2552: 	$seen{$partid}++;
1.393     albertel 2553: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2554: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2555: 	push(@partlist,$partid);
                   2556: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2557: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2558:     }
1.585     bisitz   2559:     $request->print(&gradeBox_end()); # </div>
                   2560:     $request->print('</div>');
1.468     albertel 2561: 
                   2562:     $request->print('<div class="LC_grade_info_links">');
                   2563:     $request->print('</div>');
                   2564: 
1.45      ng       2565:     $result='<input type="hidden" name="partlist'.$counter.
                   2566: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2567:     $result.='<input type="hidden" name="gradePartRespid'.
                   2568: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2569:     my $ctr = 0;
                   2570:     while ($ctr < scalar(@partlist)) {
                   2571: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2572: 	    $partlist[$ctr].'" />'."\n";
                   2573: 	$ctr++;
                   2574:     }
1.468     albertel 2575:     $request->print($result.''."\n");
1.41      ng       2576: 
1.441     www      2577: # Done with printing info for one student
                   2578: 
1.468     albertel 2579:     $request->print('</div>');#LC_grade_show_user
1.441     www      2580: 
                   2581: 
1.41      ng       2582:     # print end of form
                   2583:     if ($counter == $total) {
1.592     bisitz   2584:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2585: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2586: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2587: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2588: 	my $ntstu ='<select name="NTSTU">'.
                   2589: 	    '<option>1</option><option>2</option>'.
                   2590: 	    '<option>3</option><option>5</option>'.
                   2591: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2592: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2593: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2594:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2595: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2596: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2597: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2598: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2599:         $endform.='<span class="LC_warning">'.
                   2600:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2601:                   '</span>'."\n" ;
1.349     albertel 2602:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2603:             "' name='increment' />";
1.485     albertel 2604: 	$endform.='</td></tr></table></form>';
1.41      ng       2605: 	$request->print($endform);
                   2606:     }
                   2607:     return '';
1.38      ng       2608: }
                   2609: 
1.464     albertel 2610: sub check_collaborators {
                   2611:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2612:     my ($result,@col_fullnames);
                   2613:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2614:     foreach my $part (keys(%$handgrade)) {
                   2615: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2616: 					'.maxcollaborators',
                   2617: 					$symb,$udom,$uname);
                   2618: 	next if ($ncol <= 0);
                   2619: 	$part =~ s/\_/\./g;
                   2620: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2621: 	my (@good_collaborators, @bad_collaborators);
                   2622: 	foreach my $possible_collaborator
1.630     www      2623: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2624: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2625: 	    next if ($possible_collaborator eq '');
1.631     www      2626: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2627: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2628: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2629: 	    # Doing this grep allows 'fuzzy' specification
                   2630: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2631: 			       keys(%$classlist));
                   2632: 	    if (! scalar(@matches)) {
                   2633: 		push(@bad_collaborators, $possible_collaborator);
                   2634: 	    } else {
                   2635: 		push(@good_collaborators, @matches);
                   2636: 	    }
                   2637: 	}
                   2638: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2639: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2640: 	    foreach my $name (@good_collaborators) {
                   2641: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2642: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2643: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2644: 	    }
1.630     www      2645: 	    $result.='</ol><br />'."\n";
1.466     albertel 2646: 	    my ($part)=split(/\./,$part);
1.464     albertel 2647: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2648: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2649: 		"\n";
                   2650: 	}
                   2651: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2652: 	    $result.='<div class="LC_warning">';
1.464     albertel 2653: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2654: 	    $result .= '</div>';
                   2655: 	}         
                   2656: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2657: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2658: 	    $result .= &mt('This student has submitted too many '.
                   2659: 		'collaborators.  Maximum is [_1].',$ncol);
                   2660: 	    $result .= '</div>';
                   2661: 	}
                   2662:     }
                   2663:     return ($result,$fullname,\@col_fullnames);
                   2664: }
                   2665: 
1.44      ng       2666: #--- Retrieve the last submission for all the parts
1.38      ng       2667: sub get_last_submission {
1.745     raeburn  2668:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2669:     my (@string,$timestamp,%lasthidden);
1.119     ng       2670:     if ($$returnhash{'version'}) {
1.46      ng       2671: 	my %lasthash=();
                   2672: 	my ($version);
1.119     ng       2673: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2674: 	    foreach my $key (sort(split(/\:/,
                   2675: 					$$returnhash{$version.':keys'}))) {
                   2676: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2677: 		$timestamp = 
1.545     raeburn  2678: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2679: 	    }
                   2680: 	}
1.640     raeburn  2681:         my (%typeparts,%randombytry);
1.596     raeburn  2682:         my $showsurv = 
                   2683:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2684:         foreach my $key (sort(keys(%lasthash))) {
                   2685:             if ($key =~ /\.type$/) {
                   2686:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2687:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2688:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2689:                     my ($ign,@parts) = split(/\./,$key);
                   2690:                     pop(@parts);
1.641     raeburn  2691:                     my $id = join('.',@parts);
1.640     raeburn  2692:                     if ($lasthash{$key} eq 'randomizetry') {
                   2693:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2694:                     } else {
                   2695:                         unless ($showsurv) {
                   2696:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2697:                         }
1.596     raeburn  2698:                     }
                   2699:                     delete($lasthash{$key});
                   2700:                 }
                   2701:             }
                   2702:         }
                   2703:         my @hidden = keys(%typeparts);
1.640     raeburn  2704:         my @randomize = keys(%randombytry);
1.397     albertel 2705: 	foreach my $key (keys(%lasthash)) {
                   2706: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2707:             my $hide;
                   2708:             if (@hidden) {
                   2709:                 foreach my $id (@hidden) {
                   2710:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2711:                         $hide = 'anon';
1.596     raeburn  2712:                         last;
                   2713:                     }
                   2714:                 }
                   2715:             }
1.640     raeburn  2716:             unless ($hide) {
                   2717:                 if (@randomize) {
1.732     raeburn  2718:                     foreach my $id (@randomize) {
1.640     raeburn  2719:                         if ($key =~ /^\Q$id\E/) {
                   2720:                             $hide = 'rand';
                   2721:                             last;
                   2722:                         }
                   2723:                     }
                   2724:                 }
                   2725:             }
1.397     albertel 2726: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2727: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2728:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2729:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2730:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2731: 	}
                   2732:     }
1.397     albertel 2733:     if (!@string) {
1.745     raeburn  2734:         my $msg;
                   2735:         if ($is_tool) {
1.747     raeburn  2736:             $msg = &mt('No grade passed back.');
1.745     raeburn  2737:         } else {
                   2738:             $msg = &mt('Nothing submitted - no attempts.');
                   2739:         }
1.397     albertel 2740: 	$string[0] =
1.745     raeburn  2741: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2742:     }
                   2743:     return (\@string,\$timestamp);
1.38      ng       2744: }
1.35      ng       2745: 
1.44      ng       2746: #--- High light keywords, with style choosen by user.
1.38      ng       2747: sub keywords_highlight {
1.44      ng       2748:     my $string    = shift;
1.257     albertel 2749:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2750:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2751:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2752:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2753:     foreach my $keyword (@keylist) {
                   2754: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2755:     }
                   2756:     return $string;
1.38      ng       2757: }
1.36      ng       2758: 
1.671     raeburn  2759: # For Tasks provide a mechanism to display previous version for one specific student
                   2760: 
                   2761: sub show_previous_task_version {
                   2762:     my ($request,$symb) = @_;
                   2763:     if ($symb eq '') {
1.717     bisitz   2764:         $request->print(
                   2765:             '<span class="LC_error">'.
                   2766:             &mt('Unable to handle ambiguous references.').
                   2767:             '</span>');
1.671     raeburn  2768:         return '';
                   2769:     }
                   2770:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2771:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2772:     if (!&canview($usec)) {
1.712     bisitz   2773:         $request->print(
                   2774:             '<span class="LC_warning">'.
1.713     bisitz   2775:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2776:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2777:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2778:             '</span>');
1.671     raeburn  2779:         return;
                   2780:     }
                   2781:     my $mode = 'both';
                   2782:     my $isTask = ($symb =~/\.task$/);
                   2783:     if ($isTask) {
                   2784:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2785:             if ($env{'form.fullname'} eq '') {
                   2786:                 $env{'form.fullname'} =
                   2787:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2788:             }
                   2789:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2790:             $request->print("\n\n".
                   2791:                             '<div class="LC_grade_show_user">'.
                   2792:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2793:                             '</h2>'."\n");
                   2794:             &Apache::lonxml::clear_problem_counter();
                   2795:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2796:                             {'previousversion' => $env{'form.previousversion'} }));
                   2797:             $request->print("\n</div>");
                   2798:         }
                   2799:     }
                   2800:     return;
                   2801: }
                   2802: 
                   2803: sub choose_task_version_form {
                   2804:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2805:     my $isTask = ($symb =~/\.task$/);
                   2806:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2807:     if ($isTask) {
                   2808:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2809:                                               $udom,$uname);
                   2810:         if (($record{'resource.0.version'} eq '') ||
                   2811:             ($record{'resource.0.version'} < 2)) {
                   2812:             return ($record{'resource.0.version'},
                   2813:                     $record{'resource.0.version'},$result,$js);
                   2814:         } else {
                   2815:             $current = $record{'resource.0.version'};
                   2816:         }
                   2817:         if ($env{'form.previousversion'}) {
                   2818:             $displayed = $env{'form.previousversion'};
                   2819:             $rowtitle = &mt('Choose another version:')
                   2820:         } else {
                   2821:             $displayed = $current;
                   2822:             $rowtitle = &mt('Show earlier version:');
                   2823:         }
                   2824:         $result = '<div class="LC_left_float">';
                   2825:         my $list;
                   2826:         my $numversions = 0;
                   2827:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2828:             if ($i == $current) {
                   2829:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2830:                     next;
                   2831:                 } else {
                   2832:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2833:                     $numversions ++;
                   2834:                 }
                   2835:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2836:                 unless ($i == $env{'form.previousversion'}) {
                   2837:                     $numversions ++;
                   2838:                 }
                   2839:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2840:             }
                   2841:         }
                   2842:         if ($numversions) {
                   2843:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2844:             $result .=
                   2845:                 '<form name="getprev" method="post" action=""'.
                   2846:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2847:                 &Apache::loncommon::start_data_table().
                   2848:                 &Apache::loncommon::start_data_table_row().
                   2849:                 '<th align="left">'.$rowtitle.'</th>'.
                   2850:                 '<td><select name="version">'.
                   2851:                 '<option>'.&mt('Select').'</option>'.
                   2852:                 $list.
                   2853:                 '</select></td>'.
                   2854:                 &Apache::loncommon::end_data_table_row();
                   2855:             unless ($nomenu) {
                   2856:                 $result .= &Apache::loncommon::start_data_table_row().
                   2857:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2858:                 '<td><span class="LC_nobreak">'.
                   2859:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2860:                 &mt('Yes').'</label>'.
                   2861:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2862:                 '</span></td>'.
                   2863:                 &Apache::loncommon::end_data_table_row();
                   2864:             }
                   2865:             $result .=
                   2866:                 &Apache::loncommon::start_data_table_row().
                   2867:                 '<th align="left">&nbsp;</th>'.
                   2868:                 '<td>'.
                   2869:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2870:                 '</td>'.
                   2871:                 &Apache::loncommon::end_data_table_row().
                   2872:                 &Apache::loncommon::end_data_table().
                   2873:                 '</form>';
                   2874:             $js = &previous_display_javascript($nomenu,$current);
                   2875:         } elsif ($displayed && $nomenu) {
                   2876:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2877:         } else {
                   2878:             $result .= &mt('No previous versions to show for this student');
                   2879:         }
                   2880:         $result .= '</div>';
                   2881:     }
                   2882:     return ($current,$displayed,$result,$js);
                   2883: }
                   2884: 
                   2885: sub previous_display_javascript {
                   2886:     my ($nomenu,$current) = @_;
                   2887:     my $js = <<"JSONE";
                   2888: <script type="text/javascript">
                   2889: // <![CDATA[
                   2890: function previousVersion(uname,udom,symb) {
                   2891:     var current = '$current';
                   2892:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2893:     var prevstr = new RegExp("^\\\\d+\$");
                   2894:     if (!prevstr.test(version)) {
                   2895:         return false;
                   2896:     }
                   2897:     var url = '';
                   2898:     if (version == current) {
                   2899:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2900:     } else {
                   2901:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2902:     }
                   2903: JSONE
                   2904:     if ($nomenu) {
                   2905:         $js .= <<"JSTWO";
                   2906:     document.location.href = url;
                   2907: JSTWO
                   2908:     } else {
                   2909:         $js .= <<"JSTHREE";
                   2910:     var newwin = 0;
                   2911:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2912:         if (document.getprev.prevwin[i].checked == true) {
                   2913:             newwin = document.getprev.prevwin[i].value;
                   2914:         }
                   2915:     }
                   2916:     if (newwin == 1) {
                   2917:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2918:         url = url+'&inhibitmenu=yes';
                   2919:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2920:             previousWin = window.open(url,'',options,1);
                   2921:         } else {
                   2922:             previousWin.location.href = url;
                   2923:         }
                   2924:         previousWin.focus();
                   2925:         return false;
                   2926:     } else {
                   2927:         document.location.href = url;
                   2928:         return false;
                   2929:     }
                   2930: JSTHREE
                   2931:     }
                   2932:     $js .= <<"ENDJS";
                   2933:     return false;
                   2934: }
                   2935: // ]]>
                   2936: </script>
                   2937: ENDJS
                   2938: 
                   2939: }
                   2940: 
1.44      ng       2941: #--- Called from submission routine
1.38      ng       2942: sub processHandGrade {
1.608     www      2943:     my ($request,$symb) = @_;
1.324     albertel 2944:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2945:     my $button = $env{'form.gradeOpt'};
                   2946:     my $ngrade = $env{'form.NCT'};
                   2947:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2948:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2949:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2950: 
1.44      ng       2951:     if ($button eq 'Save & Next') {
                   2952: 	my $ctr = 0;
                   2953: 	while ($ctr < $ngrade) {
1.257     albertel 2954: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2955: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2956:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2957: 	    if ($errorflag eq 'no_score') {
                   2958: 		$ctr++;
                   2959: 		next;
                   2960: 	    }
1.104     albertel 2961: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2962: 		$request->print(
                   2963:                     '<span class="LC_error">'
                   2964:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2965:                    .'</span>');
1.104     albertel 2966: 		$ctr++;
                   2967: 		next;
                   2968: 	    }
1.726     raeburn  2969:             if ($numhidden) {
                   2970:                 $request->print(
                   2971:                     '<span class="LC_info">'
                   2972:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2973:                    .'</span><br />');
                   2974:             }
1.257     albertel 2975: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2976: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2977: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2978:             my ($feedurl,$showsymb) =
                   2979: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2980: 	    my $messagetail;
1.62      albertel 2981: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2982: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2983: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2984: 		$subject.=' ['.$restitle.']';
1.44      ng       2985: 		my (@msgnum) = split(/,/,$includemsg);
                   2986: 		foreach (@msgnum) {
1.257     albertel 2987: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2988: 		}
1.80      ng       2989: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2990: 		if ($env{'form.withgrades'.$ctr}) {
                   2991: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2992: 		    $messagetail = " for <a href=\"".
1.605     www      2993: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2994: 		}
                   2995: 		$msgstatus = 
                   2996:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2997: 						     $message.$messagetail,
1.418     albertel 2998:                                                      undef,$feedurl,undef,
1.386     raeburn  2999:                                                      undef,undef,$showsymb,
                   3000:                                                      $restitle);
1.574     bisitz   3001: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3002: 				$msgstatus.'<br />');
1.44      ng       3003: 	    }
1.257     albertel 3004: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3005: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3006: 		foreach my $collabstr (@collabstrs) {
                   3007: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3008: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3009: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3010: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3011: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3012: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3013: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3014: 			    next;
1.418     albertel 3015: 			} elsif ($message ne '') {
                   3016: 			    my ($baseurl,$showsymb) = 
                   3017: 				&get_feedurl_and_symb($symb,$collaborator,
                   3018: 						      $udom);
                   3019: 			    if ($env{'form.withgrades'.$ctr}) {
                   3020: 				$messagetail = " for <a href=\"".
1.605     www      3021:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3022: 			    }
1.418     albertel 3023: 			    $msgstatus = 
                   3024: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3025: 			}
1.44      ng       3026: 		    }
                   3027: 		}
                   3028: 	    }
                   3029: 	    $ctr++;
                   3030: 	}
                   3031:     }
                   3032: 
1.624     www      3033: #    if ($env{'form.handgrade'} eq 'yes') {
                   3034:     if (1) {
1.119     ng       3035: 	# Keywords sorted in alphabatical order
1.257     albertel 3036: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       3037: 	my %keyhash = ();
1.257     albertel 3038: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3039: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3040: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3041: 	$env{'form.keywords'} = join(' ',@keywords);
                   3042: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3043: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3044: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3045: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3046: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       3047: 
                   3048: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3049: 	# New messages are saved in env for the next student.
1.119     ng       3050: 	# All messages are saved in nohist_handgrade.db
                   3051: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3052: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3053: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3054: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3055: 		$idx++;
                   3056: 	    }
                   3057: 	    $ctr++;
1.41      ng       3058: 	}
1.119     ng       3059: 	$ctr = 0;
                   3060: 	while ($ctr < $ngrade) {
1.257     albertel 3061: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3062: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3063: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3064: 		$idx++;
                   3065: 	    }
                   3066: 	    $ctr++;
1.41      ng       3067: 	}
1.257     albertel 3068: 	$env{'form.savemsgN'} = --$idx;
                   3069: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       3070: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3071: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3072:     }
1.44      ng       3073:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3074:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3075:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3076: 	my ($ctr,$total) = (0,0);
                   3077: 	while ($ctr < $ngrade) {
1.257     albertel 3078: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3079: 	    $ctr++;
                   3080: 	}
1.257     albertel 3081: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3082: 	$ctr = 0;
                   3083: 	while ($ctr < $total) {
1.257     albertel 3084: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3085: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3086: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3087: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3088: 	    $ctr++;
                   3089: 	}
                   3090: 	return '';
                   3091:     }
1.36      ng       3092: 
1.44      ng       3093:     # Get the next/previous one or group of students
1.257     albertel 3094:     my $firststu = $env{'form.unamedom0'};
                   3095:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3096:     my $ctr = 2;
1.41      ng       3097:     while ($laststu eq '') {
1.257     albertel 3098: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3099: 	$ctr++;
                   3100: 	$laststu = $firststu if ($ctr > $ngrade);
                   3101:     }
1.44      ng       3102: 
1.41      ng       3103:     my (@parsedlist,@nextlist);
                   3104:     my ($nextflg) = 0;
1.524     raeburn  3105:     foreach my $item (sort 
1.294     albertel 3106: 	     {
                   3107: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3108: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3109: 		 }
                   3110: 		 return $a cmp $b;
                   3111: 	     } (keys(%$fullname))) {
1.605     www      3112: # FIXME: this is fishy, looks like the button label
1.41      ng       3113: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3114: 	    push(@parsedlist,$item);
1.41      ng       3115: 	}
1.524     raeburn  3116: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3117: 	if ($button eq 'Previous') {
1.524     raeburn  3118: 	    last if ($item eq $firststu);
                   3119: 	    push(@parsedlist,$item);
1.41      ng       3120: 	}
                   3121:     }
                   3122:     $ctr = 0;
1.605     www      3123: # FIXME: this is fishy, looks like the button label
1.41      ng       3124:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3125:     my $res_error;
                   3126:     my ($partlist) = &response_type($symb,\$res_error);
                   3127:     if ($res_error) {
                   3128:         $request->print(&navmap_errormsg());
                   3129:         return;
                   3130:     }
1.41      ng       3131:     foreach my $student (@parsedlist) {
1.257     albertel 3132: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3133: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3134: 	
                   3135: 	if ($submitonly eq 'queued') {
                   3136: 	    my %queue_status = 
                   3137: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3138: 							$udom,$uname);
                   3139: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3140: 	}
                   3141: 
1.156     albertel 3142: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3143: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3144: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3145: 	    my $submitted = 0;
1.248     albertel 3146: 	    my $ungraded = 0;
                   3147: 	    my $incorrect = 0;
1.524     raeburn  3148: 	    foreach my $item (keys(%status)) {
                   3149: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3150: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3151: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3152: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3153: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3154: 		    $submitted = 0;
                   3155: 		}
1.41      ng       3156: 	    }
1.156     albertel 3157: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3158: 				     $submitonly eq 'incorrect' ||
                   3159: 				     $submitonly eq 'graded'));
1.248     albertel 3160: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3161: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3162: 	}
1.524     raeburn  3163: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3164: 	last if ($ctr == $ntstu);
1.41      ng       3165: 	$ctr++;
                   3166:     }
1.36      ng       3167: 
1.41      ng       3168:     $ctr = 0;
                   3169:     my $total = scalar(@nextlist)-1;
1.39      ng       3170: 
1.524     raeburn  3171:     foreach (sort(@nextlist)) {
1.41      ng       3172: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3173: 	$env{'form.student'}  = $uname;
                   3174: 	$env{'form.userdom'}  = $udom;
                   3175: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3176: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3177: 	$ctr++;
                   3178:     }
                   3179:     if ($total < 0) {
1.653     raeburn  3180: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3181: 	$request->print($the_end);
                   3182:     }
                   3183:     return '';
1.38      ng       3184: }
1.36      ng       3185: 
1.44      ng       3186: #---- Save the score and award for each student, if changed
1.38      ng       3187: sub saveHandGrade {
1.324     albertel 3188:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3189:     my @version_parts;
1.104     albertel 3190:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3191: 					   $env{'request.course.id'});
1.104     albertel 3192:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3193:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3194:     my @parts_graded;
1.77      ng       3195:     my %newrecord  = ();
1.726     raeburn  3196:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3197:     my %aggregate = ();
                   3198:     my $aggregateflag = 0;
1.726     raeburn  3199:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3200:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3201:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3202:         $totchg += $numchgs;
                   3203:     }
1.301     albertel 3204:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3205:     foreach my $new_part (@parts) {
1.337     banghart 3206: 	#collaborator ($submi may vary for different parts
1.259     banghart 3207: 	if ($submitter && $new_part ne $part) { next; }
                   3208: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3209: 	if ($dropMenu eq 'excused') {
1.259     banghart 3210: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3211: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3212: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3213: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3214: 		}
1.364     banghart 3215: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3216: 	    }
1.125     ng       3217: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3218: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3219: 	    foreach my $key (keys(%record)) {
1.259     banghart 3220: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3221: 	    }
1.259     banghart 3222: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3223: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3224:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3225: 
                   3226:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3227: 					       [$new_part]);
                   3228:             my $aggtries =$totaltries;
1.269     raeburn  3229:             if ($last_resets{$new_part}) {
1.270     albertel 3230:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3231: 					   $new_part);
1.269     raeburn  3232:             }
1.270     albertel 3233: 
                   3234:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3235:             if ($aggtries > 0) {
1.327     albertel 3236:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3237:                 $aggregateflag = 1;
                   3238:             }
1.125     ng       3239: 	} elsif ($dropMenu eq '') {
1.259     banghart 3240: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3241: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3242: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3243: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3244: 		next;
                   3245: 	    }
1.259     banghart 3246: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3247: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3248: 	    my $partial= $pts/$wgt;
1.259     banghart 3249: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3250: 		#do not update score for part if not changed.
1.346     banghart 3251:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3252: 		next;
1.251     banghart 3253: 	    } else {
1.524     raeburn  3254: 	        push(@parts_graded,$new_part);
1.153     albertel 3255: 	    }
1.259     banghart 3256: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3257: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3258: 	    }
1.259     banghart 3259: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3260: 	    if ($partial == 0) {
1.153     albertel 3261: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3262: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3263: 		}
1.41      ng       3264: 	    } else {
1.153     albertel 3265: 		if ($record{$reckey} ne 'correct_by_override') {
                   3266: 		    $newrecord{$reckey} = 'correct_by_override';
                   3267: 		}
                   3268: 	    }	    
                   3269: 	    if ($submitter && 
1.259     banghart 3270: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3271: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3272: 	    }
1.259     banghart 3273: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3274: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3275: 	}
1.259     banghart 3276: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3277: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3278: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3279: 	        $dropMenu eq 'reset status')
                   3280: 	   {
1.524     raeburn  3281: 	    push(@version_parts,$new_part);
1.259     banghart 3282: 	}
1.41      ng       3283:     }
1.301     albertel 3284:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3285:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3286: 
1.344     albertel 3287:     if (%newrecord) {
                   3288:         if (@version_parts) {
1.364     banghart 3289:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3290:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3291: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3292: 	    foreach my $new_part (@version_parts) {
                   3293: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3294: 				$new_part,\%newrecord);
                   3295: 	    }
1.259     banghart 3296:         }
1.44      ng       3297: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3298: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3299: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3300: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3301:     }
1.269     raeburn  3302:     if ($aggregateflag) {
                   3303:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3304: 			      $cdom,$cnum);
1.269     raeburn  3305:     }
1.726     raeburn  3306:     return ('',$pts,$wgt,$totchg);
                   3307: }
                   3308: 
                   3309: sub makehidden {
1.728     raeburn  3310:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3311:     return unless (ref($record) eq 'HASH');
                   3312:     my %modified;
                   3313:     my $numchanged = 0;
                   3314:     if (exists($record->{$version.':keys'})) {
                   3315:         my $partsregexp = $parts;
                   3316:         $partsregexp =~ s/,/|/g;
                   3317:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3318:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3319:                  my $item = $1;
                   3320:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3321:                      $modified{$key} = $record->{$version.':'.$key};
                   3322:                  }
                   3323:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3324:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3325:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3326:                 $modified{$key} = $record->{$version.':'.$key};
                   3327:             }
                   3328:         }
                   3329:         if (keys(%modified)) {
                   3330:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3331:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3332:                 $numchanged ++;
                   3333:             }
                   3334:         }
                   3335:     }
                   3336:     return $numchanged;
1.36      ng       3337: }
1.322     albertel 3338: 
1.380     albertel 3339: sub check_and_remove_from_queue {
                   3340:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3341:     my @ungraded_parts;
                   3342:     foreach my $part (@{$parts}) {
                   3343: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3344: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3345: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3346: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3347: 		) {
                   3348: 	    push(@ungraded_parts, $part);
                   3349: 	}
                   3350:     }
                   3351:     if ( !@ungraded_parts ) {
                   3352: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3353: 					       $cnum,$domain,$stuname);
                   3354:     }
                   3355: }
                   3356: 
1.337     banghart 3357: sub handback_files {
                   3358:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3359:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3360:     my $res_error;
                   3361:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3362:     if ($res_error) {
                   3363:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3364:         return;
                   3365:     }
1.654     raeburn  3366:     my @handedback;
                   3367:     my $file_msg;
1.375     albertel 3368:     my @part_response_id = &flatten_responseType($responseType);
                   3369:     foreach my $part_response_id (@part_response_id) {
                   3370:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3371: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3372:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3373:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3374:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3375:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3376:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3377:                     my ($directory,$answer_file) = 
1.654     raeburn  3378:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3379:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3380: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3381: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3382:                     my $getpropath = 1;
1.662     raeburn  3383:                     my ($dir_list,$listerror) = 
                   3384:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3385:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3386: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3387:                     # fix filename
1.355     banghart 3388:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3389:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3390:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3391:             	                                $save_file_name);
1.337     banghart 3392:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3393:                         $request->print('<br /><span class="LC_error">'.
                   3394:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3395:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3396:                                         '</span>');
1.356     banghart 3397:                     } else {
1.360     banghart 3398:                         # mark the file as read only
1.654     raeburn  3399:                         push(@handedback,$save_file_name);
1.367     albertel 3400: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3401: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3402: 			}
                   3403:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3404: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3405:                     }
1.686     bisitz   3406:                     $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 3407:                 }
                   3408:             }
                   3409:         }
1.654     raeburn  3410:     }
                   3411:     if (@handedback > 0) {
                   3412:         $request->print('<br />');
                   3413:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3414:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3415:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3416:         my ($subject,$message);
                   3417:         if (scalar(@handedback) == 1) {
                   3418:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3419:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3420:         } else {
                   3421:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3422:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3423:         }
                   3424:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3425:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3426:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3427:         my ($feedurl,$showsymb) =
                   3428:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3429:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3430:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3431:         my $msgstatus =
                   3432:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3433:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3434:                  $restitle);
                   3435:         if ($msgstatus) {
                   3436:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3437:         }
                   3438:     }
1.338     banghart 3439:     return;
1.337     banghart 3440: }
                   3441: 
1.418     albertel 3442: sub get_feedurl_and_symb {
                   3443:     my ($symb,$uname,$udom) = @_;
                   3444:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3445:     $url = &Apache::lonnet::clutter($url);
                   3446:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3447: 					$symb,$udom,$uname);
                   3448:     if ($encrypturl =~ /^yes$/i) {
                   3449: 	&Apache::lonenc::encrypted(\$url,1);
                   3450: 	&Apache::lonenc::encrypted(\$symb,1);
                   3451:     }
                   3452:     return ($url,$symb);
                   3453: }
                   3454: 
1.313     banghart 3455: sub get_submitted_files {
                   3456:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3457:     my @files;
                   3458:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3459:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3460:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3461:     	    push(@files,$file_url.$file);
                   3462:         }
                   3463:     }
                   3464:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3465:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3466:     }
                   3467:     return (\@files);
                   3468: }
1.322     albertel 3469: 
1.269     raeburn  3470: # ----------- Provides number of tries since last reset.
                   3471: sub get_num_tries {
                   3472:     my ($record,$last_reset,$part) = @_;
                   3473:     my $timestamp = '';
                   3474:     my $num_tries = 0;
                   3475:     if ($$record{'version'}) {
                   3476:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3477:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3478:                 $timestamp = $$record{$version.':timestamp'};
                   3479:                 if ($timestamp > $last_reset) {
                   3480:                     $num_tries ++;
                   3481:                 } else {
                   3482:                     last;
                   3483:                 }
                   3484:             }
                   3485:         }
                   3486:     }
                   3487:     return $num_tries;
                   3488: }
                   3489: 
                   3490: # ----------- Determine decrements required in aggregate totals 
                   3491: sub decrement_aggs {
                   3492:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3493:     my %decrement = (
                   3494:                         attempts => 0,
                   3495:                         users => 0,
                   3496:                         correct => 0
                   3497:                     );
                   3498:     $decrement{'attempts'} = $aggtries;
                   3499:     if ($solvedstatus =~ /^correct/) {
                   3500:         $decrement{'correct'} = 1;
                   3501:     }
                   3502:     if ($aggtries == $totaltries) {
                   3503:         $decrement{'users'} = 1;
                   3504:     }
1.524     raeburn  3505:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3506:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3507:     }
                   3508:     return;
                   3509: }
                   3510: 
                   3511: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3512: sub get_last_resets {
1.270     albertel 3513:     my ($symb,$courseid,$partids) =@_;
                   3514:     my %last_resets;
1.269     raeburn  3515:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3516:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3517:     my @keys;
                   3518:     foreach my $part (@{$partids}) {
                   3519: 	push(@keys,"$symb\0$part\0resettime");
                   3520:     }
                   3521:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3522: 				     $cdom,$cname);
                   3523:     foreach my $part (@{$partids}) {
                   3524: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3525:     }
1.270     albertel 3526:     return %last_resets;
1.269     raeburn  3527: }
                   3528: 
1.251     banghart 3529: # ----------- Handles creating versions for portfolio files as answers
                   3530: sub version_portfiles {
1.343     banghart 3531:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3532:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3533:     my @returned_keys;
1.255     banghart 3534:     my $parts = join('|', @$parts_graded);
1.277     albertel 3535:     foreach my $key (keys(%$record)) {
1.259     banghart 3536:         my $new_portfiles;
1.263     banghart 3537:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3538:             my @versioned_portfiles;
1.367     albertel 3539:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3540:             if (@portfiles) {
                   3541:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3542:                                                       \@versioned_portfiles);
1.252     banghart 3543:             }
1.343     banghart 3544:             $$record{$key} = join(',',@versioned_portfiles);
                   3545:             push(@returned_keys,$key);
1.251     banghart 3546:         }
                   3547:     } 
1.343     banghart 3548:     return (@returned_keys);   
1.305     banghart 3549: }
                   3550: 
1.44      ng       3551: #--------------------------------------------------------------------------------------
                   3552: #
                   3553: #-------------------------- Next few routines handles grading by section or whole class
                   3554: #
                   3555: #--- Javascript to handle grading by section or whole class
1.42      ng       3556: sub viewgrades_js {
                   3557:     my ($request) = shift;
                   3558: 
1.539     riegler  3559:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3560:     &js_escape(\$alertmsg);
1.597     wenzelju 3561:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3562:    function writePoint(partid,weight,point) {
1.125     ng       3563: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3564: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3565: 	if (point == "textval") {
1.125     ng       3566: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3567: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3568: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3569: 		var resetbox = false;
                   3570: 		for (var i=0; i<radioButton.length; i++) {
                   3571: 		    if (radioButton[i].checked) {
                   3572: 			textbox.value = i;
                   3573: 			resetbox = true;
                   3574: 		    }
                   3575: 		}
                   3576: 		if (!resetbox) {
                   3577: 		    textbox.value = "";
                   3578: 		}
                   3579: 		return;
                   3580: 	    }
1.109     matthew  3581: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3582: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3583: 				   ") greater than the weight for the part. Accept?");
                   3584: 		if (resp == false) {
                   3585: 		    textbox.value = "";
                   3586: 		    return;
                   3587: 		}
                   3588: 	    }
1.42      ng       3589: 	    for (var i=0; i<radioButton.length; i++) {
                   3590: 		radioButton[i].checked=false;
1.109     matthew  3591: 		if (parseFloat(point) == i) {
1.42      ng       3592: 		    radioButton[i].checked=true;
                   3593: 		}
                   3594: 	    }
1.41      ng       3595: 
1.42      ng       3596: 	} else {
1.125     ng       3597: 	    textbox.value = parseFloat(point);
1.42      ng       3598: 	}
1.41      ng       3599: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3600: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3601: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3602: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3603: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3604: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3605: 	    if (saveval != "correct") {
                   3606: 		scorename.value = point;
1.43      ng       3607: 		if (selname[0].selected != true) {
                   3608: 		    selname[0].selected = true;
                   3609: 		}
1.42      ng       3610: 	    }
                   3611: 	}
1.125     ng       3612: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3613:     }
                   3614: 
                   3615:     function writeRadText(partid,weight) {
1.125     ng       3616: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3617: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3618:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3619: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3620: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3621: 	    for (var i=0; i<radioButton.length; i++) {
                   3622: 		radioButton[i].checked=false;
                   3623: 
                   3624: 	    }
                   3625: 	    textbox.value = "";
                   3626: 
                   3627: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3628: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3629: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3630: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3631: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3632: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3633: 		if ((saveval != "correct") || override) {
1.42      ng       3634: 		    scorename.value = "";
1.125     ng       3635: 		    if (selval[1].selected) {
                   3636: 			selname[1].selected = true;
                   3637: 		    } else {
                   3638: 			selname[2].selected = true;
                   3639: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3640: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3641: 		    }
1.42      ng       3642: 		}
                   3643: 	    }
1.43      ng       3644: 	} else {
                   3645: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3646: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3647: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3648: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3649: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3650: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3651: 		if ((saveval != "correct") || override) {
1.125     ng       3652: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3653: 		    selname[0].selected = true;
                   3654: 		}
                   3655: 	    }
                   3656: 	}	    
1.42      ng       3657:     }
                   3658: 
                   3659:     function changeSelect(partid,user) {
1.125     ng       3660: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3661: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3662: 	var point  = textbox.value;
1.125     ng       3663: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3664: 
1.109     matthew  3665: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3666: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3667: 	    textbox.value = "";
                   3668: 	    return;
                   3669: 	}
1.109     matthew  3670: 	if (parseFloat(point) > parseFloat(weight)) {
                   3671: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3672: 			       ") greater than the weight of the part. Accept?");
                   3673: 	    if (resp == false) {
                   3674: 		textbox.value = "";
                   3675: 		return;
                   3676: 	    }
                   3677: 	}
1.42      ng       3678: 	selval[0].selected = true;
                   3679:     }
                   3680: 
                   3681:     function changeOneScore(partid,user) {
1.125     ng       3682: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3683: 	if (selval[1].selected || selval[2].selected) {
                   3684: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3685: 	    if (selval[2].selected) {
                   3686: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3687: 	    }
1.269     raeburn  3688:         }
1.42      ng       3689:     }
                   3690: 
                   3691:     function resetEntry(numpart) {
                   3692: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3693: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3694: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3695: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3696: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3697: 	    for (var i=0; i<radioButton.length; i++) {
                   3698: 		radioButton[i].checked=false;
                   3699: 
                   3700: 	    }
                   3701: 	    textbox.value = "";
                   3702: 	    selval[0].selected = true;
                   3703: 
                   3704: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3705: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3706: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3707: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3708: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3709: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3710: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3711: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3712: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3713: 		if (saveselval == "excused") {
1.43      ng       3714: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3715: 		} else {
1.43      ng       3716: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3717: 		}
                   3718: 	    }
1.41      ng       3719: 	}
1.42      ng       3720:     }
                   3721: 
1.41      ng       3722: VIEWJAVASCRIPT
1.42      ng       3723: }
                   3724: 
1.44      ng       3725: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3726: sub viewgrades {
1.608     www      3727:     my ($request,$symb) = @_;
1.745     raeburn  3728:     my ($is_tool,$toolsymb);
                   3729:     if ($symb =~ /ext\.tool$/) {
                   3730:         $is_tool = 1;
                   3731:         $toolsymb = $symb;
                   3732:     }
1.42      ng       3733:     &viewgrades_js($request);
1.41      ng       3734: 
1.168     albertel 3735:     #need to make sure we have the correct data for later EXT calls, 
                   3736:     #thus invalidate the cache
                   3737:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3738:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3739:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3740:     &Apache::lonnet::clear_EXT_cache_status();
                   3741: 
1.398     albertel 3742:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3743: 
                   3744:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3745:     $result.=&jscriptNform($symb);
1.41      ng       3746: 
1.44      ng       3747:     #beginning of class grading form
1.442     banghart 3748:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3749:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3750: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3751: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3752: 	&build_section_inputs().
1.442     banghart 3753: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3754: 
1.738     raeburn  3755:     #retrieve selected groups
                   3756:     my (@groups,$group_display);
                   3757:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3758:     if (grep(/^all$/,@groups)) {
                   3759:         @groups = ('all');
                   3760:     } elsif (grep(/^none$/,@groups)) {
                   3761:         @groups = ('none');
                   3762:     } elsif (@groups > 0) {
                   3763:         $group_display = join(', ',@groups);
                   3764:     }
                   3765: 
                   3766:     my ($common_header,$specific_header,@sections,$section_display);
                   3767:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3768:     if (grep(/^all$/,@sections)) {
                   3769:         @sections = ('all');
                   3770:         if ($group_display) {
                   3771:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3772:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3773:         } elsif (grep(/^none$/,@groups)) {
                   3774:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3775:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3776:         } else {
                   3777: 	    $common_header = &mt('Assign Common Grade to Class');
                   3778:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3779:         }
                   3780:     } elsif (grep(/^none$/,@sections)) {
                   3781:         @sections = ('none');
                   3782:         if ($group_display) {
                   3783:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3784:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3785:         } elsif (grep(/^none$/,@groups)) {
                   3786:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3787:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3788:         } else {
                   3789:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3790: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3791:         }
                   3792:     } else {
                   3793:         $section_display = join (", ",@sections);
                   3794:         if ($group_display) {
                   3795:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3796:                                  $section_display,$group_display);
                   3797:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3798:                                    $section_display,$group_display);
                   3799:         } elsif (grep(/^none$/,@groups)) {
                   3800:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3801:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3802:         } else {
                   3803:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3804: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3805:         }
                   3806:     }
                   3807:     my %submit_types = &substatus_options();
                   3808:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3809: 
                   3810:     if ($env{'form.submitonly'} eq 'all') {
                   3811:         $result.= '<h3>'.$common_header.'</h3>';
                   3812:     } else {
1.745     raeburn  3813:         my $text;
                   3814:         if ($is_tool) {
                   3815:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3816:         } else {
                   3817:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3818:         }
                   3819:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3820:     }
1.738     raeburn  3821:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3822:     #radio buttons/text box for assigning points for a section or class.
                   3823:     #handles different parts of a problem
1.582     raeburn  3824:     my $res_error;
                   3825:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3826:     if ($res_error) {
                   3827:         return &navmap_errormsg();
                   3828:     }
1.42      ng       3829:     my %weight = ();
                   3830:     my $ctsparts = 0;
1.45      ng       3831:     my %seen = ();
1.745     raeburn  3832:     my @part_response_id;
                   3833:     if ($is_tool) {
                   3834:         @part_response_id = ([0,'']);
                   3835:     } else {
                   3836:         @part_response_id = &flatten_responseType($responseType);
                   3837:     }
1.375     albertel 3838:     foreach my $part_response_id (@part_response_id) {
                   3839:     	my ($partid,$respid) = @{ $part_response_id };
                   3840: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3841: 	next if $seen{$partid};
                   3842: 	$seen{$partid}++;
1.744     raeburn  3843: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3844: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3845: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3846: 
1.324     albertel 3847: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3848: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3849: 	my $ctr = 0;
1.42      ng       3850: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3851: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3852: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3853: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3854: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3855: 	    $ctr++;
                   3856: 	}
1.485     albertel 3857: 	$radio.='</tr></table>';
                   3858: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3859: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3860: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3861: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3862:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3863:             '<select name="SELVAL_'.$partid.'" '.
                   3864:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3865:                 $weight{$partid}.')"> '.
1.401     albertel 3866: 	    '<option selected="selected"> </option>'.
1.485     albertel 3867: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3868: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3869: 	    '</select></td>'.
                   3870:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3871: 	$line.='<input type="hidden" name="partid_'.
                   3872: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3873: 	$line.='<input type="hidden" name="weight_'.
                   3874: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3875: 
                   3876: 	$result.=
                   3877: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3878: 	    '<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 3879: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3880: 	$ctsparts++;
1.41      ng       3881:     }
1.474     albertel 3882:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3883: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3884:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3885: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3886: 
1.44      ng       3887:     #table listing all the students in a section/class
                   3888:     #header of table
1.738     raeburn  3889:     if ($env{'form.submitonly'} eq 'all') {
                   3890:         $result.= '<h3>'.$specific_header.'</h3>';
                   3891:     } else {
1.745     raeburn  3892:         my $text;
                   3893:         if ($is_tool) {
                   3894:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3895:         } else {
                   3896:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3897:         }
                   3898:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3899:     }
                   3900:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3901: 	      &Apache::loncommon::start_data_table_header_row().
                   3902: 	      '<th>'.&mt('No.').'</th>'.
                   3903: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3904:     my $partserror;
                   3905:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3906:     if ($partserror) {
                   3907:         return &navmap_errormsg();
                   3908:     }
1.324     albertel 3909:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3910:     my @partids = ();
1.41      ng       3911:     foreach my $part (@parts) {
1.745     raeburn  3912: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3913:         my $narrowtext = &mt('Tries');
                   3914: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3915: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3916: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3917:         push(@partids,$partid);
1.628     www      3918: #
                   3919: # FIXME: Looks like $display looks at English text
                   3920: #
1.324     albertel 3921: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3922: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3923: 	    $result.='<th>'.
1.697     bisitz   3924: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3925: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3926: 	    next;
1.485     albertel 3927: 	    
1.207     albertel 3928: 	} else {
1.485     albertel 3929: 	    if ($display =~ /Problem Status/) {
                   3930: 		my $grade_status_mt = &mt('Grade Status');
                   3931: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3932: 	    }
                   3933: 	    my $part_mt = &mt('Part:');
                   3934: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3935: 	}
1.485     albertel 3936: 
1.474     albertel 3937: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3938:     }
1.474     albertel 3939:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3940: 
1.270     albertel 3941:     my %last_resets = 
                   3942: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3943: 
1.41      ng       3944:     #get info for each student
1.44      ng       3945:     #list all the students - with points and grade status
1.738     raeburn  3946:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3947:     my $ctr = 0;
1.294     albertel 3948:     foreach (sort 
                   3949: 	     {
                   3950: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3951: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3952: 		 }
                   3953: 		 return $a cmp $b;
                   3954: 	     } (keys(%$fullname))) {
1.324     albertel 3955: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  3956: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       3957:     }
1.474     albertel 3958:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3959:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3960:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3961: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  3962:     if ($ctr == 0) {
1.442     banghart 3963:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  3964:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3965:                 '<span class="LC_warning">';
                   3966:         if ($env{'form.submitonly'} eq 'all') {
                   3967:             if (grep(/^all$/,@sections)) {
                   3968:                 if (grep(/^all$/,@groups)) {
                   3969:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3970:                                    $stu_status);
                   3971:                 } elsif (grep(/^none$/,@groups)) {
                   3972:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3973:                                    $stu_status); 
                   3974:                 } else {
                   3975:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3976:                                    $group_display,$stu_status);
                   3977:                 }
                   3978:             } elsif (grep(/^none$/,@sections)) {
                   3979:                 if (grep(/^all$/,@groups)) {
                   3980:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3981:                                    $stu_status);
                   3982:                 } elsif (grep(/^none$/,@groups)) {
                   3983:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3984:                                    $stu_status);
                   3985:                 } else {
                   3986:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3987:                                    $group_display,$stu_status);
                   3988:                 }
                   3989:             } else {
                   3990:                 if (grep(/^all$/,@groups)) {
                   3991:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3992:                                    $section_display,$stu_status);
                   3993:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  3994:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  3995:                                    $section_display,$stu_status);
                   3996:                 } else {
                   3997:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3998:                                    $section_display,$group_display,$stu_status);
                   3999:                 }
                   4000:             }
                   4001:         } else {
                   4002:             if (grep(/^all$/,@sections)) {
                   4003:                 if (grep(/^all$/,@groups)) {
                   4004:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4005:                                    $stu_status,$submission_status);
                   4006:                 } elsif (grep(/^none$/,@groups)) {
                   4007:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4008:                                    $stu_status,$submission_status);
                   4009:                 } else {
                   4010:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4011:                                    $group_display,$stu_status,$submission_status);
                   4012:                 }
                   4013:             } elsif (grep(/^none$/,@sections)) {
                   4014:                 if (grep(/^all$/,@groups)) {
                   4015:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4016:                                    $stu_status,$submission_status);
                   4017:                 } elsif (grep(/^none$/,@groups)) {
                   4018:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4019:                                    $stu_status,$submission_status);
                   4020:                 } else {
                   4021:                     $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.',
                   4022:                                    $group_display,$stu_status,$submission_status);
                   4023:                 }
                   4024:             } else {
                   4025:                 if (grep(/^all$/,@groups)) {
                   4026: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4027: 	                           $section_display,$stu_status,$submission_status);
                   4028:                 } elsif (grep(/^none$/,@groups)) {
                   4029:                     $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.',
                   4030:                                    $section_display,$stu_status,$submission_status);
                   4031:                 } else {
                   4032:                     $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.',
                   4033:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4034:                 }
                   4035:             }
                   4036:         }
                   4037: 	$result .= '</span><br />';
1.96      albertel 4038:     }
1.41      ng       4039:     return $result;
                   4040: }
                   4041: 
1.738     raeburn  4042: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4043: sub viewstudentgrade {
1.745     raeburn  4044:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4045:     my ($uname,$udom) = split(/:/,$student);
                   4046:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4047:     my $submitonly = $env{'form.submitonly'};
                   4048:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4049:         my %partstatus = ();
                   4050:         if (ref($parts) eq 'ARRAY') {
                   4051:             foreach my $apart (@{$parts}) {
                   4052:                 my ($part,$type) = &split_part_type($apart);
                   4053:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4054:                 $status = 'nothing' if ($status eq '');
                   4055:                 $partstatus{$part}      = $status;
                   4056:                 my $subkey = "resource.$part.submitted_by";
                   4057:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4058:             }
                   4059:             my $submitted = 0;
                   4060:             my $graded = 0;
                   4061:             my $incorrect = 0;
                   4062:             foreach my $key (keys(%partstatus)) {
                   4063:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4064:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4065:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4066: 
                   4067:                 my $partid = (split(/\./,$key))[1];
                   4068:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4069:                     $submitted = 0;
                   4070:                 }
                   4071:             }
                   4072:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4073:                                        $submitonly eq 'incorrect' ||
                   4074:                                        $submitonly eq 'graded'));
                   4075:             return if (!$graded && ($submitonly eq 'graded'));
                   4076:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4077:         }
                   4078:     }
                   4079:     if ($submitonly eq 'queued') {
                   4080:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4081:         my %queue_status =
                   4082:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4083:                                                     $udom,$uname);
                   4084:         return if (!defined($queue_status{'gradingqueue'}));
                   4085:     }
                   4086:     $$ctr++;
                   4087:     my %aggregates = ();
1.474     albertel 4088:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4089: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4090: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4091: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4092: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4093: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4094:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4095:     foreach my $apart (@$parts) {
                   4096: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4097: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4098:         $result.='<td align="center">';
1.269     raeburn  4099:         my ($aggtries,$totaltries);
                   4100:         unless (exists($aggregates{$part})) {
1.270     albertel 4101: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4102: 	    $aggtries = $totaltries;
1.269     raeburn  4103:             if ($$last_resets{$part}) {  
1.270     albertel 4104:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4105: 					   $part);
                   4106:             }
1.269     raeburn  4107:             $result.='<input type="hidden" name="'.
                   4108:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4109:             $result.='<input type="hidden" name="'.
                   4110:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4111:             $aggregates{$part} = 1;
                   4112:         }
1.41      ng       4113: 	if ($type eq 'awarded') {
1.320     albertel 4114: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4115: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4116: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4117: 	    $result.='<input type="text" name="'.
1.89      albertel 4118: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4119:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4120: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4121: 	} elsif ($type eq 'solved') {
                   4122: 	    my ($status,$foo)=split(/_/,$score,2);
                   4123: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4124: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4125: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4126: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4127: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4128:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4129: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4130: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4131: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4132: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4133: 	} else {
                   4134: 	    $result.='<input type="hidden" name="'.
                   4135: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4136: 		    "\n";
1.233     albertel 4137: 	    $result.='<input type="text" name="'.
1.122     ng       4138: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4139: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4140: 	}
                   4141:     }
1.474     albertel 4142:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4143:     return $result;
1.38      ng       4144: }
                   4145: 
1.44      ng       4146: #--- change scores for all the students in a section/class
                   4147: #    record does not get update if unchanged
1.38      ng       4148: sub editgrades {
1.608     www      4149:     my ($request,$symb) = @_;
1.745     raeburn  4150:     my $toolsymb;
                   4151:     if ($symb =~ /ext\.tool$/) {
                   4152:         $toolsymb = $symb;
                   4153:     }
1.41      ng       4154: 
1.433     banghart 4155:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4156:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 4157:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       4158: 
1.477     albertel 4159:     my $result= &Apache::loncommon::start_data_table().
                   4160: 	&Apache::loncommon::start_data_table_header_row().
                   4161: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4162: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4163:     my %scoreptr = (
                   4164: 		    'correct'  =>'correct_by_override',
                   4165: 		    'incorrect'=>'incorrect_by_override',
                   4166: 		    'excused'  =>'excused',
                   4167: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4168:                     'credited' =>'credit_attempted',
1.43      ng       4169: 		    'nothing'  => '',
                   4170: 		    );
1.257     albertel 4171:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4172: 
1.44      ng       4173:     my (@partid);
                   4174:     my %weight = ();
1.54      albertel 4175:     my %columns = ();
1.44      ng       4176:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4177: 
1.582     raeburn  4178:     my $partserror;
                   4179:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4180:     if ($partserror) {
                   4181:         return &navmap_errormsg();
                   4182:     }
1.54      albertel 4183:     my $header;
1.257     albertel 4184:     while ($ctr < $env{'form.totalparts'}) {
                   4185: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4186: 	push(@partid,$partid);
1.257     albertel 4187: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4188: 	$ctr++;
1.54      albertel 4189:     }
1.324     albertel 4190:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4191:     my $totcolspan = 0;
1.54      albertel 4192:     foreach my $partid (@partid) {
1.478     albertel 4193: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4194: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4195: 	$columns{$partid}=2;
                   4196: 	foreach my $stores (@parts) {
                   4197: 	    my ($part,$type) = &split_part_type($stores);
                   4198: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4199: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4200: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4201: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4202:             my $narrowtext = &mt('Tries');
                   4203: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4204: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4205: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4206: 	    $columns{$partid}+=2;
                   4207: 	}
1.748     raeburn  4208:         $totcolspan += $columns{$partid};
1.54      albertel 4209:     }
                   4210:     foreach my $partid (@partid) {
1.324     albertel 4211: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4212: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4213: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4214: 	    '</th>';
1.54      albertel 4215: 
1.44      ng       4216:     }
1.477     albertel 4217:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4218: 	&Apache::loncommon::start_data_table_header_row().
                   4219: 	$header.
                   4220: 	&Apache::loncommon::end_data_table_header_row();
                   4221:     my @noupdate;
1.126     ng       4222:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4223:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4224: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4225: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4226: 	my %newrecord;
                   4227: 	my $updateflag = 0;
1.108     albertel 4228: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4229: 	my $canmodify = &canmodify($usec);
                   4230: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4231: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4232: 	if (!$canmodify) {
1.477     albertel 4233: 	    push(@noupdate,
1.748     raeburn  4234: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4235: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4236: 	    next;
                   4237: 	}
1.269     raeburn  4238:         my %aggregate = ();
                   4239:         my $aggregateflag = 0;
1.281     albertel 4240: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4241: 	foreach (@partid) {
1.257     albertel 4242: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4243: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4244: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4245: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4246: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4247: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4248: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4249: 	    my $score;
                   4250: 	    if ($partial eq '') {
1.257     albertel 4251: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4252: 	    } elsif ($partial > 0) {
                   4253: 		$score = 'correct_by_override';
                   4254: 	    } elsif ($partial == 0) {
                   4255: 		$score = 'incorrect_by_override';
                   4256: 	    }
1.257     albertel 4257: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4258: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4259: 
1.292     albertel 4260: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4261: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4262: 	    if ($dropMenu eq 'reset status' &&
                   4263: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4264: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4265: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4266: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4267: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4268: 		$updateflag = 1;
1.269     raeburn  4269:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4270:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4271:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4272:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4273:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4274:                     $aggregateflag = 1;
                   4275:                 }
1.139     albertel 4276: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4277: 		$updateflag = 1;
                   4278: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4279: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4280: 		$rec_update++;
1.125     ng       4281: 	    }
                   4282: 
1.93      albertel 4283: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4284: 		'<td align="center">'.$awarded.
                   4285: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4286: 
1.54      albertel 4287: 
                   4288: 	    my $partid=$_;
                   4289: 	    foreach my $stores (@parts) {
                   4290: 		my ($part,$type) = &split_part_type($stores);
                   4291: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4292: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4293: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4294: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4295: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4296: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4297: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4298: 		    $updateflag=1;
                   4299: 		}
1.93      albertel 4300: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4301: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4302: 	    }
1.44      ng       4303: 	}
1.477     albertel 4304: 	$line.="\n";
1.301     albertel 4305: 
                   4306: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4307: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4308: 
1.44      ng       4309: 	if ($updateflag) {
                   4310: 	    $count++;
1.257     albertel 4311: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4312: 				    $udom,$uname);
1.301     albertel 4313: 
                   4314: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4315: 					      $cnum,$udom,$uname)) {
                   4316: 		# need to figure out if should be in queue.
                   4317: 		my %record =  
                   4318: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4319: 					     $udom,$uname);
                   4320: 		my $all_graded = 1;
                   4321: 		my $none_graded = 1;
                   4322: 		foreach my $part (@parts) {
                   4323: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4324: 			$all_graded = 0;
                   4325: 		    } else {
                   4326: 			$none_graded = 0;
                   4327: 		    }
                   4328: 		}
                   4329: 
                   4330: 		if ($all_graded || $none_graded) {
                   4331: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4332: 							   $symb,$cdom,$cnum,
                   4333: 							   $udom,$uname);
                   4334: 		}
                   4335: 	    }
                   4336: 
1.477     albertel 4337: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4338: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4339: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4340: 	    $updateCtr++;
1.93      albertel 4341: 	} else {
1.477     albertel 4342: 	    push(@noupdate,
                   4343: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4344: 	    $noupdateCtr++;
1.44      ng       4345: 	}
1.269     raeburn  4346:         if ($aggregateflag) {
                   4347:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4348: 				  $cdom,$cnum);
1.269     raeburn  4349:         }
1.93      albertel 4350:     }
1.477     albertel 4351:     if (@noupdate) {
1.748     raeburn  4352:         my $numcols=$totcolspan+2;
1.477     albertel 4353: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4354: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4355: 	    &mt('No Changes Occurred For the Students Below').
                   4356: 	    '</td>'.
1.477     albertel 4357: 	    &Apache::loncommon::end_data_table_row();
                   4358: 	foreach my $line (@noupdate) {
                   4359: 	    $result.=
                   4360: 		&Apache::loncommon::start_data_table_row().
                   4361: 		$line.
                   4362: 		&Apache::loncommon::end_data_table_row();
                   4363: 	}
1.44      ng       4364:     }
1.614     www      4365:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4366:     my $msg = '<p><b>'.
                   4367: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4368: 	    $rec_update,$count).'</b><br />'.
                   4369: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4370: 	'</b></p>';
1.44      ng       4371:     return $title.$msg.$result;
1.5       albertel 4372: }
1.54      albertel 4373: 
                   4374: sub split_part_type {
                   4375:     my ($partstr) = @_;
                   4376:     my ($temp,@allparts)=split(/_/,$partstr);
                   4377:     my $type=pop(@allparts);
1.439     albertel 4378:     my $part=join('_',@allparts);
1.54      albertel 4379:     return ($part,$type);
                   4380: }
                   4381: 
1.44      ng       4382: #------------- end of section for handling grading by section/class ---------
                   4383: #
                   4384: #----------------------------------------------------------------------------
                   4385: 
1.5       albertel 4386: 
1.44      ng       4387: #----------------------------------------------------------------------------
                   4388: #
                   4389: #-------------------------- Next few routines handles grading by csv upload
                   4390: #
                   4391: #--- Javascript to handle csv upload
1.27      albertel 4392: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4393:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4394:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4395:   &js_escape(\$error1);
                   4396:   &js_escape(\$error2);
1.27      albertel 4397:   return(<<ENDPICK);
                   4398:   function verify(vf) {
                   4399:     var foundsomething=0;
                   4400:     var founduname=0;
1.243     albertel 4401:     var foundID=0;
1.743     raeburn  4402:     var foundclicker=0;
1.27      albertel 4403:     for (i=0;i<=vf.nfields.value;i++) {
                   4404:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4405:       if (i==0 && tw!=0) { foundID=1; }
                   4406:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4407:       if (i==2 && tw!=0) { foundclicker=1; }
                   4408:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4409:     }
1.743     raeburn  4410:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4411: 	alert('$error1');
                   4412: 	return;
1.27      albertel 4413:     }
                   4414:     if (foundsomething==0) {
1.246     albertel 4415: 	alert('$error2');
                   4416: 	return;
1.27      albertel 4417:     }
                   4418:     vf.submit();
                   4419:   }
                   4420:   function flip(vf,tf) {
                   4421:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4422:     var i;
                   4423:     for (i=0;i<=vf.nfields.value;i++) {
                   4424:       //can not pick the same destination field for both name and domain
                   4425:       if (((i ==0)||(i ==1)) && 
                   4426:           ((tf==0)||(tf==1)) && 
                   4427:           (i!=tf) &&
                   4428:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4429:         eval('vf.f'+i+'.selectedIndex=0;')
                   4430:       }
                   4431:     }
                   4432:   }
                   4433: ENDPICK
                   4434: }
                   4435: 
                   4436: sub csvupload_javascript_forward_associate {
1.743     raeburn  4437:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4438:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4439:   &js_escape(\$error1);
                   4440:   &js_escape(\$error2);
1.27      albertel 4441:   return(<<ENDPICK);
                   4442:   function verify(vf) {
                   4443:     var foundsomething=0;
                   4444:     var founduname=0;
1.243     albertel 4445:     var foundID=0;
1.743     raeburn  4446:     var foundclicker=0;
1.27      albertel 4447:     for (i=0;i<=vf.nfields.value;i++) {
                   4448:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4449:       if (tw==1) { foundID=1; }
                   4450:       if (tw==2) { founduname=1; }
1.745     raeburn  4451:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4452:       if (tw>4) { foundsomething=1; }
1.27      albertel 4453:     }
1.743     raeburn  4454:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4455: 	alert('$error1');
                   4456: 	return;
1.27      albertel 4457:     }
                   4458:     if (foundsomething==0) {
1.246     albertel 4459: 	alert('$error2');
                   4460: 	return;
1.27      albertel 4461:     }
                   4462:     vf.submit();
                   4463:   }
                   4464:   function flip(vf,tf) {
                   4465:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4466:     var i;
                   4467:     //can not pick the same destination field twice
                   4468:     for (i=0;i<=vf.nfields.value;i++) {
                   4469:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4470:         eval('vf.f'+i+'.selectedIndex=0;')
                   4471:       }
                   4472:     }
                   4473:   }
                   4474: ENDPICK
                   4475: }
                   4476: 
1.26      albertel 4477: sub csvuploadmap_header {
1.324     albertel 4478:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4479:     my $javascript;
1.257     albertel 4480:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4481: 	$javascript=&csvupload_javascript_reverse_associate();
                   4482:     } else {
                   4483: 	$javascript=&csvupload_javascript_forward_associate();
                   4484:     }
1.45      ng       4485: 
1.418     albertel 4486:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4487:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4488:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4489:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4490:     my $reverse=&mt("Reverse Association");
1.41      ng       4491:     $request->print(<<ENDPICK);
1.632     www      4492: <br />
                   4493: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4494: <input type="hidden" name="associate"  value="" />
                   4495: <input type="hidden" name="phase"      value="three" />
                   4496: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4497: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4498: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4499: <input type="hidden" name="upfile_associate" 
1.257     albertel 4500:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4501: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4502: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4503: <hr />
                   4504: ENDPICK
1.597     wenzelju 4505:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4506:     return '';
1.26      albertel 4507: 
                   4508: }
                   4509: 
                   4510: sub csvupload_fields {
1.582     raeburn  4511:     my ($symb,$errorref) = @_;
1.745     raeburn  4512:     my $toolsymb;
                   4513:     if ($symb =~ /ext\.tool$/) {
                   4514:         $toolsymb = $symb;
                   4515:     }
1.582     raeburn  4516:     my (@parts) = &getpartlist($symb,$errorref);
                   4517:     if (ref($errorref)) {
                   4518:         if ($$errorref) {
                   4519:             return;
                   4520:         }
                   4521:     }
                   4522: 
1.556     weissno  4523:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4524: 		['username','Student Username'],
1.743     raeburn  4525: 		['clicker','Clicker ID'],
1.243     albertel 4526: 		['domain','Student Domain']);
1.324     albertel 4527:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4528:     foreach my $part (sort(@parts)) {
                   4529: 	my @datum;
1.745     raeburn  4530: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4531: 	my $name=$part;
1.745     raeburn  4532: 	if (!$display) { $display = $name; }
1.41      ng       4533: 	@datum=($name,$display);
1.244     albertel 4534: 	if ($name=~/^stores_(.*)_awarded/) {
                   4535: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4536: 	}
1.41      ng       4537: 	push(@fields,\@datum);
                   4538:     }
                   4539:     return (@fields);
1.26      albertel 4540: }
                   4541: 
                   4542: sub csvuploadmap_footer {
1.41      ng       4543:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4544:     my $buttontext = &mt('Assign Grades');
1.41      ng       4545:     $request->print(<<ENDPICK);
1.26      albertel 4546: </table>
                   4547: <input type="hidden" name="nfields" value="$i" />
                   4548: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4549: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4550: </form>
                   4551: ENDPICK
                   4552: }
                   4553: 
1.283     albertel 4554: sub checkforfile_js {
1.638     www      4555:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4556:     &js_escape(\$alertmsg);
1.597     wenzelju 4557:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4558:     function checkUpload(formname) {
                   4559: 	if (formname.upfile.value == "") {
1.539     riegler  4560: 	    alert("$alertmsg");
1.86      ng       4561: 	    return false;
                   4562: 	}
                   4563: 	formname.submit();
                   4564:     }
                   4565: CSVFORMJS
1.283     albertel 4566:     return $result;
                   4567: }
                   4568: 
                   4569: sub upcsvScores_form {
1.608     www      4570:     my ($request,$symb) = @_;
1.283     albertel 4571:     if (!$symb) {return '';}
                   4572:     my $result=&checkforfile_js();
1.632     www      4573:     $result.=&Apache::loncommon::start_data_table().
                   4574:              &Apache::loncommon::start_data_table_header_row().
                   4575:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4576:              &Apache::loncommon::end_data_table_header_row().
                   4577:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4578:     my $upload=&mt("Upload Scores");
1.86      ng       4579:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4580:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4581:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4582:     $result.=<<ENDUPFORM;
1.106     albertel 4583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4584: <input type="hidden" name="symb" value="$symb" />
                   4585: <input type="hidden" name="command" value="csvuploadmap" />
                   4586: $upfile_select
1.589     bisitz   4587: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4588: </form>
                   4589: ENDUPFORM
1.370     www      4590:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4591:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4592:              '</td>'.
                   4593:             &Apache::loncommon::end_data_table_row().
                   4594:             &Apache::loncommon::end_data_table();
1.86      ng       4595:     return $result;
                   4596: }
                   4597: 
                   4598: 
1.26      albertel 4599: sub csvuploadmap {
1.608     www      4600:     my ($request,$symb)= @_;
1.41      ng       4601:     if (!$symb) {return '';}
1.72      ng       4602: 
1.41      ng       4603:     my $datatoken;
1.257     albertel 4604:     if (!$env{'form.datatoken'}) {
1.41      ng       4605: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4606:     } else {
1.742     raeburn  4607: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4608:         if ($datatoken ne '') {
                   4609: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4610:         }
1.26      albertel 4611:     }
1.41      ng       4612:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4613:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4614:     my ($i,$keyfields);
                   4615:     if (@records) {
1.582     raeburn  4616:         my $fieldserror;
                   4617: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4618:         if ($fieldserror) {
                   4619:             $request->print(&navmap_errormsg());
                   4620:             return;
                   4621:         }
1.257     albertel 4622: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4623: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4624: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4625: 							  \@fields);
                   4626: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4627: 	    chop($keyfields);
                   4628: 	} else {
                   4629: 	    unshift(@fields,['none','']);
                   4630: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4631: 							    \@fields);
1.311     banghart 4632:             foreach my $rec (@records) {
                   4633:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4634:                 if (%temp) {
                   4635:                     $keyfields=join(',',sort(keys(%temp)));
                   4636:                     last;
                   4637:                 }
                   4638:             }
1.41      ng       4639: 	}
                   4640:     }
                   4641:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4642: 
1.41      ng       4643:     return '';
1.27      albertel 4644: }
                   4645: 
1.246     albertel 4646: sub csvuploadoptions {
1.608     www      4647:     my ($request,$symb)= @_;
1.632     www      4648:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4649:     $request->print(<<ENDPICK);
                   4650: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4651: <input type="hidden" name="command"    value="csvuploadassign" />
                   4652: <p>
                   4653: <label>
                   4654:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4655:    $overwrite
1.246     albertel 4656: </label>
                   4657: </p>
                   4658: ENDPICK
                   4659:     my %fields=&get_fields();
                   4660:     if (!defined($fields{'domain'})) {
1.257     albertel 4661: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4662: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4663:     }
1.257     albertel 4664:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4665: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4666: 	my $cleankey=$1;
                   4667: 	if ($cleankey eq 'command') { next; }
                   4668: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4669: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4670:     }
                   4671:     # FIXME do a check for any duplicated user ids...
                   4672:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4673:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4674: <hr /></form>'."\n");
1.246     albertel 4675:     return '';
                   4676: }
                   4677: 
                   4678: sub get_fields {
                   4679:     my %fields;
1.257     albertel 4680:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4681:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4682: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4683: 	    if ($env{'form.f'.$i} ne 'none') {
                   4684: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4685: 	    }
                   4686: 	} else {
1.257     albertel 4687: 	    if ($env{'form.f'.$i} ne 'none') {
                   4688: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4689: 	    }
                   4690: 	}
1.27      albertel 4691:     }
1.246     albertel 4692:     return %fields;
                   4693: }
                   4694: 
                   4695: sub csvuploadassign {
1.608     www      4696:     my ($request,$symb)= @_;
1.246     albertel 4697:     if (!$symb) {return '';}
1.345     bowersj2 4698:     my $error_msg = '';
1.742     raeburn  4699:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4700:     if ($datatoken ne '') { 
                   4701:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4702:     }
1.246     albertel 4703:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4704:     my %fields=&get_fields();
1.257     albertel 4705:     my $courseid=$env{'request.course.id'};
1.97      albertel 4706:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4707:     my @notallowed;
1.41      ng       4708:     my @skipped;
1.657     raeburn  4709:     my @warnings;
1.41      ng       4710:     my $countdone=0;
                   4711:     foreach my $grade (@gradedata) {
                   4712: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4713: 	my $domain;
                   4714: 	if ($entries{$fields{'domain'}}) {
                   4715: 	    $domain=$entries{$fields{'domain'}};
                   4716: 	} else {
1.257     albertel 4717: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4718: 	}
1.243     albertel 4719: 	$domain=~s/\s//g;
1.41      ng       4720: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4721: 	$username=~s/\s//g;
1.243     albertel 4722: 	if (!$username) {
                   4723: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4724: 	    $id=~s/\s//g;
1.737     raeburn  4725:             if ($id ne '') {
                   4726: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4727: 	        $username=$ids{$id};
                   4728:             } else {
                   4729:                 if ($entries{$fields{'clicker'}}) {
                   4730:                     my $clicker = $entries{$fields{'clicker'}};
                   4731:                     $clicker=~s/\s//g;
                   4732:                     if ($clicker ne '') {
                   4733:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4734:                         if ($clickers{$clicker} ne '') {  
                   4735:                             my $match = 0;
                   4736:                             my @inclass;
                   4737:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4738:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4739:                                     $username = $poss;
                   4740:                                     push(@inclass,$poss);
                   4741:                                     $match ++;
                   4742:                                     
                   4743:                                 }
                   4744:                             }
                   4745:                             if ($match > 1) {
                   4746:                                 undef($username); 
                   4747:                                 $request->print('<p class="LC_warning">'.
                   4748:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4749:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4750:                             }
                   4751:                         }
                   4752:                     }
                   4753:                 }
                   4754:             }
1.243     albertel 4755: 	}
1.41      ng       4756: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4757: 	    my $id=$entries{$fields{'ID'}};
                   4758: 	    $id=~s/\s//g;
1.737     raeburn  4759:             my $clicker = $entries{$fields{'clicker'}};
                   4760:             $clicker=~s/\s//g;
                   4761:             if ($clicker) {
                   4762:                 push(@skipped,"$clicker:$domain");
                   4763: 	    } elsif ($id) {
1.247     albertel 4764: 		push(@skipped,"$id:$domain");
                   4765: 	    } else {
                   4766: 		push(@skipped,"$username:$domain");
                   4767: 	    }
1.41      ng       4768: 	    next;
                   4769: 	}
1.108     albertel 4770: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4771: 	if (!&canmodify($usec)) {
                   4772: 	    push(@notallowed,"$username:$domain");
                   4773: 	    next;
                   4774: 	}
1.244     albertel 4775: 	my %points;
1.41      ng       4776: 	my %grades;
                   4777: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4778: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4779: 		$dest eq 'domain') { next; }
                   4780: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4781: 	    if ($dest=~/stores_(.*)_points/) {
                   4782: 		my $part=$1;
                   4783: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4784: 					      $symb,$domain,$username);
1.345     bowersj2 4785:                 if ($wgt) {
                   4786:                     $entries{$fields{$dest}}=~s/\s//g;
                   4787:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4788:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4789:                                           : 'correct_by_override';
1.638     www      4790:                     if ($pcr>1) {
1.657     raeburn  4791:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4792:                     }
1.345     bowersj2 4793:                     $grades{"resource.$part.awarded"}=$pcr;
                   4794:                     $grades{"resource.$part.solved"}=$award;
                   4795:                     $points{$part}=1;
                   4796:                 } else {
                   4797:                     $error_msg = "<br />" .
                   4798:                         &mt("Some point values were assigned"
                   4799:                             ." for problems with a weight "
                   4800:                             ."of zero. These values were "
                   4801:                             ."ignored.");
                   4802:                 }
1.244     albertel 4803: 	    } else {
                   4804: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4805: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4806: 		my $store_key=$dest;
                   4807: 		$store_key=~s/^stores/resource/;
                   4808: 		$store_key=~s/_/\./g;
                   4809: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4810: 	    }
1.41      ng       4811: 	}
1.508     www      4812: 	if (! %grades) { 
                   4813:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4814:         } else {
                   4815: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4816: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4817: 					   $env{'request.course.id'},
                   4818: 					   $domain,$username);
1.508     www      4819: 	   if ($result eq 'ok') {
1.627     www      4820: # Successfully stored
1.508     www      4821: 	      $request->print('.');
1.627     www      4822: # Remove from grading queue
                   4823:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4824:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4825:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4826:                                              $domain,$username);
                   4827:               $countdone++;
                   4828:            } else {
1.508     www      4829: 	      $request->print("<p><span class=\"LC_error\">".
                   4830:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4831:                                   "$username:$domain",$result)."</span></p>");
                   4832: 	   }
                   4833: 	   $request->rflush();
                   4834:         }
1.41      ng       4835:     }
1.570     www      4836:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4837:     if (@warnings) {
                   4838:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4839:         $request->print(join(', ',@warnings));
                   4840:     }
1.41      ng       4841:     if (@skipped) {
1.571     www      4842: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4843:         $request->print(join(', ',@skipped));
1.106     albertel 4844:     }
                   4845:     if (@notallowed) {
1.571     www      4846: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4847: 	$request->print(join(', ',@notallowed));
1.41      ng       4848:     }
1.106     albertel 4849:     $request->print("<br />\n");
1.345     bowersj2 4850:     return $error_msg;
1.26      albertel 4851: }
1.44      ng       4852: #------------- end of section for handling csv file upload ---------
                   4853: #
                   4854: #-------------------------------------------------------------------
                   4855: #
1.122     ng       4856: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4857: #
                   4858: #--- Select a page/sequence and a student to grade
1.68      ng       4859: sub pickStudentPage {
1.608     www      4860:     my ($request,$symb) = @_;
1.68      ng       4861: 
1.539     riegler  4862:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4863:     &js_escape(\$alertmsg);
1.597     wenzelju 4864:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4865: 
                   4866: function checkPickOne(formname) {
1.76      ng       4867:     if (radioSelection(formname.student) == null) {
1.539     riegler  4868: 	alert("$alertmsg");
1.68      ng       4869: 	return;
                   4870:     }
1.125     ng       4871:     ptr = pullDownSelection(formname.selectpage);
                   4872:     formname.page.value = formname["page"+ptr].value;
                   4873:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4874:     formname.submit();
                   4875: }
                   4876: 
                   4877: LISTJAVASCRIPT
1.118     ng       4878:     &commonJSfunctions($request);
1.608     www      4879: 
1.257     albertel 4880:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4881:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4882:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4883: 
1.398     albertel 4884:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4885: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4886: 
1.80      ng       4887:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4888:     my $map_error;
                   4889:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4890:     if ($map_error) {
                   4891:         $request->print(&navmap_errormsg());
                   4892:         return; 
                   4893:     }
1.137     albertel 4894:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4895: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4896: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4897: 
                   4898:     # Collection of hidden fields
1.70      ng       4899:     my $ctr=0;
1.68      ng       4900:     foreach (@$titles) {
1.700     bisitz   4901:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4902:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4903:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4904:         $ctr++;
1.68      ng       4905:     }
1.700     bisitz   4906:     $result.='<input type="hidden" name="page" />'."\n".
                   4907:         '<input type="hidden" name="title" />'."\n";
                   4908: 
                   4909:     $result.=&build_section_inputs();
                   4910:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4911:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4912: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4913: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4914: 
1.700     bisitz   4915:     # Show grading options
                   4916:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4917:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4918:     $ctr=0;
                   4919:     foreach (@$titles) {
                   4920: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4921: 	$select.='<option value="'.$ctr.'"'.
                   4922: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4923: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4924: 	$ctr++;
                   4925:     }
1.700     bisitz   4926:     $select.= '</select>';
1.68      ng       4927: 
1.700     bisitz   4928:     $result.=
                   4929:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4930:        .$select
                   4931:        .&Apache::lonhtmlcommon::row_closure();
                   4932: 
                   4933:     $result.=
                   4934:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4935:        .'<label><input type="radio" name="vProb" value="no"'
                   4936:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4937:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4938:            .&mt('yes').'</label>'."\n"
                   4939:        .&Apache::lonhtmlcommon::row_closure();
                   4940: 
                   4941:     $result.=
                   4942:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4943:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4944:            .&mt('none').' </label>'."\n"
                   4945:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4946:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4947:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4948:            .&mt('all submissions with details').' </label>'
                   4949:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4950:     
1.700     bisitz   4951:     $result.=
                   4952:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4953:        .'<input type="text" name="CODE" value="" />'
                   4954:        .&Apache::lonhtmlcommon::row_closure(1)
                   4955:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4956: 
1.700     bisitz   4957:     # Show list of students to select for grading
                   4958:     $result.='<br /><input type="button" '.
1.589     bisitz   4959:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4960: 
1.68      ng       4961:     $request->print($result);
                   4962: 
1.485     albertel 4963:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4964: 	&Apache::loncommon::start_data_table().
                   4965: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4966: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4967: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4968: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4969: 	'<th>'.&nameUserString('header').'</th>'.
                   4970: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4971:  
1.76      ng       4972:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4973:     my $ptr = 1;
1.294     albertel 4974:     foreach my $student (sort 
                   4975: 			 {
                   4976: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4977: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4978: 			     }
                   4979: 			     return $a cmp $b;
                   4980: 			 } (keys(%$fullname))) {
1.68      ng       4981: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4982: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4983:                                   : '</td>');
1.126     ng       4984: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4985: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4986: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4987: 	$studentTable.=
                   4988: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4989:                          : '');
1.68      ng       4990: 	$ptr++;
                   4991:     }
1.484     albertel 4992:     if ($ptr%2 == 0) {
                   4993: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4994: 	    &Apache::loncommon::end_data_table_row();
                   4995:     }
                   4996:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4997:     $studentTable.='<input type="button" '.
1.589     bisitz   4998:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4999: 
                   5000:     $request->print($studentTable);
                   5001: 
                   5002:     return '';
                   5003: }
                   5004: 
                   5005: sub getSymbMap {
1.582     raeburn  5006:     my ($map_error) = @_;
1.132     bowersj2 5007:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5008:     unless (ref($navmap)) {
                   5009:         if (ref($map_error)) {
                   5010:             $$map_error = 'navmap';
                   5011:         }
                   5012:         return;
                   5013:     }
1.68      ng       5014:     my %symbx = ();
                   5015:     my @titles = ();
1.117     bowersj2 5016:     my $minder = 0;
                   5017: 
                   5018:     # Gather every sequence that has problems.
1.240     albertel 5019:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5020: 					       1,0,1);
1.117     bowersj2 5021:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5022: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5023: 	    my $title = $minder.'.'.
                   5024: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5025: 	    push(@titles, $title); # minder in case two titles are identical
                   5026: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5027: 	    $minder++;
1.241     albertel 5028: 	}
1.68      ng       5029:     }
                   5030:     return \@titles,\%symbx;
                   5031: }
                   5032: 
1.72      ng       5033: #
                   5034: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5035: sub displayPage {
1.608     www      5036:     my ($request,$symb) = @_;
1.257     albertel 5037:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5038:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5039:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5040:     my $pageTitle = $env{'form.page'};
1.103     albertel 5041:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5042:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5043:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5044: 
                   5045:     #need to make sure we have the correct data for later EXT calls, 
                   5046:     #thus invalidate the cache
                   5047:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5048:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5049:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5050:     &Apache::lonnet::clear_EXT_cache_status();
                   5051: 
1.103     albertel 5052:     if (!&canview($usec)) {
1.712     bisitz   5053:         $request->print(
                   5054:             '<span class="LC_warning">'.
                   5055:             &mt('Unable to view requested student. ([_1])',
                   5056:                     $env{'form.student'}).
                   5057:             '</span>');
                   5058:         return;
1.103     albertel 5059:     }
1.398     albertel 5060:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5061:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5062: 	'</h3>'."\n";
1.500     albertel 5063:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5064:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5065: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5066:     } else {
                   5067: 	delete($env{'form.CODE'});
                   5068:     }
1.71      ng       5069:     &sub_page_js($request);
                   5070:     $request->print($result);
                   5071: 
1.132     bowersj2 5072:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5073:     unless (ref($navmap)) {
                   5074:         $request->print(&navmap_errormsg());
                   5075:         return;
                   5076:     }
1.257     albertel 5077:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5078:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5079:     if (!$map) {
1.485     albertel 5080: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5081: 	return; 
                   5082:     }
1.68      ng       5083:     my $iterator = $navmap->getIterator($map->map_start(),
                   5084: 					$map->map_finish());
                   5085: 
1.71      ng       5086:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5087: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5088: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5089: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5090: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5091: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5092: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5093: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5094: 
1.382     albertel 5095:     if (defined($env{'form.CODE'})) {
                   5096: 	$studentTable.=
                   5097: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5098:     }
1.381     albertel 5099:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5100: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5101: 
1.594     bisitz   5102:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5103:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5104:         '</span>'."\n".
1.484     albertel 5105: 	&Apache::loncommon::start_data_table().
                   5106: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5107: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5108: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5109: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5110: 
1.329     albertel 5111:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5112:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5113:     $iterator->next(); # skip the first BEGIN_MAP
                   5114:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5115:     while ($depth > 0) {
1.68      ng       5116:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5117:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5118: 
1.745     raeburn  5119:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5120: 	    my $parts = $curRes->parts();
1.68      ng       5121:             my $title = $curRes->compTitle();
1.71      ng       5122: 	    my $symbx = $curRes->symb();
1.746     raeburn  5123:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5124: 	    $studentTable.=
                   5125: 		&Apache::loncommon::start_data_table_row().
                   5126: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5127: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5128: 		                        : '<br />('.&mt('[_1]parts',
                   5129: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5130: 		 ).
                   5131: 		 '</td>';
1.71      ng       5132: 	    $studentTable.='<td valign="top">';
1.382     albertel 5133: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5134:             if ($is_tool) {
                   5135:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5136:             } else {
1.745     raeburn  5137: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5138: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5139: 					         undef,'both',\%form);
                   5140: 	        } else {
                   5141: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5142: 		    $companswer =~ s|<form(.*?)>||g;
                   5143: 		    $companswer =~ s|</form>||g;
                   5144: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5145: #		        $companswer =~ s/$1/ /ms;
                   5146: #		        $request->print('match='.$1."<br />\n");
                   5147: #		    }
                   5148: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5149: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5150: 		}
1.71      ng       5151: 	    }
                   5152: 
1.257     albertel 5153: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5154: 
1.257     albertel 5155: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5156: 		if ($record{'version'} eq '') {
1.745     raeburn  5157:                     my $msg = &mt('No recorded submission for this problem.');
                   5158:                     if ($is_tool) {
                   5159:                         $msg = &mt('No recorded transactions for this external tool');
                   5160:                     }
                   5161: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5162: 		} else {
1.116     ng       5163: 		    my %responseType = ();
                   5164: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5165: 			my @responseIds =$curRes->responseIds($partid);
                   5166: 			my @responseType =$curRes->responseType($partid);
                   5167: 			my %responseIds;
                   5168: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5169: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5170: 			}
                   5171: 			$responseType{$partid} = \%responseIds;
1.116     ng       5172: 		    }
1.148     albertel 5173: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5174: 		}
1.257     albertel 5175: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5176: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5177:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5178: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5179: 									$env{'request.course.id'},
1.726     raeburn  5180: 									'','.submission',undef,
                   5181:                                                                         $usec,$identifier);
1.71      ng       5182:  
                   5183: 	    }
1.103     albertel 5184: 	    if (&canmodify($usec)) {
1.585     bisitz   5185:             $studentTable.=&gradeBox_start();
1.103     albertel 5186: 		foreach my $partid (@{$parts}) {
                   5187: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5188: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5189: 		    $question++;
                   5190: 		}
1.585     bisitz   5191:             $studentTable.=&gradeBox_end();
1.196     albertel 5192: 		$prob++;
1.71      ng       5193: 	    }
                   5194: 	    $studentTable.='</td></tr>';
1.68      ng       5195: 
1.103     albertel 5196: 	}
1.68      ng       5197:         $curRes = $iterator->next();
                   5198:     }
                   5199: 
1.589     bisitz   5200:     $studentTable.=
                   5201:         '</table>'."\n".
                   5202:         '<input type="button" value="'.&mt('Save').'" '.
                   5203:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5204:         '</form>'."\n";
1.71      ng       5205:     $request->print($studentTable);
                   5206: 
                   5207:     return '';
1.119     ng       5208: }
                   5209: 
                   5210: sub displaySubByDates {
1.148     albertel 5211:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5212:     my $isCODE=0;
1.335     albertel 5213:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5214:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5215:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5216:     my $studentTable=&Apache::loncommon::start_data_table().
                   5217: 	&Apache::loncommon::start_data_table_header_row().
                   5218: 	'<th>'.&mt('Date/Time').'</th>'.
                   5219: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5220:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5221: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5222: 	'<th>'.&mt('Status').'</th>'.
                   5223: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5224:     my ($version);
                   5225:     my %mark;
1.148     albertel 5226:     my %orders;
1.119     ng       5227:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5228:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5229:         if ($is_tool) {
                   5230:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5231:         } else {
                   5232:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5233:         }
1.147     albertel 5234:     }
1.335     albertel 5235: 
                   5236:     my $interaction;
1.525     raeburn  5237:     my $no_increment = 1;
1.735     raeburn  5238:     my (%lastrndseed,%lasttype);
1.119     ng       5239:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5240: 	my $timestamp = 
                   5241: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5242: 	if (exists($$record{$version.':resource.0.version'})) {
                   5243: 	    $interaction = $$record{$version.':resource.0.version'};
                   5244: 	}
1.671     raeburn  5245:         if ($isTask && $env{'form.previousversion'}) {
                   5246:             next unless ($interaction == $env{'form.previousversion'});
                   5247:         }
1.335     albertel 5248: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5249: 		             : "$version:resource");
1.467     albertel 5250: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5251: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5252: 	if ($isCODE) {
                   5253: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5254: 	}
1.671     raeburn  5255:         if ($isTask) {
                   5256:             $studentTable.='<td>'.$interaction.'</td>';
                   5257:         }
1.119     ng       5258: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5259: 	my @displaySub = ();
                   5260: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5261:             my ($hidden,$type);
                   5262:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5263:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5264:                 $hidden = 1;
                   5265:             }
1.749     raeburn  5266:             my @matchKey;
                   5267:             if ($isTask) {
                   5268:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
                   5269:             } elsif ($is_tool) {
                   5270:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
                   5271:             } else {
                   5272:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
                   5273:             }
1.122     ng       5274: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5275: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5276: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5277: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5278: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5279:                     if ($is_tool) {
                   5280:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5281:                     } else {
1.749     raeburn  5282: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5283: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5284:                         $displaySub[0].='<span class="LC_nobreak">';
                   5285:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5286:                                        .' <span class="LC_internal_info">'
                   5287:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5288:                                        .'</span>'
                   5289:                                        .' <b>';
                   5290:                         if ($hidden) {
                   5291:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5292:                         } else {
                   5293:                             my ($trial,$rndseed,$newvariation);
                   5294:                             if ($type eq 'randomizetry') {
                   5295:                                 $trial = $$record{"$where.$partid.tries"};
                   5296:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5297:                             }
                   5298: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5299: 			        $displaySub[0].=&mt('Trial not counted');
                   5300: 		            } else {
                   5301: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5302: 					        $$record{"$where.$partid.tries"});
                   5303:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5304:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5305:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5306:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5307:                                     }
1.640     raeburn  5308:                                 }
1.749     raeburn  5309:                                 $lastrndseed{$partid} = $rndseed;
                   5310:                                 $lasttype{$partid} = $type;
                   5311: 		            }
                   5312: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5313:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5314: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5315: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5316: 			        $orders{$partid}->{$responseId}=
                   5317: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5318:                                                $no_increment,$type,$trial,$rndseed);
                   5319: 		            }
                   5320: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5321: 		            $displaySub[0].='&nbsp; '.
                   5322: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5323:                         }
1.596     raeburn  5324:                     }
1.147     albertel 5325: 		}
                   5326: 	    }
1.335     albertel 5327: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5328: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5329: 				    $$record{"$where.$partid.checkedin"},
                   5330: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5331: 					'<br />';
1.335     albertel 5332: 	    }
                   5333: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5334: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5335: 		    lc($$record{"$where.$partid.award"}).' '.
                   5336: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5337: 		    '<br />';
1.749     raeburn  5338: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5339: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5340: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5341: 		}
1.147     albertel 5342: 	    }
1.335     albertel 5343: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5344: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5345: 		unless ($is_tool) {
                   5346: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5347: 		}
1.335     albertel 5348: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5349: 		$displaySub[2].=
1.749     raeburn  5350: 		    $$record{"$version:resource.$partid.regrader"};
                   5351:                 unless ($is_tool) {
                   5352: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5353:                 }
1.147     albertel 5354: 	    }
                   5355: 	}
                   5356: 	# needed because old essay regrader has not parts info
                   5357: 	if (exists $$record{"$version:resource.regrader"}) {
                   5358: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5359: 	}
                   5360: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5361: 	if ($displaySub[2]) {
1.467     albertel 5362: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5363: 	}
1.467     albertel 5364: 	$studentTable.='&nbsp;</td>'.
                   5365: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5366:     }
1.467     albertel 5367:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5368:     return $studentTable;
1.71      ng       5369: }
                   5370: 
                   5371: sub updateGradeByPage {
1.608     www      5372:     my ($request,$symb) = @_;
1.71      ng       5373: 
1.257     albertel 5374:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5375:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5376:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5377:     my $pageTitle = $env{'form.page'};
1.103     albertel 5378:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5379:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5380:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5381:     if (!&canmodify($usec)) {
1.526     raeburn  5382: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5383: 	return;
                   5384:     }
1.398     albertel 5385:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5386:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5387: 	'</h3>'."\n";
1.70      ng       5388: 
1.68      ng       5389:     $request->print($result);
                   5390: 
1.582     raeburn  5391: 
1.132     bowersj2 5392:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5393:     unless (ref($navmap)) {
                   5394:         $request->print(&navmap_errormsg());
                   5395:         return;
                   5396:     }
1.257     albertel 5397:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5398:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5399:     if (!$map) {
1.527     raeburn  5400: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5401: 	return; 
                   5402:     }
1.71      ng       5403:     my $iterator = $navmap->getIterator($map->map_start(),
                   5404: 					$map->map_finish());
1.70      ng       5405: 
1.484     albertel 5406:     my $studentTable=
                   5407: 	&Apache::loncommon::start_data_table().
                   5408: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5409: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5410: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5411: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5412: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5413: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5414: 
                   5415:     $iterator->next(); # skip the first BEGIN_MAP
                   5416:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5417:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5418:     while ($depth > 0) {
1.71      ng       5419:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5420:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5421: 
1.385     albertel 5422:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5423: 	    my $parts = $curRes->parts();
1.71      ng       5424:             my $title = $curRes->compTitle();
                   5425: 	    my $symbx = $curRes->symb();
1.484     albertel 5426: 	    $studentTable.=
                   5427: 		&Apache::loncommon::start_data_table_row().
                   5428: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5429: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5430:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5431: 		.')').'</td>';
1.71      ng       5432: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5433: 
                   5434: 	    my %newrecord=();
                   5435: 	    my @displayPts=();
1.269     raeburn  5436:             my %aggregate = ();
                   5437:             my $aggregateflag = 0;
1.726     raeburn  5438:             if ($env{'form.HIDE'.$prob}) {
                   5439:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5440:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5441:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5442:                 $hideflag += $numchgs;
                   5443:             }
1.71      ng       5444: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5445: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5446: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5447: 
1.257     albertel 5448: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5449: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5450: 		my $partial = $newpts/$wgt;
                   5451: 		my $score;
                   5452: 		if ($partial > 0) {
                   5453: 		    $score = 'correct_by_override';
1.125     ng       5454: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5455: 		    $score = 'incorrect_by_override';
                   5456: 		}
1.257     albertel 5457: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5458: 		if ($dropMenu eq 'excused') {
1.71      ng       5459: 		    $partial = '';
                   5460: 		    $score = 'excused';
1.125     ng       5461: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5462: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5463: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5464: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5465: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5466: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5467: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5468: 		    $changeflag++;
                   5469: 		    $newpts = '';
1.269     raeburn  5470:                     
                   5471:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5472:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5473:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5474:                     if ($aggtries > 0) {
                   5475:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5476:                         $aggregateflag = 1;
                   5477:                     }
1.71      ng       5478: 		}
1.324     albertel 5479: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5480: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5481: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5482: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5483: 		    '&nbsp;<br />';
1.526     raeburn  5484: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5485: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5486: 		    '&nbsp;<br />';
1.71      ng       5487: 		$question++;
1.380     albertel 5488: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5489: 
1.71      ng       5490: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5491: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5492: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5493: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5494: 
                   5495: 		$changeflag++;
                   5496: 	    }
                   5497: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5498: 		my %record = 
                   5499: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5500: 					     $udom,$uname);
                   5501: 
                   5502: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5503: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5504: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5505: 		    $newrecord{'resource.CODE'} = '';
                   5506: 		}
1.257     albertel 5507: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5508: 					$udom,$uname);
1.382     albertel 5509: 		%record = &Apache::lonnet::restore($symbx,
                   5510: 						   $env{'request.course.id'},
                   5511: 						   $udom,$uname);
1.380     albertel 5512: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5513: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5514: 	    }
1.380     albertel 5515: 	    
1.269     raeburn  5516:             if ($aggregateflag) {
                   5517:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5518:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5519:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5520:             }
1.125     ng       5521: 
1.71      ng       5522: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5523: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5524: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5525: 
1.196     albertel 5526: 	    $prob++;
1.68      ng       5527: 	}
1.71      ng       5528:         $curRes = $iterator->next();
1.68      ng       5529:     }
1.98      albertel 5530: 
1.484     albertel 5531:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5532:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5533: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5534: 		  $changeflag).'<br />');
                   5535:     my $hidemsg=($hideflag == 0 ? '' :
                   5536:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5537:                      $hideflag).'<br />');
                   5538:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5539: 
1.70      ng       5540:     return '';
                   5541: }
                   5542: 
1.72      ng       5543: #-------- end of section for handling grading by page/sequence ---------
                   5544: #
                   5545: #-------------------------------------------------------------------
                   5546: 
1.581     www      5547: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5548: #
                   5549: #------ start of section for handling grading by page/sequence ---------
                   5550: 
1.423     albertel 5551: =pod
                   5552: 
                   5553: =head1 Bubble sheet grading routines
                   5554: 
1.424     albertel 5555:   For this documentation:
                   5556: 
                   5557:    'scanline' refers to the full line of characters
                   5558:    from the file that we are parsing that represents one entire sheet
                   5559: 
                   5560:    'bubble line' refers to the data
1.659     raeburn  5561:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5562: 
                   5563: 
1.659     raeburn  5564: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5565: into a course. When a user wants to grade, they select a
1.659     raeburn  5566: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5567: one of the predefined configurations for what each scanline looks
                   5568: like.
                   5569: 
                   5570: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5571: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5572: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5573: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5574: invalid student/employee ID
1.424     albertel 5575: 
                   5576: If the CODE option is used that determines the randomization of the
1.556     weissno  5577: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5578: username:domain.
                   5579: 
                   5580: During the validation phase the instructor can choose to skip scanlines. 
                   5581: 
1.659     raeburn  5582: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5583: 
                   5584:   scantron_original_filename (unmodified original file)
                   5585:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5586:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5587: 
                   5588: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5589: correction information that isn't representable in the bubblesheet
1.424     albertel 5590: file (see &scantron_getfile() for more information)
                   5591: 
                   5592: After all scanlines are either valid, marked as valid or skipped, then
                   5593: foreach line foreach problem in the picked sequence, an ssi request is
                   5594: made that simulates a user submitting their selected letter(s) against
                   5595: the homework problem.
1.423     albertel 5596: 
                   5597: =over 4
                   5598: 
                   5599: 
                   5600: 
                   5601: =item defaultFormData
                   5602: 
                   5603:   Returns html hidden inputs used to hold context/default values.
                   5604: 
                   5605:  Arguments:
                   5606:   $symb - $symb of the current resource 
                   5607: 
                   5608: =cut
1.422     foxr     5609: 
1.81      albertel 5610: sub defaultFormData {
1.324     albertel 5611:     my ($symb)=@_;
1.613     www      5612:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5613: }
                   5614: 
1.447     foxr     5615: 
1.423     albertel 5616: =pod 
                   5617: 
                   5618: =item getSequenceDropDown
                   5619: 
                   5620:    Return html dropdown of possible sequences to grade
                   5621:  
                   5622:  Arguments:
1.582     raeburn  5623:    $symb - $symb of the current resource
                   5624:    $map_error - ref to scalar which will container error if
                   5625:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5626: 
                   5627: =cut
1.422     foxr     5628: 
1.75      albertel 5629: sub getSequenceDropDown {
1.582     raeburn  5630:     my ($symb,$map_error)=@_;
1.75      albertel 5631:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5632:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5633:     if (ref($map_error)) {
                   5634:         return if ($$map_error);
                   5635:     }
1.137     albertel 5636:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5637:     my $ctr=0;
                   5638:     foreach (@$titles) {
                   5639: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5640: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5641: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5642: 	    '>'.$showtitle.'</option>'."\n";
                   5643: 	$ctr++;
                   5644:     }
                   5645:     $result.= '</select>';
                   5646:     return $result;
                   5647: }
                   5648: 
1.495     albertel 5649: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5650:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5651: 
                   5652: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5653: 
1.509     raeburn  5654: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5655:                                    # matchresponse or rankresponse, where 
                   5656:                                    # an individual response can have multiple 
                   5657:                                    # lines
1.503     raeburn  5658: 
                   5659: my %responsetype_per_response;     # responsetype for each response
                   5660: 
1.691     raeburn  5661: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5662:                                    # numbered response. Needed when randomorder
                   5663:                                    # or randompick are in use. Key is ID, value 
                   5664:                                    # is response number.
                   5665: 
1.495     albertel 5666: # Save and restore the bubble lines array to the form env.
                   5667: 
                   5668: 
                   5669: sub save_bubble_lines {
                   5670:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5671: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5672: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5673: 	    $first_bubble_line{$line};
1.503     raeburn  5674:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5675:             $subdivided_bubble_lines{$line};
                   5676:         $env{"form.scantron.responsetype.$line"} =
                   5677:             $responsetype_per_response{$line};
1.495     albertel 5678:     }
1.691     raeburn  5679:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5680:         my $line = $masterseq_id_responsenum{$resid};
                   5681:         $env{"form.scantron.residpart.$line"} = $resid;
                   5682:     }
1.495     albertel 5683: }
                   5684: 
                   5685: 
                   5686: sub restore_bubble_lines {
                   5687:     my $line = 0;
                   5688:     %bubble_lines_per_response = ();
1.691     raeburn  5689:     %masterseq_id_responsenum = ();
1.495     albertel 5690:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5691: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5692: 	$bubble_lines_per_response{$line} = $value;
                   5693: 	$first_bubble_line{$line}  =
                   5694: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5695:         $subdivided_bubble_lines{$line} =
                   5696:             $env{"form.scantron.sub_bubblelines.$line"};
                   5697:         $responsetype_per_response{$line} =
                   5698:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5699:         my $id = $env{"form.scantron.residpart.$line"};
                   5700:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5701: 	$line++;
                   5702:     }
                   5703: }
                   5704: 
1.423     albertel 5705: =pod 
                   5706: 
                   5707: =item scantron_filenames
                   5708: 
                   5709:    Returns a list of the scantron files in the current course 
                   5710: 
                   5711: =cut
1.422     foxr     5712: 
1.202     albertel 5713: sub scantron_filenames {
1.257     albertel 5714:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5715:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5716:     my $getpropath = 1;
1.662     raeburn  5717:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5718:                                                         $cname,$getpropath);
1.202     albertel 5719:     my @possiblenames;
1.662     raeburn  5720:     if (ref($dirlist) eq 'ARRAY') {
                   5721:         foreach my $filename (sort(@{$dirlist})) {
                   5722: 	    ($filename)=split(/&/,$filename);
                   5723: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5724: 	    $filename=~s/^scantron_orig_//;
                   5725: 	    push(@possiblenames,$filename);
                   5726:         }
1.202     albertel 5727:     }
                   5728:     return @possiblenames;
                   5729: }
                   5730: 
1.423     albertel 5731: =pod 
                   5732: 
                   5733: =item scantron_uploads
                   5734: 
                   5735:    Returns  html drop-down list of scantron files in current course.
                   5736: 
                   5737:  Arguments:
                   5738:    $file2grade - filename to set as selected in the dropdown
                   5739: 
                   5740: =cut
1.422     foxr     5741: 
1.202     albertel 5742: sub scantron_uploads {
1.209     ng       5743:     my ($file2grade) = @_;
1.202     albertel 5744:     my $result=	'<select name="scantron_selectfile">';
                   5745:     $result.="<option></option>";
                   5746:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5747: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5748:     }
                   5749:     $result.="</select>";
                   5750:     return $result;
                   5751: }
                   5752: 
1.423     albertel 5753: =pod 
                   5754: 
                   5755: =item scantron_scantab
                   5756: 
                   5757:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5758:   file.
                   5759: 
                   5760: =cut
1.422     foxr     5761: 
1.82      albertel 5762: sub scantron_scantab {
                   5763:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5764:     $result.='<option></option>'."\n";
1.518     raeburn  5765:     my @lines = &get_scantronformat_file();
                   5766:     if (@lines > 0) {
                   5767:         foreach my $line (@lines) {
                   5768:             next if (($line =~ /^\#/) || ($line eq ''));
                   5769: 	    my ($name,$descrip)=split(/:/,$line);
                   5770: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5771:         }
1.82      albertel 5772:     }
                   5773:     $result.='</select>'."\n";
1.518     raeburn  5774:     return $result;
                   5775: }
                   5776: 
                   5777: =pod
                   5778: 
                   5779: =item get_scantronformat_file
                   5780: 
                   5781:   Returns an array containing lines from the scantron format file for
                   5782:   the domain of the course.
                   5783: 
                   5784:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5785:   lines are from this file.
                   5786: 
                   5787:   Otherwise, if a default.tab has been published in RES space by the 
                   5788:   domainconfig user, lines are from this file.
                   5789: 
                   5790:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5791:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5792: 
1.518     raeburn  5793: =cut
                   5794: 
                   5795: sub get_scantronformat_file {
                   5796:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5797:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5798:     my $gottab = 0;
                   5799:     my @lines;
                   5800:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5801:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5802:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5803:             if ($formatfile ne '-1') {
                   5804:                 @lines = split("\n",$formatfile,-1);
                   5805:                 $gottab = 1;
                   5806:             }
                   5807:         }
                   5808:     }
                   5809:     if (!$gottab) {
                   5810:         my $confname = $cdom.'-domainconfig';
                   5811:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5812:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5813:         if ($formatfile ne '-1') {
                   5814:             @lines = split("\n",$formatfile,-1);
                   5815:             $gottab = 1;
                   5816:         }
                   5817:     }
                   5818:     if (!$gottab) {
1.519     raeburn  5819:         my @domains = &Apache::lonnet::current_machine_domains();
                   5820:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5821:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5822:             @lines = <$fh>;
                   5823:             close($fh);
                   5824:         } else {
                   5825:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5826:             @lines = <$fh>;
                   5827:             close($fh);
                   5828:         }
1.518     raeburn  5829:     }
                   5830:     return @lines;
1.82      albertel 5831: }
                   5832: 
1.423     albertel 5833: =pod 
                   5834: 
                   5835: =item scantron_CODElist
                   5836: 
                   5837:   Returns html drop down of the saved CODE lists from current course,
                   5838:   generated from earlier printings.
                   5839: 
                   5840: =cut
1.422     foxr     5841: 
1.186     albertel 5842: sub scantron_CODElist {
1.257     albertel 5843:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5844:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5845:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5846:     my $namechoice='<option></option>';
1.225     albertel 5847:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5848: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5849: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5850: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5851:     }
                   5852:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5853:     return $namechoice;
                   5854: }
                   5855: 
1.423     albertel 5856: =pod 
                   5857: 
                   5858: =item scantron_CODEunique
                   5859: 
                   5860:   Returns the html for "Each CODE to be used once" radio.
                   5861: 
                   5862: =cut
1.422     foxr     5863: 
1.186     albertel 5864: sub scantron_CODEunique {
1.532     bisitz   5865:     my $result='<span class="LC_nobreak">
1.272     albertel 5866:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5867:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5868:                 </span>
1.532     bisitz   5869:                 <span class="LC_nobreak">
1.272     albertel 5870:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5871:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5872:                 </span>';
1.186     albertel 5873:     return $result;
                   5874: }
1.423     albertel 5875: 
                   5876: =pod 
                   5877: 
                   5878: =item scantron_selectphase
                   5879: 
1.659     raeburn  5880:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5881:   Allows for - starting a grading run.
1.424     albertel 5882:              - downloading existing scan data (original, corrected
1.423     albertel 5883:                                                 or skipped info)
                   5884: 
                   5885:              - uploading new scan data
                   5886: 
                   5887:  Arguments:
                   5888:   $r          - The Apache request object
                   5889:   $file2grade - name of the file that contain the scanned data to score
                   5890: 
                   5891: =cut
1.186     albertel 5892: 
1.75      albertel 5893: sub scantron_selectphase {
1.608     www      5894:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5895:     if (!$symb) {return '';}
1.582     raeburn  5896:     my $map_error;
                   5897:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5898:     if ($map_error) {
                   5899:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5900:         return;
                   5901:     }
1.324     albertel 5902:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5903:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5904:     my $format_selector=&scantron_scantab();
1.186     albertel 5905:     my $CODE_selector=&scantron_CODElist();
                   5906:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5907:     my $result;
1.422     foxr     5908: 
1.513     foxr     5909:     $ssi_error = 0;
                   5910: 
1.606     wenzelju 5911:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5912:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5913: 
                   5914: 	# Chunk of form to prompt for a scantron file upload.
                   5915: 
                   5916:         $r->print('
                   5917:     <br />
                   5918:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5919:        '.&Apache::loncommon::start_data_table_header_row().'
                   5920:             <th>
                   5921:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5922:             </th>
                   5923:        '.&Apache::loncommon::end_data_table_header_row().'
                   5924:        '.&Apache::loncommon::start_data_table_row().'
                   5925:             <td>
                   5926: ');
1.608     www      5927:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5928:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5929:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5930:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5931:     &js_escape(\$alertmsg);
1.606     wenzelju 5932:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5933:     function checkUpload(formname) {
                   5934: 	if (formname.upfile.value == "") {
1.736     damieng  5935: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5936: 	    return false;
                   5937: 	}
                   5938: 	formname.submit();
                   5939:     }'));
                   5940:     $r->print('
                   5941:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5942:                 '.$default_form_data.'
                   5943:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5944:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5945:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5946:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5947:                 <br />
                   5948:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5949:               </form>
                   5950: ');
                   5951: 
                   5952:         $r->print('
                   5953:             </td>
                   5954:        '.&Apache::loncommon::end_data_table_row().'
                   5955:        '.&Apache::loncommon::end_data_table().'
                   5956: ');
                   5957:     }
                   5958: 
1.422     foxr     5959:     # Chunk of form to prompt for a file to grade and how:
                   5960: 
1.489     albertel 5961:     $result.= '
                   5962:     <br />
                   5963:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5964:     <input type="hidden" name="command" value="scantron_warning" />
                   5965:     '.$default_form_data.'
                   5966:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5967:        '.&Apache::loncommon::start_data_table_header_row().'
                   5968:             <th colspan="2">
1.492     albertel 5969:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5970:             </th>
                   5971:        '.&Apache::loncommon::end_data_table_header_row().'
                   5972:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5973:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5974:        '.&Apache::loncommon::end_data_table_row().'
                   5975:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5976:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5977:        '.&Apache::loncommon::end_data_table_row().'
                   5978:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5979:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5980:        '.&Apache::loncommon::end_data_table_row().'
                   5981:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5982:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5983:        '.&Apache::loncommon::end_data_table_row().'
                   5984:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5985:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5986:        '.&Apache::loncommon::end_data_table_row().'
                   5987:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5988: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5989:             <td>
1.492     albertel 5990: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5991:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5992:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5993: 	    </td>
1.489     albertel 5994:        '.&Apache::loncommon::end_data_table_row().'
                   5995:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5996:             <td colspan="2">
1.572     www      5997:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5998:             </td>
1.489     albertel 5999:        '.&Apache::loncommon::end_data_table_row().'
                   6000:     '.&Apache::loncommon::end_data_table().'
                   6001:     </form>
                   6002: ';
1.162     albertel 6003:    
                   6004:     $r->print($result);
                   6005: 
1.422     foxr     6006: 
                   6007: 
                   6008:     # Chunk of the form that prompts to view a scoring office file,
                   6009:     # corrected file, skipped records in a file.
                   6010: 
1.489     albertel 6011:     $r->print('
                   6012:    <br />
                   6013:    <form action="/adm/grades" name="scantron_download">
                   6014:      '.$default_form_data.'
                   6015:      <input type="hidden" name="command" value="scantron_download" />
                   6016:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6017:        '.&Apache::loncommon::start_data_table_header_row().'
                   6018:               <th>
1.492     albertel 6019:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6020:               </th>
                   6021:        '.&Apache::loncommon::end_data_table_header_row().'
                   6022:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6023:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6024:                 <br />
1.492     albertel 6025:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6026:        '.&Apache::loncommon::end_data_table_row().'
                   6027:      '.&Apache::loncommon::end_data_table().'
                   6028:    </form>
                   6029:    <br />
                   6030: ');
1.162     albertel 6031: 
1.457     banghart 6032:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6033: 
1.694     bisitz   6034:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6035:              $default_form_data."\n".
                   6036:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6037:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6038:              '<th colspan="2">
1.572     www      6039:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6040:              '</th>'."\n".
                   6041:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6042:               &Apache::loncommon::start_data_table_row()."\n".
                   6043:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6044:               '<td> '.$sequence_selector.' </td>'.
                   6045:               &Apache::loncommon::end_data_table_row()."\n".
                   6046:               &Apache::loncommon::start_data_table_row()."\n".
                   6047:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6048:               '<td> '.$file_selector.' </td>'."\n".
                   6049:               &Apache::loncommon::end_data_table_row()."\n".
                   6050:               &Apache::loncommon::start_data_table_row()."\n".
                   6051:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6052:               '<td> '.$format_selector.' </td>'."\n".
                   6053:               &Apache::loncommon::end_data_table_row()."\n".
                   6054:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6055:               '<td> '.&mt('Options').' </td>'."\n".
                   6056:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6057:               &Apache::loncommon::end_data_table_row()."\n".
                   6058:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6059:               '<td colspan="2">'."\n".
                   6060:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6061:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6062:               '</td>'."\n".
                   6063:               &Apache::loncommon::end_data_table_row()."\n".
                   6064:               &Apache::loncommon::end_data_table()."\n".
                   6065:               '</form><br />');
                   6066:     return;
1.75      albertel 6067: }
                   6068: 
1.423     albertel 6069: =pod
                   6070: 
                   6071: =item get_scantron_config
                   6072: 
1.711     bisitz   6073:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 6074:    hash of configuration file fields.
                   6075: 
                   6076:  Arguments:
                   6077:     which - the name of the configuration to parse from the file.
                   6078: 
                   6079: 
                   6080:  Returns:
                   6081:             If the named configuration is not in the file, an empty
                   6082:             hash is returned.
                   6083:     a hash with the fields
                   6084:       name         - internal name for the this configuration setup
                   6085:       description  - text to display to operator that describes this config
                   6086:       CODElocation - if 0 or the string 'none'
                   6087:                           - no CODE exists for this config
                   6088:                      if -1 || the string 'letter'
                   6089:                           - a CODE exists for this config and is
                   6090:                             a string of letters
                   6091:                      Unsupported value (but planned for future support)
                   6092:                           if a positive integer
                   6093:                                - The CODE exists as the first n items from
                   6094:                                  the question section of the form
                   6095:                           if the string 'number'
                   6096:                                - The CODE exists for this config and is
                   6097:                                  a string of numbers
                   6098:       CODEstart   - (only matter if a CODE exists) column in the line where
                   6099:                      the CODE starts
                   6100:       CODElength  - length of the CODE
1.573     bisitz   6101:       IDstart     - column where the student/employee ID starts
1.556     weissno  6102:       IDlength    - length of the student/employee ID info
1.423     albertel 6103:       Qstart      - column where the information from the bubbled
                   6104:                     'questions' start
                   6105:       Qlength     - number of columns comprising a single bubble line from
                   6106:                     the sheet. (usually either 1 or 10)
1.424     albertel 6107:       Qon         - either a single character representing the character used
1.423     albertel 6108:                     to signal a bubble was chosen in the positional setup, or
                   6109:                     the string 'letter' if the letter of the chosen bubble is
                   6110:                     in the final, or 'number' if a number representing the
                   6111:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 6112:       Qoff        - the character used to represent that a bubble was
                   6113:                     left blank
1.423     albertel 6114:       PaperID     - if the scanning process generates a unique number for each
                   6115:                     sheet scanned the column that this ID number starts in
                   6116:       PaperIDlength - number of columns that comprise the unique ID number
                   6117:                       for the sheet of paper
1.424     albertel 6118:       FirstName   - column that the first name starts in
1.423     albertel 6119:       FirstNameLength - number of columns that the first name spans
                   6120:  
                   6121:       LastName    - column that the last name starts in
                   6122:       LastNameLength - number of columns that the last name spans
1.649     raeburn  6123:       BubblesPerRow - number of bubbles available in each row used to 
                   6124:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  6125: 
1.423     albertel 6126: =cut
1.422     foxr     6127: 
1.82      albertel 6128: sub get_scantron_config {
                   6129:     my ($which) = @_;
1.518     raeburn  6130:     my @lines = &get_scantronformat_file();
1.82      albertel 6131:     my %config;
1.157     albertel 6132:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  6133:     foreach my $line (@lines) {
1.82      albertel 6134: 	my ($name,$descrip)=split(/:/,$line);
                   6135: 	if ($name ne $which ) { next; }
                   6136: 	chomp($line);
                   6137: 	my @config=split(/:/,$line);
                   6138: 	$config{'name'}=$config[0];
                   6139: 	$config{'description'}=$config[1];
                   6140: 	$config{'CODElocation'}=$config[2];
                   6141: 	$config{'CODEstart'}=$config[3];
                   6142: 	$config{'CODElength'}=$config[4];
                   6143: 	$config{'IDstart'}=$config[5];
                   6144: 	$config{'IDlength'}=$config[6];
                   6145: 	$config{'Qstart'}=$config[7];
1.497     foxr     6146:  	$config{'Qlength'}=$config[8];
1.82      albertel 6147: 	$config{'Qoff'}=$config[9];
                   6148: 	$config{'Qon'}=$config[10];
1.157     albertel 6149: 	$config{'PaperID'}=$config[11];
                   6150: 	$config{'PaperIDlength'}=$config[12];
                   6151: 	$config{'FirstName'}=$config[13];
                   6152: 	$config{'FirstNamelength'}=$config[14];
                   6153: 	$config{'LastName'}=$config[15];
                   6154: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  6155:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 6156: 	last;
                   6157:     }
                   6158:     return %config;
                   6159: }
                   6160: 
1.423     albertel 6161: =pod 
                   6162: 
                   6163: =item username_to_idmap
                   6164: 
1.556     weissno  6165:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6166:     student username:domain. If a single ID occurs for more than one student,
                   6167:     the status of the student is checked, and if Active, the value in the hash
                   6168:     will be set to the Active student.
1.423     albertel 6169: 
                   6170:   Arguments:
                   6171: 
                   6172:     $classlist - reference to the class list hash. This is a hash
                   6173:                  keyed by student name:domain  whose elements are references
1.424     albertel 6174:                  to arrays containing various chunks of information
1.423     albertel 6175:                  about the student. (See loncoursedata for more info).
                   6176: 
                   6177:   Returns
                   6178:     %idmap - the constructed hash
                   6179: 
                   6180: =cut
                   6181: 
1.82      albertel 6182: sub username_to_idmap {
                   6183:     my ($classlist)= @_;
                   6184:     my %idmap;
                   6185:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6186:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6187:         unless ($id eq '') {
                   6188:             if (!exists($idmap{$id})) {
                   6189:                 $idmap{$id} = $student;
                   6190:             } else {
                   6191:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6192:                 if ($status eq 'Active') {
                   6193:                     $idmap{$id} = $student;
                   6194:                 }
                   6195:             }
                   6196:         }
1.82      albertel 6197:     }
                   6198:     return %idmap;
                   6199: }
1.423     albertel 6200: 
                   6201: =pod
                   6202: 
1.424     albertel 6203: =item scantron_fixup_scanline
1.423     albertel 6204: 
                   6205:    Process a requested correction to a scanline.
                   6206: 
                   6207:   Arguments:
                   6208:     $scantron_config   - hash from &get_scantron_config()
                   6209:     $scan_data         - hash of correction information 
                   6210:                           (see &scantron_getfile())
                   6211:     $line              - existing scanline
                   6212:     $whichline         - line number of the passed in scanline
                   6213:     $field             - type of change to process 
                   6214:                          (either 
1.573     bisitz   6215:                           'ID'     -> correct the student/employee ID
1.423     albertel 6216:                           'CODE'   -> correct the CODE
                   6217:                           'answer' -> fixup the submitted answers)
                   6218:     
                   6219:    $args               - hash of additional info,
                   6220:                           - 'ID' 
                   6221:                                'newid' -> studentID to use in replacement
1.424     albertel 6222:                                           of existing one
1.423     albertel 6223:                           - 'CODE' 
                   6224:                                'CODE_ignore_dup' - set to true if duplicates
                   6225:                                                    should be ignored.
                   6226: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6227:                                         if the existing unfound code should
1.423     albertel 6228:                                         be used as is
                   6229:                           - 'answer'
                   6230:                                'response' - new answer or 'none' if blank
                   6231:                                'question' - the bubble line to change
1.503     raeburn  6232:                                'questionnum' - the question identifier,
                   6233:                                                may include subquestion. 
1.423     albertel 6234: 
                   6235:   Returns:
                   6236:     $line - the modified scanline
                   6237: 
                   6238:   Side effects: 
                   6239:     $scan_data - may be updated
                   6240: 
                   6241: =cut
                   6242: 
1.82      albertel 6243: 
1.157     albertel 6244: sub scantron_fixup_scanline {
                   6245:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6246:     if ($field eq 'ID') {
                   6247: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6248: 	    return ($line,1,'New value too large');
1.157     albertel 6249: 	}
                   6250: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6251: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6252: 				     $args->{'newid'});
                   6253: 	}
                   6254: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6255: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6256: 	if ($args->{'newid'}=~/^\s*$/) {
                   6257: 	    &scan_data($scan_data,"$whichline.user",
                   6258: 		       $args->{'username'}.':'.$args->{'domain'});
                   6259: 	}
1.186     albertel 6260:     } elsif ($field eq 'CODE') {
1.192     albertel 6261: 	if ($args->{'CODE_ignore_dup'}) {
                   6262: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6263: 	}
                   6264: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6265: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6266: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6267: 		return ($line,1,'New CODE value too large');
                   6268: 	    }
                   6269: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6270: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6271: 	    }
                   6272: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6273: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6274: 	}
1.157     albertel 6275:     } elsif ($field eq 'answer') {
1.497     foxr     6276: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6277: 	my $off=$scantron_config->{'Qoff'};
                   6278: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6279: 	my $answer=${off}x$length;
                   6280: 	if ($args->{'response'} eq 'none') {
                   6281: 	    &scan_data($scan_data,
1.503     raeburn  6282: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6283: 	} else {
                   6284: 	    if ($on eq 'letter') {
                   6285: 		my @alphabet=('A'..'Z');
                   6286: 		$answer=$alphabet[$args->{'response'}];
                   6287: 	    } elsif ($on eq 'number') {
                   6288: 		$answer=$args->{'response'}+1;
                   6289: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6290: 	    } else {
1.497     foxr     6291: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6292: 	    }
1.497     foxr     6293: 	    &scan_data($scan_data,
1.503     raeburn  6294: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6295: 	}
1.497     foxr     6296: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6297: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6298:     }
                   6299:     return $line;
                   6300: }
1.423     albertel 6301: 
                   6302: =pod
                   6303: 
                   6304: =item scan_data
                   6305: 
                   6306:     Edit or look up  an item in the scan_data hash.
                   6307: 
                   6308:   Arguments:
                   6309:     $scan_data  - The hash (see scantron_getfile)
                   6310:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6311:                   scantronfilename_key).
1.423     albertel 6312:     $data        - New value of the hash entry.
                   6313:     $delete      - If true, the entry is removed from the hash.
                   6314: 
                   6315:   Returns:
                   6316:     The new value of the hash table field (undefined if deleted).
                   6317: 
                   6318: =cut
                   6319: 
                   6320: 
1.157     albertel 6321: sub scan_data {
                   6322:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6323:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6324:     if (defined($value)) {
                   6325: 	$scan_data->{$filename.'_'.$key} = $value;
                   6326:     }
                   6327:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6328:     return $scan_data->{$filename.'_'.$key};
                   6329: }
1.423     albertel 6330: 
1.495     albertel 6331: # ----- These first few routines are general use routines.----
                   6332: 
                   6333: # Return the number of occurences of a pattern in a string.
                   6334: 
                   6335: sub occurence_count {
                   6336:     my ($string, $pattern) = @_;
                   6337: 
                   6338:     my @matches = ($string =~ /$pattern/g);
                   6339: 
                   6340:     return scalar(@matches);
                   6341: }
                   6342: 
                   6343: 
                   6344: # Take a string known to have digits and convert all the
                   6345: # digits into letters in the range J,A..I.
                   6346: 
                   6347: sub digits_to_letters {
                   6348:     my ($input) = @_;
                   6349: 
                   6350:     my @alphabet = ('J', 'A'..'I');
                   6351: 
                   6352:     my @input    = split(//, $input);
                   6353:     my $output ='';
                   6354:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6355: 	if ($input[$i] =~ /\d/) {
                   6356: 	    $output .= $alphabet[$input[$i]];
                   6357: 	} else {
                   6358: 	    $output .= $input[$i];
                   6359: 	}
                   6360:     }
                   6361:     return $output;
                   6362: }
                   6363: 
1.423     albertel 6364: =pod 
                   6365: 
                   6366: =item scantron_parse_scanline
                   6367: 
1.711     bisitz   6368:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6369: 
                   6370:  Arguments:
1.711     bisitz   6371:     line             - The text of the bubblesheet file line to process
1.423     albertel 6372:     whichline        - Line number
1.711     bisitz   6373:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6374:     scan_data        - Hash of extra information about the scanline
                   6375:                        (see scantron_getfile for more information)
                   6376:     just_header      - True if should not process question answers but only
                   6377:                        the stuff to the left of the answers.
1.691     raeburn  6378:     randomorder      - True if randomorder in use
                   6379:     randompick       - True if randompick in use
                   6380:     sequence         - Exam folder URL
                   6381:     master_seq       - Ref to array containing symbs in exam folder
                   6382:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6383:                        (corresponding values are resource objects)
                   6384:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6385:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6386:                        are refs to an array of resource objects, ordered
                   6387:                        according to order used for CODE, when randomorder
                   6388:                        and or randompick are in use.
                   6389:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6390:                        for current line to question number used for same question
                   6391:                         in "Master Sequence" (as seen by Course Coordinator).
                   6392:     startline        - Ref to hash where key is question number (0 is first)
                   6393:                        and value is number of first bubble line for current 
                   6394:                        student or code-based randompick and/or randomorder.
                   6395:     totalref         - Ref of scalar used to score total number of bubble
                   6396:                        lines needed for responses in a scan line (used when
                   6397:                        randompick in use. 
                   6398:     
1.423     albertel 6399:  Returns:
                   6400:    Hash containing the result of parsing the scanline
                   6401: 
                   6402:    Keys are all proceeded by the string 'scantron.'
                   6403: 
                   6404:        CODE    - the CODE in use for this scanline
                   6405:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6406:                  by the operator
                   6407:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6408:                             CODEs were selected, but the usage has been
                   6409:                             forced by the operator
1.556     weissno  6410:        ID  - student/employee ID
1.423     albertel 6411:        PaperID - if used, the ID number printed on the sheet when the 
                   6412:                  paper was scanned
                   6413:        FirstName - first name from the sheet
                   6414:        LastName  - last name from the sheet
                   6415: 
                   6416:      if just_header was not true these key may also exist
                   6417: 
1.447     foxr     6418:        missingerror - a list of bubble ranges that are considered to be answers
                   6419:                       to a single question that don't have any bubbles filled in.
                   6420:                       Of the form questionnumber:firstbubblenumber:count.
                   6421:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6422:                       to a single question that have more than one bubble filled in.
                   6423:                       Of the form questionnumber::firstbubblenumber:count
                   6424:    
                   6425:                 In the above, count is the number of bubble responses in the
                   6426:                 input line needed to represent the possible answers to the question.
                   6427:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6428:                 per line would have count = 2.
                   6429: 
1.423     albertel 6430:        maxquest     - the number of the last bubble line that was parsed
                   6431: 
                   6432:        (<number> starts at 1)
                   6433:        <number>.answer - zero or more letters representing the selected
                   6434:                          letters from the scanline for the bubble line 
                   6435:                          <number>.
                   6436:                          if blank there was either no bubble or there where
                   6437:                          multiple bubbles, (consult the keys missingerror and
                   6438:                          doubleerror if this is an error condition)
                   6439: 
                   6440: =cut
                   6441: 
1.82      albertel 6442: sub scantron_parse_scanline {
1.691     raeburn  6443:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6444:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6445:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6446: 
1.82      albertel 6447:     my %record;
1.691     raeburn  6448:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6449:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6450: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6451: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6452: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6453: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6454: 	    $record{'scantron.CODE'}=substr($data,
                   6455: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6456: 					    $$scantron_config{'CODElength'});
1.191     albertel 6457: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6458: 		$record{'scantron.useCODE'}=1;
                   6459: 	    }
1.192     albertel 6460: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6461: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6462: 	    }
1.82      albertel 6463: 	} else {
                   6464: 	    #FIXME interpret first N questions
                   6465: 	}
                   6466:     }
1.83      albertel 6467:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6468: 				  $$scantron_config{'IDlength'});
1.157     albertel 6469:     $record{'scantron.PaperID'}=
                   6470: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6471: 	       $$scantron_config{'PaperIDlength'});
                   6472:     $record{'scantron.FirstName'}=
                   6473: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6474: 	       $$scantron_config{'FirstNamelength'});
                   6475:     $record{'scantron.LastName'}=
                   6476: 	substr($data,$$scantron_config{'LastName'}-1,
                   6477: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6478:     if ($just_header) { return \%record; }
1.194     albertel 6479: 
1.82      albertel 6480:     my @alphabet=('A'..'Z');
                   6481:     my $questnum=0;
1.447     foxr     6482:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6483: 
1.691     raeburn  6484:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6485:     if ($randompick || $randomorder) {
                   6486:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6487:                                          $master_seq,$symb_to_resource,
                   6488:                                          $partids_by_symb,$orderedforcode,
                   6489:                                          $respnumlookup,$startline);
                   6490:         if ($total) {
                   6491:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6492:         }
                   6493:         if (ref($totalref)) {
                   6494:             $$totalref = $total;
                   6495:         }
                   6496:     }
                   6497:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6498:     chomp($questions);		# Get rid of any trailing \n.
                   6499:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6500:     while (length($questions)) {
1.691     raeburn  6501:         my $answers_needed;
                   6502:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6503:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6504:         } else {
                   6505: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6506:         }
1.503     raeburn  6507:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6508:                              || 1;
                   6509:         $questnum++;
                   6510:         my $quest_id = $questnum;
                   6511:         my $currentquest = substr($questions,0,$answer_length);
                   6512:         $questions       = substr($questions,$answer_length);
                   6513:         if (length($currentquest) < $answer_length) { next; }
                   6514: 
1.691     raeburn  6515:         my $subdivided;
                   6516:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6517:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6518:         } else {
                   6519:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6520:         }
                   6521:         if ($subdivided =~ /,/) {
1.503     raeburn  6522:             my $subquestnum = 1;
                   6523:             my $subquestions = $currentquest;
1.691     raeburn  6524:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6525:             foreach my $subans (@subanswers_needed) {
                   6526:                 my $subans_length =
                   6527:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6528:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6529:                 $subquestions   = substr($subquestions,$subans_length);
                   6530:                 $quest_id = "$questnum.$subquestnum";
                   6531:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6532:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6533:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6534:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6535:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6536:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6537:                 } else {
                   6538:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6539:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6540:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6541:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6542:                 }
                   6543:                 $subquestnum ++;
                   6544:             }
                   6545:         } else {
                   6546:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6547:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6548:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6549:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6550:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6551:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6552:             } else {
                   6553:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6554:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6555:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6556:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6557:             }
                   6558:         }
                   6559:     }
                   6560:     $record{'scantron.maxquest'}=$questnum;
                   6561:     return \%record;
                   6562: }
1.447     foxr     6563: 
1.691     raeburn  6564: sub get_master_seq {
                   6565:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6566:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6567:                    (ref($symb_to_resource) eq 'HASH'));
                   6568:     my $resource_error;
                   6569:     foreach my $resource (@{$resources}) {
                   6570:         my $ressymb;
                   6571:         if (ref($resource)) {
                   6572:             $ressymb = $resource->symb();
                   6573:             push(@{$master_seq},$ressymb);
                   6574:             $symb_to_resource->{$ressymb} = $resource;
                   6575:         } else {
                   6576:             $resource_error = 1;
                   6577:             last;
                   6578:         }
                   6579:     }
                   6580:     return $resource_error;
                   6581: }
                   6582: 
                   6583: sub get_respnum_lookups {
                   6584:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6585:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6586:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6587:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6588:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6589:                    (ref($startline) eq 'HASH'));
                   6590:     my ($user,$scancode);
                   6591:     if ((exists($record->{'scantron.CODE'})) &&
                   6592:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6593:         $scancode = $record->{'scantron.CODE'};
                   6594:     } else {
                   6595:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6596:     }
                   6597:     my @mapresources =
                   6598:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6599:                      $orderedforcode);
                   6600:     my $total = 0;
                   6601:     my $count = 0;
                   6602:     foreach my $resource (@mapresources) {
                   6603:         my $id = $resource->id();
                   6604:         my $symb = $resource->symb();
                   6605:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6606:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6607:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6608:                 if ($respnum ne '') {
                   6609:                     $respnumlookup->{$count} = $respnum;
                   6610:                     $startline->{$count} = $total;
                   6611:                     $total += $bubble_lines_per_response{$respnum};
                   6612:                     $count ++;
                   6613:                 }
                   6614:             }
                   6615:         }
                   6616:     }
                   6617:     return $total;
                   6618: }
                   6619: 
1.503     raeburn  6620: sub scantron_validator_lettnum {
                   6621:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6622:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6623:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6624: 
                   6625:     # Qon 'letter' implies for each slot in currquest we have:
                   6626:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6627:     #    about anything else (esp. a value of Qoff) for missing
                   6628:     #    bubbles.
                   6629:     #
                   6630:     # Qon 'number' implies each slot gives a digit that indexes the
                   6631:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6632:     #    and * or ? for double bubbles on a single line.
                   6633:     #
1.447     foxr     6634: 
1.503     raeburn  6635:     my $matchon;
                   6636:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6637:         $matchon = '[A-Z]';
                   6638:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6639:         $matchon = '\d';
                   6640:     }
                   6641:     my $occurrences = 0;
1.691     raeburn  6642:     my $responsenum = $questnum-1;
                   6643:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6644:        $responsenum = $respnumlookup->{$questnum-1} 
                   6645:     }
                   6646:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6647:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6648:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6649:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6650:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6651:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6652:         my @singlelines = split('',$currquest);
                   6653:         foreach my $entry (@singlelines) {
                   6654:             $occurrences = &occurence_count($entry,$matchon);
                   6655:             if ($occurrences > 1) {
                   6656:                 last;
                   6657:             }
1.691     raeburn  6658:         }
1.503     raeburn  6659:     } else {
                   6660:         $occurrences = &occurence_count($currquest,$matchon); 
                   6661:     }
                   6662:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6663:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6664:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6665:             my $bubble = substr($currquest,$ans,1);
                   6666:             if ($bubble =~ /$matchon/ ) {
                   6667:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6668:                     if ($bubble == 0) {
                   6669:                         $bubble = 10; 
                   6670:                     }
                   6671:                     $record->{"scantron.$ansnum.answer"} = 
                   6672:                         $alphabet->[$bubble-1];
                   6673:                 } else {
                   6674:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6675:                 }
                   6676:             } else {
                   6677:                 $record->{"scantron.$ansnum.answer"}='';
                   6678:             }
                   6679:             $ansnum++;
                   6680:         }
                   6681:     } elsif (!defined($currquest)
                   6682:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6683:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6684:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6685:             $record->{"scantron.$ansnum.answer"}='';
                   6686:             $ansnum++;
                   6687:         }
                   6688:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6689:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6690:         }
                   6691:     } else {
                   6692:         if ($$scantron_config{'Qon'} eq 'number') {
                   6693:             $currquest = &digits_to_letters($currquest);            
                   6694:         }
                   6695:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6696:             my $bubble = substr($currquest,$ans,1);
                   6697:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6698:             $ansnum++;
                   6699:         }
                   6700:     }
                   6701:     return $ansnum;
                   6702: }
1.447     foxr     6703: 
1.503     raeburn  6704: sub scantron_validator_positional {
                   6705:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6706:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6707:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6708: 
1.503     raeburn  6709:     # Otherwise there's a positional notation;
                   6710:     # each bubble line requires Qlength items, and there are filled in
                   6711:     # bubbles for each case where there 'Qon' characters.
                   6712:     #
1.447     foxr     6713: 
1.503     raeburn  6714:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6715: 
1.503     raeburn  6716:     # If the split only gives us one element.. the full length of the
                   6717:     # answer string, no bubbles are filled in:
1.447     foxr     6718: 
1.507     raeburn  6719:     if ($answers_needed eq '') {
                   6720:         return;
                   6721:     }
                   6722: 
1.503     raeburn  6723:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6724:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6725:             $record->{"scantron.$ansnum.answer"}='';
                   6726:             $ansnum++;
                   6727:         }
                   6728:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6729:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6730:         }
                   6731:     } elsif (scalar(@array) == 2) {
                   6732:         my $location = length($array[0]);
                   6733:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6734:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6735:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6736:             if ($ans eq $line_num) {
                   6737:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6738:             } else {
                   6739:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6740:             }
                   6741:             $ansnum++;
                   6742:          }
                   6743:     } else {
                   6744:         #  If there's more than one instance of a bubble character
                   6745:         #  That's a double bubble; with positional notation we can
                   6746:         #  record all the bubbles filled in as well as the
                   6747:         #  fact this response consists of multiple bubbles.
                   6748:         #
1.691     raeburn  6749:         my $responsenum = $questnum-1;
                   6750:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6751:             $responsenum = $respnumlookup->{$questnum-1}
                   6752:         }
                   6753:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6754:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6755:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6756:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6757:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6758:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6759:             my $doubleerror = 0;
                   6760:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6761:                    (!$doubleerror)) {
                   6762:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6763:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6764:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6765:                if (length(@currarray) > 2) {
                   6766:                    $doubleerror = 1;
                   6767:                } 
                   6768:             }
                   6769:             if ($doubleerror) {
                   6770:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6771:             }
                   6772:         } else {
                   6773:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6774:         }
                   6775:         my $item = $ansnum;
                   6776:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6777:             $record->{"scantron.$item.answer"} = '';
                   6778:             $item ++;
                   6779:         }
1.447     foxr     6780: 
1.503     raeburn  6781:         my @ans=@array;
                   6782:         my $i=0;
                   6783:         my $increment = 0;
                   6784:         while ($#ans) {
                   6785:             $i+=length($ans[0]) + $increment;
                   6786:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6787:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6788:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6789:             shift(@ans);
                   6790:             $increment = 1;
                   6791:         }
                   6792:         $ansnum += $answers_needed;
1.82      albertel 6793:     }
1.503     raeburn  6794:     return $ansnum;
1.82      albertel 6795: }
                   6796: 
1.423     albertel 6797: =pod
                   6798: 
                   6799: =item scantron_add_delay
                   6800: 
                   6801:    Adds an error message that occurred during the grading phase to a
                   6802:    queue of messages to be shown after grading pass is complete
                   6803: 
                   6804:  Arguments:
1.424     albertel 6805:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6806:    $scanline    - the scanline that caused the error
                   6807:    $errormesage - the error message
                   6808:    $errorcode   - a numeric code for the error
                   6809: 
                   6810:  Side Effects:
1.424     albertel 6811:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6812: 
                   6813: =cut
                   6814: 
1.82      albertel 6815: sub scantron_add_delay {
1.140     albertel 6816:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6817:     push(@$delayqueue,
                   6818: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6819: 	  'ecode' => $errorcode }
                   6820: 	 );
1.82      albertel 6821: }
                   6822: 
1.423     albertel 6823: =pod
                   6824: 
                   6825: =item scantron_find_student
                   6826: 
1.424     albertel 6827:    Finds the username for the current scanline
                   6828: 
                   6829:   Arguments:
                   6830:    $scantron_record - hash result from scantron_parse_scanline
                   6831:    $scan_data       - hash of correction information 
                   6832:                       (see &scantron_getfile() form more information)
                   6833:    $idmap           - hash from &username_to_idmap()
                   6834:    $line            - number of current scanline
                   6835:  
                   6836:   Returns:
                   6837:    Either 'username:domain' or undef if unknown
                   6838: 
1.423     albertel 6839: =cut
                   6840: 
1.82      albertel 6841: sub scantron_find_student {
1.157     albertel 6842:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6843:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6844:     if ($scanID =~ /^\s*$/) {
                   6845:  	return &scan_data($scan_data,"$line.user");
                   6846:     }
1.83      albertel 6847:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6848:  	if (lc($id) eq lc($scanID)) {
                   6849:  	    return $$idmap{$id};
                   6850:  	}
1.83      albertel 6851:     }
                   6852:     return undef;
                   6853: }
                   6854: 
1.423     albertel 6855: =pod
                   6856: 
                   6857: =item scantron_filter
                   6858: 
1.424     albertel 6859:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6860:    hidden resources was selected
                   6861: 
1.423     albertel 6862: =cut
                   6863: 
1.83      albertel 6864: sub scantron_filter {
                   6865:     my ($curres)=@_;
1.331     albertel 6866: 
                   6867:     if (ref($curres) && $curres->is_problem()) {
                   6868: 	# if the user has asked to not have either hidden
                   6869: 	# or 'randomout' controlled resources to be graded
                   6870: 	# don't include them
                   6871: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6872: 	    && $curres->randomout) {
                   6873: 	    return 0;
                   6874: 	}
1.83      albertel 6875: 	return 1;
                   6876:     }
                   6877:     return 0;
1.82      albertel 6878: }
                   6879: 
1.423     albertel 6880: =pod
                   6881: 
                   6882: =item scantron_process_corrections
                   6883: 
1.424     albertel 6884:    Gets correction information out of submitted form data and corrects
                   6885:    the scanline
                   6886: 
1.423     albertel 6887: =cut
                   6888: 
1.157     albertel 6889: sub scantron_process_corrections {
                   6890:     my ($r) = @_;
1.257     albertel 6891:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6892:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6893:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6894:     my $which=$env{'form.scantron_line'};
1.200     albertel 6895:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6896:     my ($skip,$err,$errmsg);
1.257     albertel 6897:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6898: 	$skip=1;
1.257     albertel 6899:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6900: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6901: 	    $env{'form.scantron_domain'};
1.157     albertel 6902: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6903: 	($line,$err,$errmsg)=
                   6904: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6905: 				     'ID',{'newid'=>$newid,
1.257     albertel 6906: 				    'username'=>$env{'form.scantron_username'},
                   6907: 				    'domain'=>$env{'form.scantron_domain'}});
                   6908:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6909: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6910: 	my $newCODE;
1.192     albertel 6911: 	my %args;
1.190     albertel 6912: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6913: 	    $newCODE='use_unfound';
1.190     albertel 6914: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6915: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6916: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6917: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6918: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6919: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6920: 	}
1.257     albertel 6921: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6922: 	    $args{'CODE_ignore_dup'}=1;
                   6923: 	}
                   6924: 	$args{'CODE'}=$newCODE;
1.186     albertel 6925: 	($line,$err,$errmsg)=
                   6926: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6927: 				     'CODE',\%args);
1.257     albertel 6928:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6929: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6930: 	    ($line,$err,$errmsg)=
                   6931: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6932: 					 $which,'answer',
                   6933: 					 { 'question'=>$question,
1.503     raeburn  6934: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6935:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6936: 	    if ($err) { last; }
                   6937: 	}
                   6938:     }
                   6939:     if ($err) {
1.703     bisitz   6940:         $r->print(
                   6941:             '<p class="LC_error">'
                   6942:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6943:                 $errmsg)
1.704     raeburn  6944:            .'</p>');
1.157     albertel 6945:     } else {
1.200     albertel 6946: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6947: 	&scantron_putfile($scanlines,$scan_data);
                   6948:     }
                   6949: }
                   6950: 
1.423     albertel 6951: =pod
                   6952: 
                   6953: =item reset_skipping_status
                   6954: 
1.424     albertel 6955:    Forgets the current set of remember skipped scanlines (and thus
                   6956:    reverts back to considering all lines in the
                   6957:    scantron_skipped_<filename> file)
                   6958: 
1.423     albertel 6959: =cut
                   6960: 
1.200     albertel 6961: sub reset_skipping_status {
                   6962:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6963:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6964:     &scantron_putfile(undef,$scan_data);
                   6965: }
                   6966: 
1.423     albertel 6967: =pod
                   6968: 
                   6969: =item start_skipping
                   6970: 
1.424     albertel 6971:    Marks a scanline to be skipped. 
                   6972: 
1.423     albertel 6973: =cut
                   6974: 
1.376     albertel 6975: sub start_skipping {
1.200     albertel 6976:     my ($scan_data,$i)=@_;
                   6977:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6978:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6979: 	$remembered{$i}=2;
                   6980:     } else {
                   6981: 	$remembered{$i}=1;
                   6982:     }
1.200     albertel 6983:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6984: }
                   6985: 
1.423     albertel 6986: =pod
                   6987: 
                   6988: =item should_be_skipped
                   6989: 
1.424     albertel 6990:    Checks whether a scanline should be skipped.
                   6991: 
1.423     albertel 6992: =cut
                   6993: 
1.200     albertel 6994: sub should_be_skipped {
1.376     albertel 6995:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6996:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6997: 	# not redoing old skips
1.376     albertel 6998: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6999: 	return 0;
                   7000:     }
                   7001:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7002: 
                   7003:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7004: 	return 0;
                   7005:     }
1.200     albertel 7006:     return 1;
                   7007: }
                   7008: 
1.423     albertel 7009: =pod
                   7010: 
                   7011: =item remember_current_skipped
                   7012: 
1.424     albertel 7013:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7014:    file and remembers them into scan_data for later use.
                   7015: 
1.423     albertel 7016: =cut
                   7017: 
1.200     albertel 7018: sub remember_current_skipped {
                   7019:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7020:     my %to_remember;
                   7021:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7022: 	if ($scanlines->{'skipped'}[$i]) {
                   7023: 	    $to_remember{$i}=1;
                   7024: 	}
                   7025:     }
1.376     albertel 7026: 
1.200     albertel 7027:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7028:     &scantron_putfile(undef,$scan_data);
                   7029: }
                   7030: 
1.423     albertel 7031: =pod
                   7032: 
                   7033: =item check_for_error
                   7034: 
1.424     albertel 7035:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7036:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7037:     something went wrong.
                   7038: 
1.423     albertel 7039: =cut
                   7040: 
1.200     albertel 7041: sub check_for_error {
                   7042:     my ($r,$result)=@_;
                   7043:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7044: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7045:     }
                   7046: }
1.157     albertel 7047: 
1.423     albertel 7048: =pod
                   7049: 
                   7050: =item scantron_warning_screen
                   7051: 
1.424     albertel 7052:    Interstitial screen to make sure the operator has selected the
                   7053:    correct options before we start the validation phase.
                   7054: 
1.423     albertel 7055: =cut
                   7056: 
1.203     albertel 7057: sub scantron_warning_screen {
1.650     raeburn  7058:     my ($button_text,$symb)=@_;
1.257     albertel 7059:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 7060:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7061:     my $CODElist;
1.284     albertel 7062:     if ($scantron_config{'CODElocation'} &&
                   7063: 	$scantron_config{'CODEstart'} &&
                   7064: 	$scantron_config{'CODElength'}) {
                   7065: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7066: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7067: 	$CODElist=
1.492     albertel 7068: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7069: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7070:     }
1.663     raeburn  7071:     my $lastbubblepoints;
                   7072:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7073:         $lastbubblepoints =
                   7074:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7075:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7076:     }
1.492     albertel 7077:     return ('
1.203     albertel 7078: <p>
1.492     albertel 7079: <span class="LC_warning">
1.705     raeburn  7080: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7081: </p>
                   7082: <table>
1.492     albertel 7083: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7084: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7085: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7086: </table>
1.680     raeburn  7087: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7088: '.&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 7089: 
                   7090: <br />
1.492     albertel 7091: ');
1.203     albertel 7092: }
                   7093: 
1.423     albertel 7094: =pod
                   7095: 
                   7096: =item scantron_do_warning
                   7097: 
1.424     albertel 7098:    Check if the operator has picked something for all required
                   7099:    fields. Error out if something is missing.
                   7100: 
1.423     albertel 7101: =cut
                   7102: 
1.203     albertel 7103: sub scantron_do_warning {
1.608     www      7104:     my ($r,$symb)=@_;
1.203     albertel 7105:     if (!$symb) {return '';}
1.324     albertel 7106:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7107:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7108:     if ( $env{'form.selectpage'} eq '' ||
                   7109: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7110: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7111: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7112: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7113: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7114: 	} 
1.257     albertel 7115: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7116: 	    $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 7117: 	} 
1.257     albertel 7118: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7119: 	    $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 7120: 	} 
                   7121:     } else {
1.650     raeburn  7122: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  7123:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7124: 	$r->print('
1.663     raeburn  7125: '.$warning.$bubbledbyhand.'
1.492     albertel 7126: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7127: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7128: ');
1.237     albertel 7129:     }
1.614     www      7130:     $r->print("</form><br />");
1.203     albertel 7131:     return '';
                   7132: }
                   7133: 
1.423     albertel 7134: =pod
                   7135: 
                   7136: =item scantron_form_start
                   7137: 
1.424     albertel 7138:     html hidden input for remembering all selected grading options
                   7139: 
1.423     albertel 7140: =cut
                   7141: 
1.203     albertel 7142: sub scantron_form_start {
                   7143:     my ($max_bubble)=@_;
                   7144:     my $result= <<SCANTRONFORM;
                   7145: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7146:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7147:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7148:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7149:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7150:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7151:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7152:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7153:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7154:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7155: SCANTRONFORM
1.447     foxr     7156: 
                   7157:   my $line = 0;
                   7158:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7159:        my $chunk =
                   7160: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7161:        $chunk .=
                   7162: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7163:        $chunk .= 
                   7164:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7165:        $chunk .=
                   7166:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7167:        $chunk .=
                   7168:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7169:        $result .= $chunk;
                   7170:        $line++;
1.691     raeburn  7171:     }
1.203     albertel 7172:     return $result;
                   7173: }
                   7174: 
1.423     albertel 7175: =pod
                   7176: 
                   7177: =item scantron_validate_file
                   7178: 
1.659     raeburn  7179:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7180: 
                   7181:     Also processes any necessary information resets that need to
                   7182:     occur before validation begins (ignore previous corrections,
                   7183:     restarting the skipped records processing)
                   7184: 
1.423     albertel 7185: =cut
                   7186: 
1.157     albertel 7187: sub scantron_validate_file {
1.608     www      7188:     my ($r,$symb) = @_;
1.157     albertel 7189:     if (!$symb) {return '';}
1.324     albertel 7190:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7191:     
1.703     bisitz   7192:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7193:     # them when doing the corrections reset
1.257     albertel 7194:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7195: 	&reset_skipping_status();
                   7196:     }
1.257     albertel 7197:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7198: 	&remember_current_skipped();
1.257     albertel 7199: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7200:     }
                   7201: 
1.257     albertel 7202:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7203: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7204: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7205: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7206: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7207:     }
1.200     albertel 7208: 
1.257     albertel 7209:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7210: 	&scantron_process_corrections($r);
                   7211:     }
1.503     raeburn  7212:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7213:     #get the student pick code ready
                   7214:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7215:     my $nav_error;
1.649     raeburn  7216:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   7217:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7218:     if ($nav_error) {
                   7219:         $r->print(&navmap_errormsg());
                   7220:         return '';
                   7221:     }
1.203     albertel 7222:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7223:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7224:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7225:     }
1.157     albertel 7226:     $r->print($result);
                   7227:     
1.334     albertel 7228:     my @validate_phases=( 'sequence',
                   7229: 			  'ID',
1.157     albertel 7230: 			  'CODE',
                   7231: 			  'doublebubble',
                   7232: 			  'missingbubbles');
1.257     albertel 7233:     if (!$env{'form.validatepass'}) {
                   7234: 	$env{'form.validatepass'} = 0;
1.157     albertel 7235:     }
1.257     albertel 7236:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7237: 
1.448     foxr     7238: 
1.157     albertel 7239:     my $stop=0;
                   7240:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7241: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7242: 	$r->rflush();
1.691     raeburn  7243:      
1.157     albertel 7244: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7245: 	{
                   7246: 	    no strict 'refs';
                   7247: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7248: 	}
                   7249:     }
                   7250:     if (!$stop) {
1.650     raeburn  7251: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7252: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7253:                   $warning.
                   7254:                   &mt('Perform verification for each student after storage of submissions?').
                   7255:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7256:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7257:                   ('&nbsp;'x3).'<label>'.
                   7258:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7259:                   '</label></span><br />'.
                   7260:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7261:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7262:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7263:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7264:     } else {
                   7265: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7266: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7267:     }
                   7268:     if ($stop) {
1.334     albertel 7269: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7270: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7271: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7272: 
1.650     raeburn  7273: 	    $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 7274: 	} else {
1.503     raeburn  7275:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7276: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7277:             } else {
1.539     riegler  7278:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7279:             }
1.492     albertel 7280: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7281: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7282: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7283: 	}
1.157     albertel 7284:     }
1.614     www      7285:     $r->print(" </form><br />");
1.157     albertel 7286:     return '';
                   7287: }
                   7288: 
1.423     albertel 7289: 
                   7290: =pod
                   7291: 
                   7292: =item scantron_remove_file
                   7293: 
1.659     raeburn  7294:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7295:    scantron_original_<filename> is never removed
                   7296: 
                   7297: 
1.423     albertel 7298: =cut
                   7299: 
1.200     albertel 7300: sub scantron_remove_file {
1.192     albertel 7301:     my ($which)=@_;
1.257     albertel 7302:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7303:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7304:     my $file='scantron_';
1.200     albertel 7305:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7306: 	$file.=$which.'_';
1.192     albertel 7307:     } else {
                   7308: 	return 'refused';
                   7309:     }
1.257     albertel 7310:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7311:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7312: }
                   7313: 
1.423     albertel 7314: 
                   7315: =pod
                   7316: 
                   7317: =item scantron_remove_scan_data
                   7318: 
1.659     raeburn  7319:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7320:    data file.  (In the case that both the are doing skipped records we need
                   7321:    to remember the old skipped lines for the time being so that element
                   7322:    persists for a while.)
                   7323: 
1.423     albertel 7324: =cut
                   7325: 
1.200     albertel 7326: sub scantron_remove_scan_data {
1.257     albertel 7327:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7328:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7329:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7330:     my @todelete;
1.257     albertel 7331:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7332:     foreach my $key (@keys) {
                   7333: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7334: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7335: 		$key=~/remember_skipping/) {
                   7336: 		next;
                   7337: 	    }
1.192     albertel 7338: 	    push(@todelete,$key);
                   7339: 	}
                   7340:     }
1.200     albertel 7341:     my $result;
1.192     albertel 7342:     if (@todelete) {
1.491     albertel 7343: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7344: 				       \@todelete,$cdom,$cname);
                   7345:     } else {
                   7346: 	$result = 'ok';
1.192     albertel 7347:     }
                   7348:     return $result;
                   7349: }
                   7350: 
1.423     albertel 7351: 
                   7352: =pod
                   7353: 
                   7354: =item scantron_getfile
                   7355: 
1.659     raeburn  7356:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7357:     the scan_data hash
                   7358:   
                   7359:   Arguments:
                   7360:     None
                   7361: 
                   7362:   Returns:
                   7363:     2 hash references
                   7364: 
                   7365:      - first one has 
                   7366:          orig      -
                   7367:          corrected -
                   7368:          skipped   -  each of which points to an array ref of the specified
                   7369:                       file broken up into individual lines
                   7370:          count     - number of scanlines
                   7371:  
                   7372:      - second is the scan_data hash possible keys are
1.425     albertel 7373:        ($number refers to scanline numbered $number and thus the key affects
                   7374:         only that scanline
                   7375:         $bubline refers to the specific bubble line element and the aspects
                   7376:         refers to that specific bubble line element)
                   7377: 
                   7378:        $number.user - username:domain to use
                   7379:        $number.CODE_ignore_dup 
                   7380:                     - ignore the duplicate CODE error 
                   7381:        $number.useCODE
                   7382:                     - use the CODE in the scanline as is
                   7383:        $number.no_bubble.$bubline
                   7384:                     - it is valid that there is no bubbled in bubble
                   7385:                       at $number $bubline
                   7386:        remember_skipping
                   7387:                     - a frozen hash containing keys of $number and values
                   7388:                       of either 
                   7389:                         1 - we are on a 'do skipped records pass' and plan
                   7390:                             on processing this line
                   7391:                         2 - we are on a 'do skipped records pass' and this
                   7392:                             scanline has been marked to skip yet again
1.424     albertel 7393: 
1.423     albertel 7394: =cut
                   7395: 
1.157     albertel 7396: sub scantron_getfile {
1.200     albertel 7397:     #FIXME really would prefer a scantron directory
1.257     albertel 7398:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7399:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7400:     my $lines;
                   7401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7402: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7403:     my %scanlines;
                   7404:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7405:     my $temp=$scanlines{'orig'};
                   7406:     $scanlines{'count'}=$#$temp;
                   7407: 
                   7408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7409: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7410:     if ($lines eq '-1') {
                   7411: 	$scanlines{'corrected'}=[];
                   7412:     } else {
                   7413: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7414:     }
                   7415:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7416: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7417:     if ($lines eq '-1') {
                   7418: 	$scanlines{'skipped'}=[];
                   7419:     } else {
                   7420: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7421:     }
1.175     albertel 7422:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7423:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7424:     my %scan_data = @tmp;
                   7425:     return (\%scanlines,\%scan_data);
                   7426: }
                   7427: 
1.423     albertel 7428: =pod
                   7429: 
                   7430: =item lonnet_putfile
                   7431: 
1.424     albertel 7432:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7433: 
                   7434:  Arguments:
                   7435:    $contents - data to store
                   7436:    $filename - filename to store $contents into
                   7437: 
                   7438:  Returns:
                   7439:    result value from &Apache::lonnet::finishuserfileupload
                   7440: 
1.423     albertel 7441: =cut
                   7442: 
1.157     albertel 7443: sub lonnet_putfile {
                   7444:     my ($contents,$filename)=@_;
1.257     albertel 7445:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7446:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7447:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7448:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7449: 
                   7450: }
                   7451: 
1.423     albertel 7452: =pod
                   7453: 
                   7454: =item scantron_putfile
                   7455: 
1.659     raeburn  7456:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7457:     scan_data hash. (Does not modify the original version only the
                   7458:     corrected and skipped versions.
                   7459: 
                   7460:  Arguments:
                   7461:     $scanlines - hash ref that looks like the first return value from
                   7462:                  &scantron_getfile()
                   7463:     $scan_data - hash ref that looks like the second return value from
                   7464:                  &scantron_getfile()
                   7465: 
1.423     albertel 7466: =cut
                   7467: 
1.157     albertel 7468: sub scantron_putfile {
                   7469:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7470:     #FIXME really would prefer a scantron directory
1.257     albertel 7471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7473:     if ($scanlines) {
                   7474: 	my $prefix='scantron_';
1.157     albertel 7475: # no need to update orig, shouldn't change
                   7476: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7477: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7478: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7479: 			$prefix.'corrected_'.
1.257     albertel 7480: 			$env{'form.scantron_selectfile'});
1.200     albertel 7481: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7482: 			$prefix.'skipped_'.
1.257     albertel 7483: 			$env{'form.scantron_selectfile'});
1.200     albertel 7484:     }
1.175     albertel 7485:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7486: }
                   7487: 
1.423     albertel 7488: =pod
                   7489: 
                   7490: =item scantron_get_line
                   7491: 
1.424     albertel 7492:    Returns the correct version of the scanline
                   7493: 
                   7494:  Arguments:
                   7495:     $scanlines - hash ref that looks like the first return value from
                   7496:                  &scantron_getfile()
                   7497:     $scan_data - hash ref that looks like the second return value from
                   7498:                  &scantron_getfile()
                   7499:     $i         - number of the requested line (starts at 0)
                   7500: 
                   7501:  Returns:
                   7502:    A scanline, (either the original or the corrected one if it
                   7503:    exists), or undef if the requested scanline should be
                   7504:    skipped. (Either because it's an skipped scanline, or it's an
                   7505:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7506:    pass.
                   7507: 
1.423     albertel 7508: =cut
                   7509: 
1.157     albertel 7510: sub scantron_get_line {
1.200     albertel 7511:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7512:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7513:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7514:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7515:     return $scanlines->{'orig'}[$i]; 
                   7516: }
                   7517: 
1.423     albertel 7518: =pod
                   7519: 
                   7520: =item scantron_todo_count
                   7521: 
1.424     albertel 7522:     Counts the number of scanlines that need processing.
                   7523: 
                   7524:  Arguments:
                   7525:     $scanlines - hash ref that looks like the first return value from
                   7526:                  &scantron_getfile()
                   7527:     $scan_data - hash ref that looks like the second return value from
                   7528:                  &scantron_getfile()
                   7529: 
                   7530:  Returns:
                   7531:     $count - number of scanlines to process
                   7532: 
1.423     albertel 7533: =cut
                   7534: 
1.200     albertel 7535: sub get_todo_count {
                   7536:     my ($scanlines,$scan_data)=@_;
                   7537:     my $count=0;
                   7538:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7539: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7540: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7541: 	$count++;
                   7542:     }
                   7543:     return $count;
                   7544: }
                   7545: 
1.423     albertel 7546: =pod
                   7547: 
                   7548: =item scantron_put_line
                   7549: 
1.659     raeburn  7550:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7551:     data file.
                   7552: 
                   7553:  Arguments:
                   7554:     $scanlines - hash ref that looks like the first return value from
                   7555:                  &scantron_getfile()
                   7556:     $scan_data - hash ref that looks like the second return value from
                   7557:                  &scantron_getfile()
                   7558:     $i         - line number to update
                   7559:     $newline   - contents of the updated scanline
                   7560:     $skip      - if true make the line for skipping and update the
                   7561:                  'skipped' file
                   7562: 
1.423     albertel 7563: =cut
                   7564: 
1.157     albertel 7565: sub scantron_put_line {
1.200     albertel 7566:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7567:     if ($skip) {
                   7568: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7569: 	&start_skipping($scan_data,$i);
1.157     albertel 7570: 	return;
                   7571:     }
                   7572:     $scanlines->{'corrected'}[$i]=$newline;
                   7573: }
                   7574: 
1.423     albertel 7575: =pod
                   7576: 
                   7577: =item scantron_clear_skip
                   7578: 
1.424     albertel 7579:    Remove a line from the 'skipped' file
                   7580: 
                   7581:  Arguments:
                   7582:     $scanlines - hash ref that looks like the first return value from
                   7583:                  &scantron_getfile()
                   7584:     $scan_data - hash ref that looks like the second return value from
                   7585:                  &scantron_getfile()
                   7586:     $i         - line number to update
                   7587: 
1.423     albertel 7588: =cut
                   7589: 
1.376     albertel 7590: sub scantron_clear_skip {
                   7591:     my ($scanlines,$scan_data,$i)=@_;
                   7592:     if (exists($scanlines->{'skipped'}[$i])) {
                   7593: 	undef($scanlines->{'skipped'}[$i]);
                   7594: 	return 1;
                   7595:     }
                   7596:     return 0;
                   7597: }
                   7598: 
1.423     albertel 7599: =pod
                   7600: 
                   7601: =item scantron_filter_not_exam
                   7602: 
1.424     albertel 7603:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7604:    filter out resources that are not marked as 'exam' mode
                   7605: 
1.423     albertel 7606: =cut
                   7607: 
1.334     albertel 7608: sub scantron_filter_not_exam {
                   7609:     my ($curres)=@_;
                   7610:     
                   7611:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7612: 	# if the user has asked to not have either hidden
                   7613: 	# or 'randomout' controlled resources to be graded
                   7614: 	# don't include them
                   7615: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7616: 	    && $curres->randomout) {
                   7617: 	    return 0;
                   7618: 	}
                   7619: 	return 1;
                   7620:     }
                   7621:     return 0;
                   7622: }
                   7623: 
1.423     albertel 7624: =pod
                   7625: 
                   7626: =item scantron_validate_sequence
                   7627: 
1.424     albertel 7628:     Validates the selected sequence, checking for resource that are
                   7629:     not set to exam mode.
                   7630: 
1.423     albertel 7631: =cut
                   7632: 
1.334     albertel 7633: sub scantron_validate_sequence {
                   7634:     my ($r,$currentphase) = @_;
                   7635: 
                   7636:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7637:     unless (ref($navmap)) {
                   7638:         $r->print(&navmap_errormsg());
                   7639:         return (1,$currentphase);
                   7640:     }
1.334     albertel 7641:     my (undef,undef,$sequence)=
                   7642: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7643: 
                   7644:     my $map=$navmap->getResourceByUrl($sequence);
                   7645: 
                   7646:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7647:                                     value="ignore" />');
                   7648:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7649: 	my @resources=
                   7650: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7651: 	if (@resources) {
1.675     bisitz   7652: 	    $r->print(
                   7653:                 '<p class="LC_warning">'
                   7654:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7655:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7656:                    .' work correctly.')
                   7657:                .'</p>'
                   7658:             );
1.334     albertel 7659: 	    return (1,$currentphase);
                   7660: 	}
                   7661:     }
                   7662: 
                   7663:     return (0,$currentphase+1);
                   7664: }
                   7665: 
1.423     albertel 7666: 
                   7667: 
1.157     albertel 7668: sub scantron_validate_ID {
                   7669:     my ($r,$currentphase) = @_;
                   7670:     
                   7671:     #get student info
                   7672:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7673:     my %idmap=&username_to_idmap($classlist);
                   7674: 
                   7675:     #get scantron line setup
1.257     albertel 7676:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7677:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7678: 
                   7679:     my $nav_error;
1.649     raeburn  7680:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7681:     if ($nav_error) {
                   7682:         $r->print(&navmap_errormsg());
                   7683:         return(1,$currentphase);
                   7684:     }
1.157     albertel 7685: 
                   7686:     my %found=('ids'=>{},'usernames'=>{});
                   7687:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7688: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7689: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7690: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7691: 						 $scan_data);
                   7692: 	my $id=$$scan_record{'scantron.ID'};
                   7693: 	my $found;
                   7694: 	foreach my $checkid (keys(%idmap)) {
                   7695: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7696: 	}
                   7697: 	if ($found) {
                   7698: 	    my $username=$idmap{$found};
                   7699: 	    if ($found{'ids'}{$found}) {
                   7700: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7701: 					 $line,'duplicateID',$found);
1.194     albertel 7702: 		return(1,$currentphase);
1.157     albertel 7703: 	    } elsif ($found{'usernames'}{$username}) {
                   7704: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7705: 					 $line,'duplicateID',$username);
1.194     albertel 7706: 		return(1,$currentphase);
1.157     albertel 7707: 	    }
1.186     albertel 7708: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7709: 	    $found{'ids'}{$found}++;
                   7710: 	    $found{'usernames'}{$username}++;
                   7711: 	} else {
                   7712: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7713: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7714: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7715: 		    &scantron_get_correction($r,$i,$scan_record,
                   7716: 					     \%scantron_config,
                   7717: 					     $line,'duplicateID',$username);
1.194     albertel 7718: 		    return(1,$currentphase);
1.157     albertel 7719: 		} elsif (!defined($username)) {
                   7720: 		    &scantron_get_correction($r,$i,$scan_record,
                   7721: 					     \%scantron_config,
                   7722: 					     $line,'incorrectID');
1.194     albertel 7723: 		    return(1,$currentphase);
1.157     albertel 7724: 		}
                   7725: 		$found{'usernames'}{$username}++;
                   7726: 	    } else {
                   7727: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7728: 					 $line,'incorrectID');
1.194     albertel 7729: 		return(1,$currentphase);
1.157     albertel 7730: 	    }
                   7731: 	}
                   7732:     }
                   7733: 
                   7734:     return (0,$currentphase+1);
                   7735: }
                   7736: 
1.423     albertel 7737: 
1.157     albertel 7738: sub scantron_get_correction {
1.691     raeburn  7739:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7740:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7741: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7742: #to show both the current line and the previous one and allow skipping
                   7743: #the previous one or the current one
                   7744: 
1.333     albertel 7745:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7746:         $r->print(
                   7747:             '<p class="LC_warning">'
                   7748:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7749:                 "<b>$error</b>",
                   7750:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7751:            ."</p> \n");
1.157     albertel 7752:     } else {
1.658     bisitz   7753:         $r->print(
                   7754:             '<p class="LC_warning">'
                   7755:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7756:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7757:            ."</p> \n");
                   7758:     }
                   7759:     my $message =
                   7760:         '<p>'
                   7761:        .&mt('The ID on the form is [_1]',
                   7762:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7763:        .'<br />'
1.665     raeburn  7764:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7765:             $$scan_record{'scantron.LastName'},
                   7766:             $$scan_record{'scantron.FirstName'})
                   7767:        .'</p>';
1.242     albertel 7768: 
1.157     albertel 7769:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7770:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7771:                            # Array populated for doublebubble or
                   7772:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7773:                            # to validate radio button checking   
                   7774: 
1.157     albertel 7775:     if ($error =~ /ID$/) {
1.186     albertel 7776: 	if ($error eq 'incorrectID') {
1.658     bisitz   7777:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7778: 		      "</p>\n");
1.157     albertel 7779: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7780:             $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 7781: 	}
1.242     albertel 7782: 	$r->print($message);
1.492     albertel 7783: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7784: 	$r->print("\n<ul><li> ");
                   7785: 	#FIXME it would be nice if this sent back the user ID and
                   7786: 	#could do partial userID matches
                   7787: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7788: 				       'scantron_username','scantron_domain'));
                   7789: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7790: 	$r->print("\n:\n".
1.257     albertel 7791: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7792: 
                   7793: 	$r->print('</li>');
1.186     albertel 7794:     } elsif ($error =~ /CODE$/) {
                   7795: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7796: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7797: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7798: 	    $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 7799: 	}
1.658     bisitz   7800: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7801: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7802:                  ."</p>\n");
1.242     albertel 7803: 	$r->print($message);
1.658     bisitz   7804: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7805: 	$r->print("\n<br /> ");
1.194     albertel 7806: 	my $i=0;
1.273     albertel 7807: 	if ($error eq 'incorrectCODE' 
                   7808: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7809: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7810: 	    if ($closest > 0) {
                   7811: 		foreach my $testcode (@{$closest}) {
                   7812: 		    my $checked='';
1.569     bisitz   7813: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7814: 		    $r->print("
                   7815:    <label>
1.569     bisitz   7816:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7817:        ".&mt("Use the similar CODE [_1] instead.",
                   7818: 	    "<b><tt>".$testcode."</tt></b>")."
                   7819:     </label>
                   7820:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7821: 		    $r->print("\n<br />");
                   7822: 		    $i++;
                   7823: 		}
1.194     albertel 7824: 	    }
                   7825: 	}
1.273     albertel 7826: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7827: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7828: 	    $r->print("
                   7829:     <label>
1.569     bisitz   7830:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7831:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7832: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7833:     </label>");
1.273     albertel 7834: 	    $r->print("\n<br />");
                   7835: 	}
1.194     albertel 7836: 
1.597     wenzelju 7837: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7838: function change_radio(field) {
1.190     albertel 7839:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7840:     var i;
                   7841:     for (i=0;i<slct.length;i++) {
                   7842:         if (slct[i].value==field) { slct[i].checked=true; }
                   7843:     }
                   7844: }
                   7845: ENDSCRIPT
1.187     albertel 7846: 	my $href="/adm/pickcode?".
1.359     www      7847: 	   "form=".&escape("scantronupload").
                   7848: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7849: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7850: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7851: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7852: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7853: 	    $r->print("
                   7854:     <label>
                   7855:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7856:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7857: 	     "<a target='_blank' href='$href'>","</a>")."
                   7858:     </label> 
1.558     bisitz   7859:     ".&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 7860: 	    $r->print("\n<br />");
                   7861: 	}
1.492     albertel 7862: 	$r->print("
                   7863:     <label>
                   7864:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7865:        ".&mt("Use [_1] as the CODE.",
                   7866: 	     "</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 7867: 	$r->print("\n<br /><br />");
1.157     albertel 7868:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7869: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7870: 
                   7871: 	# The form field scantron_questions is acutally a list of line numbers.
                   7872: 	# represented by this form so:
                   7873: 
1.691     raeburn  7874: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7875:                                                 $respnumlookup,$startline);
1.497     foxr     7876: 
1.157     albertel 7877: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7878: 		  $line_list.'" />');
1.242     albertel 7879: 	$r->print($message);
1.492     albertel 7880: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7881: 	foreach my $question (@{$arg}) {
1.503     raeburn  7882: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7883:                                                    $scan_record, $error,
                   7884:                                                    $randomorder,$randompick,
                   7885:                                                    $respnumlookup,$startline);
1.524     raeburn  7886:             push(@lines_to_correct,@linenums);
1.157     albertel 7887: 	}
1.503     raeburn  7888:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7889:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7890: 	$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 7891: 	$r->print($message);
1.492     albertel 7892: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7893: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7894: 
1.503     raeburn  7895: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7896: 	# a list of question numbers. Therefore:
                   7897: 	#
1.691     raeburn  7898: 
                   7899: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7900:                                                 $respnumlookup,$startline);
1.497     foxr     7901: 
1.157     albertel 7902: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7903: 		  $line_list.'" />');
1.157     albertel 7904: 	foreach my $question (@{$arg}) {
1.503     raeburn  7905: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7906:                                                    $scan_record, $error,
                   7907:                                                    $randomorder,$randompick,
                   7908:                                                    $respnumlookup,$startline);
1.524     raeburn  7909:             push(@lines_to_correct,@linenums);
1.157     albertel 7910: 	}
1.503     raeburn  7911:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7912:     } else {
                   7913: 	$r->print("\n<ul>");
                   7914:     }
                   7915:     $r->print("\n</li></ul>");
1.497     foxr     7916: }
                   7917: 
1.503     raeburn  7918: sub verify_bubbles_checked {
                   7919:     my (@ansnums) = @_;
                   7920:     my $ansnumstr = join('","',@ansnums);
                   7921:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7922:     &js_escape(\$warning);
1.597     wenzelju 7923:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7924: function verify_bubble_radio(form) {
                   7925:     var ansnumArray = new Array ("$ansnumstr");
                   7926:     var need_bubble_count = 0;
                   7927:     for (var i=0; i<ansnumArray.length; i++) {
                   7928:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7929:             var bubble_picked = 0; 
                   7930:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7931:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7932:                     bubble_picked = 1;
                   7933:                 }
                   7934:             }
                   7935:             if (bubble_picked == 0) {
                   7936:                 need_bubble_count ++;
                   7937:             }
                   7938:         }
                   7939:     }
                   7940:     if (need_bubble_count) {
                   7941:         alert("$warning");
                   7942:         return;
                   7943:     }
                   7944:     form.submit(); 
                   7945: }
                   7946: ENDSCRIPT
                   7947:     return $output;
                   7948: }
                   7949: 
1.497     foxr     7950: =pod
                   7951: 
                   7952: =item  questions_to_line_list
1.157     albertel 7953: 
1.497     foxr     7954: Converts a list of questions into a string of comma separated
                   7955: line numbers in the answer sheet used by the questions.  This is
                   7956: used to fill in the scantron_questions form field.
                   7957: 
                   7958:   Arguments:
                   7959:      questions    - Reference to an array of questions.
1.691     raeburn  7960:      randomorder  - True if randomorder in use.
                   7961:      randompick   - True if randompick in use.
                   7962:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7963:                      for current line to question number used for same question
                   7964:                      in "Master Seqence" (as seen by Course Coordinator).
                   7965:      startline    - Reference to hash where key is question number (0 is first)
                   7966:                     and key is number of first bubble line for current student
                   7967:                     or code-based randompick and/or randomorder.
1.693     raeburn  7968: 
1.497     foxr     7969: =cut
                   7970: 
                   7971: 
                   7972: sub questions_to_line_list {
1.691     raeburn  7973:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7974:     my @lines;
                   7975: 
1.503     raeburn  7976:     foreach my $item (@{$questions}) {
                   7977:         my $question = $item;
                   7978:         my ($first,$count,$last);
                   7979:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7980:             $question = $1;
                   7981:             my $subquestion = $2;
1.691     raeburn  7982:             my $responsenum = $question-1;
                   7983:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7984:                 $responsenum = $respnumlookup->{$question-1};
                   7985:                 if (ref($startline) eq 'HASH') {
                   7986:                     $first = $startline->{$question-1} + 1;
                   7987:                 }
                   7988:             } else {
                   7989:                 $first = $first_bubble_line{$responsenum} + 1;
                   7990:             }
                   7991:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7992:             my $subcount = 1;
                   7993:             while ($subcount<$subquestion) {
                   7994:                 $first += $subans[$subcount-1];
                   7995:                 $subcount ++;
                   7996:             }
                   7997:             $count = $subans[$subquestion-1];
                   7998:         } else {
1.691     raeburn  7999:             my $responsenum = $question-1;
                   8000:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8001:                 $responsenum = $respnumlookup->{$question-1};
                   8002:                 if (ref($startline) eq 'HASH') {
                   8003:                     $first = $startline->{$question-1} + 1;
                   8004:                 }
                   8005:             } else {
                   8006:                 $first = $first_bubble_line{$responsenum} + 1;
                   8007:             }
                   8008: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8009:         }
1.506     raeburn  8010:         $last = $first+$count-1;
1.503     raeburn  8011:         push(@lines, ($first..$last));
1.497     foxr     8012:     }
                   8013:     return join(',', @lines);
                   8014: }
                   8015: 
                   8016: =pod 
                   8017: 
                   8018: =item prompt_for_corrections
                   8019: 
                   8020: Prompts for a potentially multiline correction to the
                   8021: user's bubbling (factors out common code from scantron_get_correction
                   8022: for multi and missing bubble cases).
                   8023: 
                   8024:  Arguments:
                   8025:    $r           - Apache request object.
                   8026:    $question    - The question number to prompt for.
                   8027:    $scan_config - The scantron file configuration hash.
                   8028:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8029:    $error       - Type of error
1.691     raeburn  8030:    $randomorder - True if randomorder in use.
                   8031:    $randompick  - True if randompick in use.
                   8032:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8033:                     for current line to question number used for same question
                   8034:                     in "Master Seqence" (as seen by Course Coordinator).
                   8035:    $startline   - Reference to hash where key is question number (0 is first)
                   8036:                   and value is number of first bubble line for current student
                   8037:                   or code-based randompick and/or randomorder.
                   8038: 
1.497     foxr     8039: 
                   8040:  Implicit inputs:
                   8041:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8042:                                   Numbered from 0 (but question numbers are from
                   8043:                                   1.
                   8044:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8045:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8046:                                   type problems render as separate sub-questions, 
1.503     raeburn  8047:                                   in exam mode. This hash contains a 
                   8048:                                   comma-separated list of the lines per 
                   8049:                                   sub-question.
1.510     raeburn  8050:    %responsetype_per_response   - essayresponse, formularesponse,
                   8051:                                   stringresponse, imageresponse, reactionresponse,
                   8052:                                   and organicresponse type problem parts can have
1.503     raeburn  8053:                                   multiple lines per response if the weight
                   8054:                                   assigned exceeds 10.  In this case, only
                   8055:                                   one bubble per line is permitted, but more 
                   8056:                                   than one line might contain bubbles, e.g.
                   8057:                                   bubbling of: line 1 - J, line 2 - J, 
                   8058:                                   line 3 - B would assign 22 points.  
1.497     foxr     8059: 
                   8060: =cut
                   8061: 
                   8062: sub prompt_for_corrections {
1.691     raeburn  8063:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8064:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8065:     my ($current_line,$lines);
                   8066:     my @linenums;
                   8067:     my $questionnum = $question;
1.691     raeburn  8068:     my ($first,$responsenum);
1.503     raeburn  8069:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8070:         $question = $1;
                   8071:         my $subquestion = $2;
1.691     raeburn  8072:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8073:             $responsenum = $respnumlookup->{$question-1};
                   8074:             if (ref($startline) eq 'HASH') {
                   8075:                 $first = $startline->{$question-1};
                   8076:             }
                   8077:         } else {
                   8078:             $responsenum = $question-1;
1.714     raeburn  8079:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8080:         }
                   8081:         $current_line = $first + 1 ;
                   8082:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8083:         my $subcount = 1;
                   8084:         while ($subcount<$subquestion) {
                   8085:             $current_line += $subans[$subcount-1];
                   8086:             $subcount ++;
                   8087:         }
                   8088:         $lines = $subans[$subquestion-1];
                   8089:     } else {
1.691     raeburn  8090:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8091:             $responsenum = $respnumlookup->{$question-1};
                   8092:             if (ref($startline) eq 'HASH') { 
                   8093:                 $first = $startline->{$question-1};
                   8094:             }
                   8095:         } else {
                   8096:             $responsenum = $question-1;
                   8097:             $first = $first_bubble_line{$responsenum};
                   8098:         }
                   8099:         $current_line = $first + 1;
                   8100:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8101:     }
1.497     foxr     8102:     if ($lines > 1) {
1.503     raeburn  8103:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8104:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8105:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8106:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8107:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8108:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8109:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8110:             $r->print(
                   8111:                 &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)
                   8112:                .'<br /><br />'
                   8113:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8114:                .'<br />'
                   8115:                .&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.')
                   8116:                .'<br />'
                   8117:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8118:                .'<br /><br />'
                   8119:             );
1.503     raeburn  8120:         } else {
                   8121:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8122:         }
1.497     foxr     8123:     }
                   8124:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8125:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8126: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8127: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8128:         push(@linenums,$current_line);
1.497     foxr     8129: 	$current_line++;
                   8130:     }
                   8131:     if ($lines > 1) {
                   8132: 	$r->print("<hr /><br />");
                   8133:     }
1.503     raeburn  8134:     return @linenums;
1.157     albertel 8135: }
1.423     albertel 8136: 
                   8137: =pod
                   8138: 
                   8139: =item scantron_bubble_selector
                   8140:   
                   8141:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8142:    possibly showing the existing the selected bubbles if known
1.423     albertel 8143: 
                   8144:  Arguments:
                   8145:     $r           - Apache request object
                   8146:     $scan_config - hash from &get_scantron_config()
1.497     foxr     8147:     $line        - Number of the line being displayed.
1.503     raeburn  8148:     $questionnum - Question number (may include subquestion)
                   8149:     $error       - Type of error.
1.497     foxr     8150:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8151: 
                   8152: =cut
                   8153: 
1.157     albertel 8154: sub scantron_bubble_selector {
1.503     raeburn  8155:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8156:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8157: 
                   8158:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8159:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8160:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8161:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8162:             $max=$$scan_config{'BubblesPerRow'};
                   8163:             if (($scmode eq 'number') && ($max > 10)) {
                   8164:                 $max = 10;
                   8165:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8166:                 $max = 26;
                   8167:             }
                   8168:         } else {
                   8169:             $max = 10;
                   8170:         }
                   8171:     }
1.274     albertel 8172: 
1.157     albertel 8173:     my @alphabet=('A'..'Z');
1.503     raeburn  8174:     $r->print(&Apache::loncommon::start_data_table().
                   8175:               &Apache::loncommon::start_data_table_row());
                   8176:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8177:     for (my $i=0;$i<$max+1;$i++) {
                   8178: 	$r->print("\n".'<td align="center">');
                   8179: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8180: 	else { $r->print('&nbsp;'); }
                   8181: 	$r->print('</td>');
                   8182:     }
1.503     raeburn  8183:     $r->print(&Apache::loncommon::end_data_table_row().
                   8184:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8185:     for (my $i=0;$i<$max;$i++) {
                   8186: 	$r->print("\n".
                   8187: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8188: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8189:     }
1.503     raeburn  8190:     my $nobub_checked = ' ';
                   8191:     if ($error eq 'missingbubble') {
                   8192:         $nobub_checked = ' checked = "checked" ';
                   8193:     }
                   8194:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8195: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8196:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8197:               $line.'" value="'.$questionnum.'" /></td>');
                   8198:     $r->print(&Apache::loncommon::end_data_table_row().
                   8199:               &Apache::loncommon::end_data_table());
1.157     albertel 8200: }
                   8201: 
1.423     albertel 8202: =pod
                   8203: 
                   8204: =item num_matches
                   8205: 
1.424     albertel 8206:    Counts the number of characters that are the same between the two arguments.
                   8207: 
                   8208:  Arguments:
                   8209:    $orig - CODE from the scanline
                   8210:    $code - CODE to match against
                   8211: 
                   8212:  Returns:
                   8213:    $count - integer count of the number of same characters between the
                   8214:             two arguments
                   8215: 
1.423     albertel 8216: =cut
                   8217: 
1.194     albertel 8218: sub num_matches {
                   8219:     my ($orig,$code) = @_;
                   8220:     my @code=split(//,$code);
                   8221:     my @orig=split(//,$orig);
                   8222:     my $same=0;
                   8223:     for (my $i=0;$i<scalar(@code);$i++) {
                   8224: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8225:     }
                   8226:     return $same;
                   8227: }
                   8228: 
1.423     albertel 8229: =pod
                   8230: 
                   8231: =item scantron_get_closely_matching_CODEs
                   8232: 
1.424     albertel 8233:    Cycles through all CODEs and finds the set that has the greatest
                   8234:    number of same characters as the provided CODE
                   8235: 
                   8236:  Arguments:
                   8237:    $allcodes - hash ref returned by &get_codes()
                   8238:    $CODE     - CODE from the current scanline
                   8239: 
                   8240:  Returns:
                   8241:    2 element list
                   8242:     - first elements is number of how closely matching the best fit is 
                   8243:       (5 means best set has 5 matching characters)
                   8244:     - second element is an arrary ref containing the set of valid CODEs
                   8245:       that best fit the passed in CODE
                   8246: 
1.423     albertel 8247: =cut
                   8248: 
1.194     albertel 8249: sub scantron_get_closely_matching_CODEs {
                   8250:     my ($allcodes,$CODE)=@_;
                   8251:     my @CODEs;
                   8252:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8253: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8254:     }
                   8255: 
                   8256:     return ($#CODEs,$CODEs[-1]);
                   8257: }
                   8258: 
1.423     albertel 8259: =pod
                   8260: 
                   8261: =item get_codes
                   8262: 
1.424     albertel 8263:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8264:    set of remembered CODEs.
                   8265: 
                   8266:  Arguments:
                   8267:   $old_name - name of the set of remembered CODEs
                   8268:   $cdom     - domain of the course
                   8269:   $cnum     - internal course name
                   8270: 
                   8271:  Returns:
                   8272:   %allcodes - keys are the valid CODEs, values are all 1
                   8273: 
1.423     albertel 8274: =cut
                   8275: 
1.194     albertel 8276: sub get_codes {
1.280     foxr     8277:     my ($old_name, $cdom, $cnum) = @_;
                   8278:     if (!$old_name) {
                   8279: 	$old_name=$env{'form.scantron_CODElist'};
                   8280:     }
                   8281:     if (!$cdom) {
                   8282: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8283:     }
                   8284:     if (!$cnum) {
                   8285: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8286:     }
1.278     albertel 8287:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8288: 				    $cdom,$cnum);
                   8289:     my %allcodes;
                   8290:     if ($result{"type\0$old_name"} eq 'number') {
                   8291: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8292:     } else {
                   8293: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8294:     }
1.194     albertel 8295:     return %allcodes;
                   8296: }
                   8297: 
1.423     albertel 8298: =pod
                   8299: 
                   8300: =item scantron_validate_CODE
                   8301: 
1.424     albertel 8302:    Validates all scanlines in the selected file to not have any
                   8303:    invalid or underspecified CODEs and that none of the codes are
                   8304:    duplicated if this was requested.
                   8305: 
1.423     albertel 8306: =cut
                   8307: 
1.157     albertel 8308: sub scantron_validate_CODE {
                   8309:     my ($r,$currentphase) = @_;
1.257     albertel 8310:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8311:     if ($scantron_config{'CODElocation'} &&
                   8312: 	$scantron_config{'CODEstart'} &&
                   8313: 	$scantron_config{'CODElength'}) {
1.257     albertel 8314: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8315: 	    &FIXME_blow_up()
                   8316: 	}
                   8317:     } else {
                   8318: 	return (0,$currentphase+1);
                   8319:     }
                   8320:     
                   8321:     my %usedCODEs;
                   8322: 
1.194     albertel 8323:     my %allcodes=&get_codes();
1.186     albertel 8324: 
1.582     raeburn  8325:     my $nav_error;
1.649     raeburn  8326:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8327:     if ($nav_error) {
                   8328:         $r->print(&navmap_errormsg());
                   8329:         return(1,$currentphase);
                   8330:     }
1.447     foxr     8331: 
1.186     albertel 8332:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8333:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8334: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8335: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8336: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8337: 						 $scan_data);
                   8338: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8339: 	my $error=0;
1.224     albertel 8340: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8341: 	    &scantron_get_correction($r,$i,$scan_record,
                   8342: 				     \%scantron_config,
                   8343: 				     $line,'incorrectCODE',\%allcodes);
                   8344: 	    return(1,$currentphase);
                   8345: 	}
1.221     albertel 8346: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8347: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8348: 	    &scantron_get_correction($r,$i,$scan_record,
                   8349: 				     \%scantron_config,
1.194     albertel 8350: 				     $line,'incorrectCODE',\%allcodes);
                   8351: 	    return(1,$currentphase);
1.186     albertel 8352: 	}
1.214     albertel 8353: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8354: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8355: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8356: 	    &scantron_get_correction($r,$i,$scan_record,
                   8357: 				     \%scantron_config,
1.194     albertel 8358: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8359: 	    return(1,$currentphase);
1.186     albertel 8360: 	}
1.524     raeburn  8361: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8362:     }
1.157     albertel 8363:     return (0,$currentphase+1);
                   8364: }
                   8365: 
1.423     albertel 8366: =pod
                   8367: 
                   8368: =item scantron_validate_doublebubble
                   8369: 
1.424     albertel 8370:    Validates all scanlines in the selected file to not have any
                   8371:    bubble lines with multiple bubbles marked.
                   8372: 
1.423     albertel 8373: =cut
                   8374: 
1.157     albertel 8375: sub scantron_validate_doublebubble {
                   8376:     my ($r,$currentphase) = @_;
                   8377:     #get student info
                   8378:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8379:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8380:     my (undef,undef,$sequence)=
                   8381:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8382: 
                   8383:     #get scantron line setup
1.257     albertel 8384:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8385:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8386: 
                   8387:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8388:     unless (ref($navmap)) {
                   8389:         $r->print(&navmap_errormsg());
                   8390:         return(1,$currentphase);
                   8391:     }
                   8392:     my $map=$navmap->getResourceByUrl($sequence);
                   8393:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8394:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8395:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8396:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8397: 
1.583     raeburn  8398:     my $nav_error;
1.691     raeburn  8399:     if (ref($map)) {
                   8400:         $randomorder = $map->randomorder();
                   8401:         $randompick = $map->randompick();
                   8402:         if ($randomorder || $randompick) {
                   8403:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8404:             if ($nav_error) {
                   8405:                 $r->print(&navmap_errormsg());
                   8406:                 return(1,$currentphase);
                   8407:             }
                   8408:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8409:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8410:         }
                   8411:     } else {
                   8412:         $r->print(&navmap_errormsg());
                   8413:         return(1,$currentphase);
                   8414:     }
                   8415: 
1.649     raeburn  8416:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8417:     if ($nav_error) {
                   8418:         $r->print(&navmap_errormsg());
                   8419:         return(1,$currentphase);
                   8420:     }
1.447     foxr     8421: 
1.157     albertel 8422:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8423: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8424: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8425: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8426: 						 $scan_data,undef,\%idmap,$randomorder,
                   8427:                                                  $randompick,$sequence,\@master_seq,
                   8428:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8429:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8430: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8431: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8432: 				 'doublebubble',
1.691     raeburn  8433: 				 $$scan_record{'scantron.doubleerror'},
                   8434:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8435:     	return (1,$currentphase);
                   8436:     }
                   8437:     return (0,$currentphase+1);
                   8438: }
                   8439: 
1.423     albertel 8440: 
1.503     raeburn  8441: sub scantron_get_maxbubble {
1.649     raeburn  8442:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8443:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8444: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8445: 	&restore_bubble_lines();
1.257     albertel 8446: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8447:     }
1.330     albertel 8448: 
1.447     foxr     8449:     my (undef, undef, $sequence) =
1.257     albertel 8450: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8451: 
1.447     foxr     8452:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8453:     unless (ref($navmap)) {
                   8454:         if (ref($nav_error)) {
                   8455:             $$nav_error = 1;
                   8456:         }
1.591     raeburn  8457:         return;
1.582     raeburn  8458:     }
1.191     albertel 8459:     my $map=$navmap->getResourceByUrl($sequence);
                   8460:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8461:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8462: 
                   8463:     &Apache::lonxml::clear_problem_counter();
                   8464: 
1.557     raeburn  8465:     my $uname       = $env{'user.name'};
                   8466:     my $udom        = $env{'user.domain'};
1.435     foxr     8467:     my $cid         = $env{'request.course.id'};
                   8468:     my $total_lines = 0;
                   8469:     %bubble_lines_per_response = ();
1.447     foxr     8470:     %first_bubble_line         = ();
1.503     raeburn  8471:     %subdivided_bubble_lines   = ();
                   8472:     %responsetype_per_response = ();
1.691     raeburn  8473:     %masterseq_id_responsenum  = ();
1.554     raeburn  8474: 
1.447     foxr     8475:     my $response_number = 0;
                   8476:     my $bubble_line     = 0;
1.191     albertel 8477:     foreach my $resource (@resources) {
1.691     raeburn  8478:         my $resid = $resource->id(); 
1.672     raeburn  8479:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8480:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8481:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8482: 	    foreach my $part_id (@{$parts}) {
                   8483:                 my $lines;
                   8484: 
                   8485: 	        # TODO - make this a persistent hash not an array.
                   8486: 
                   8487:                 # optionresponse, matchresponse and rankresponse type items 
                   8488:                 # render as separate sub-questions in exam mode.
                   8489:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8490:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8491:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8492:                     my ($numbub,$numshown);
                   8493:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8494:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8495:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8496:                         }
                   8497:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8498:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8499:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8500:                         }
                   8501:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8502:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8503:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8504:                         }
                   8505:                     }
                   8506:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8507:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8508:                     }
1.649     raeburn  8509:                     my $bubbles_per_row =
                   8510:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8511:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8512:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8513:                         $inner_bubble_lines++;
                   8514:                     }
                   8515:                     for (my $i=0; $i<$numshown; $i++) {
                   8516:                         $subdivided_bubble_lines{$response_number} .= 
                   8517:                             $inner_bubble_lines.',';
                   8518:                     }
                   8519:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8520:                     $lines = $numshown * $inner_bubble_lines;
                   8521:                 } else {
                   8522:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8523:                 }
1.542     raeburn  8524: 
                   8525:                 $first_bubble_line{$response_number} = $bubble_line;
                   8526: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8527:                 $responsetype_per_response{$response_number} = 
                   8528:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8529:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8530: 	        $response_number++;
                   8531: 
                   8532: 	        $bubble_line +=  $lines;
                   8533: 	        $total_lines +=  $lines;
                   8534: 	    }
                   8535:         }
                   8536:     }
1.552     raeburn  8537:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8538: 
                   8539:     &save_bubble_lines();
                   8540:     $env{'form.scantron_maxbubble'} =
                   8541: 	$total_lines;
                   8542:     return $env{'form.scantron_maxbubble'};
                   8543: }
1.523     raeburn  8544: 
1.649     raeburn  8545: sub bubblesheet_bubbles_per_row {
                   8546:     my ($scantron_config) = @_;
                   8547:     my $bubbles_per_row;
                   8548:     if (ref($scantron_config) eq 'HASH') {
                   8549:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8550:     }
                   8551:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8552:         $bubbles_per_row = 10;
                   8553:     }
                   8554:     return $bubbles_per_row;
                   8555: }
                   8556: 
1.157     albertel 8557: sub scantron_validate_missingbubbles {
                   8558:     my ($r,$currentphase) = @_;
                   8559:     #get student info
                   8560:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8561:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8562:     my (undef,undef,$sequence)=
                   8563:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8564: 
                   8565:     #get scantron line setup
1.257     albertel 8566:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8567:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8568: 
                   8569:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8570:     unless (ref($navmap)) {
                   8571:         $r->print(&navmap_errormsg());
                   8572:         return(1,$currentphase);
                   8573:     }
                   8574: 
                   8575:     my $map=$navmap->getResourceByUrl($sequence);
                   8576:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8577:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8578:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8579:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8580: 
1.582     raeburn  8581:     my $nav_error;
1.691     raeburn  8582:     if (ref($map)) {
                   8583:         $randomorder = $map->randomorder();
                   8584:         $randompick = $map->randompick();
                   8585:         if ($randomorder || $randompick) {
                   8586:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8587:             if ($nav_error) {
                   8588:                 $r->print(&navmap_errormsg());
                   8589:                 return(1,$currentphase);
                   8590:             }
                   8591:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8592:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8593:         }
                   8594:     } else {
                   8595:         $r->print(&navmap_errormsg());
                   8596:         return(1,$currentphase);
                   8597:     }
                   8598: 
                   8599: 
1.649     raeburn  8600:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8601:     if ($nav_error) {
1.691     raeburn  8602:         $r->print(&navmap_errormsg());
1.693     raeburn  8603:         return(1,$currentphase);
1.582     raeburn  8604:     }
1.691     raeburn  8605: 
1.157     albertel 8606:     if (!$max_bubble) { $max_bubble=2**31; }
                   8607:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8608: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8609: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8610: 	my $scan_record =
                   8611:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8612: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8613:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8614:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8615: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8616: 	my @to_correct;
1.470     foxr     8617: 	
                   8618: 	# Probably here's where the error is...
                   8619: 
1.157     albertel 8620: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8621:             my $lastbubble;
                   8622:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8623:                my $question = $1;
                   8624:                my $subquestion = $2;
1.691     raeburn  8625:                my ($first,$responsenum);
                   8626:                if ($randomorder || $randompick) {
                   8627:                    $responsenum = $respnumlookup{$question-1};
                   8628:                    $first = $startline{$question-1};
                   8629:                } else {
                   8630:                    $responsenum = $question-1; 
                   8631:                    $first = $first_bubble_line{$responsenum};
                   8632:                }
                   8633:                if (!defined($first)) { next; }
                   8634:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8635:                my $subcount = 1;
                   8636:                while ($subcount<$subquestion) {
                   8637:                    $first += $subans[$subcount-1];
                   8638:                    $subcount ++;
                   8639:                }
                   8640:                my $count = $subans[$subquestion-1];
                   8641:                $lastbubble = $first + $count;
                   8642:             } else {
1.691     raeburn  8643:                my ($first,$responsenum);
                   8644:                if ($randomorder || $randompick) {
                   8645:                    $responsenum = $respnumlookup{$missing-1};
                   8646:                    $first = $startline{$missing-1};
                   8647:                } else {
                   8648:                    $responsenum = $missing-1;
                   8649:                    $first = $first_bubble_line{$responsenum};
                   8650:                }
                   8651:                if (!defined($first)) { next; }
                   8652:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8653:             }
                   8654:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8655: 	    push(@to_correct,$missing);
                   8656: 	}
                   8657: 	if (@to_correct) {
                   8658: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8659: 				     $line,'missingbubble',\@to_correct,
                   8660:                                      $randomorder,$randompick,\%respnumlookup,
                   8661:                                      \%startline);
1.157     albertel 8662: 	    return (1,$currentphase);
                   8663: 	}
                   8664: 
                   8665:     }
                   8666:     return (0,$currentphase+1);
                   8667: }
                   8668: 
1.663     raeburn  8669: sub hand_bubble_option {
                   8670:     my (undef, undef, $sequence) =
                   8671:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8672:     return if ($sequence eq '');
                   8673:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8674:     unless (ref($navmap)) {
                   8675:         return;
                   8676:     }
                   8677:     my $needs_hand_bubbles;
                   8678:     my $map=$navmap->getResourceByUrl($sequence);
                   8679:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8680:     foreach my $res (@resources) {
                   8681:         if (ref($res)) {
                   8682:             if ($res->is_problem()) {
                   8683:                 my $partlist = $res->parts();
                   8684:                 foreach my $part (@{ $partlist }) {
                   8685:                     my @types = $res->responseType($part);
                   8686:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8687:                         $needs_hand_bubbles = 1;
                   8688:                         last;
                   8689:                     }
                   8690:                 }
                   8691:             }
                   8692:         }
                   8693:     }
                   8694:     if ($needs_hand_bubbles) {
                   8695:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8696:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8697:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8698:                &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 />').
                   8699:                '<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  8700:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8701:     }
                   8702:     return;
                   8703: }
1.423     albertel 8704: 
1.82      albertel 8705: sub scantron_process_students {
1.608     www      8706:     my ($r,$symb) = @_;
1.513     foxr     8707: 
1.257     albertel 8708:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8709:     if (!$symb) {
                   8710: 	return '';
                   8711:     }
1.324     albertel 8712:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8713: 
1.257     albertel 8714:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8715:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8716:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8717:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8718:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8719:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8720:     unless (ref($navmap)) {
                   8721:         $r->print(&navmap_errormsg());
                   8722:         return '';
1.691     raeburn  8723:     }
1.83      albertel 8724:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8725:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8726:         %grader_randomlists_by_symb);
1.677     raeburn  8727:     if (ref($map)) {
                   8728:         $randomorder = $map->randomorder();
1.689     raeburn  8729:         $randompick = $map->randompick();
1.691     raeburn  8730:     } else {
                   8731:         $r->print(&navmap_errormsg());
                   8732:         return '';
1.677     raeburn  8733:     }
1.691     raeburn  8734:     my $nav_error;
1.83      albertel 8735:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8736:     if ($randomorder || $randompick) {
                   8737:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8738:         if ($nav_error) {
                   8739:             $r->print(&navmap_errormsg());
                   8740:             return '';
                   8741:         }
                   8742:     }
1.557     raeburn  8743:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8744:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8745: 
1.554     raeburn  8746:     my ($uname,$udom);
1.82      albertel 8747:     my $result= <<SCANTRONFORM;
1.81      albertel 8748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8749:   <input type="hidden" name="command" value="scantron_configphase" />
                   8750:   $default_form_data
                   8751: SCANTRONFORM
1.82      albertel 8752:     $r->print($result);
                   8753: 
                   8754:     my @delayqueue;
1.542     raeburn  8755:     my (%completedstudents,%scandata);
1.140     albertel 8756:     
1.520     www      8757:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8758:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8759:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8760:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8761:     $r->print('<br />');
1.140     albertel 8762:     my $start=&Time::HiRes::time();
1.158     albertel 8763:     my $i=-1;
1.542     raeburn  8764:     my $started;
1.447     foxr     8765: 
1.649     raeburn  8766:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8767:     if ($nav_error) {
                   8768:         $r->print(&navmap_errormsg());
                   8769:         return '';
                   8770:     }
                   8771: 
1.513     foxr     8772:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8773:     # the user and return.
                   8774: 
                   8775:     if ($ssi_error) {
                   8776: 	$r->print("</form>");
                   8777: 	&ssi_print_error($r);
1.520     www      8778:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8779: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8780:     }
1.447     foxr     8781: 
1.542     raeburn  8782:     my %lettdig = &letter_to_digits();
                   8783:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8784:     my %orderedforcode;
1.542     raeburn  8785: 
1.157     albertel 8786:     while ($i<$scanlines->{'count'}) {
                   8787:  	($uname,$udom)=('','');
                   8788:  	$i++;
1.200     albertel 8789:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8790:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8791: 	if ($started) {
1.667     www      8792: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8793: 	}
                   8794: 	$started=1;
1.691     raeburn  8795:         my %respnumlookup = ();
                   8796:         my %startline = ();
                   8797:         my $total;
1.157     albertel 8798:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8799:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8800:                                                  $randompick,$sequence,\@master_seq,
                   8801:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8802:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8803:                                                  \$total);
1.157     albertel 8804:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8805:  					      \%idmap,$i)) {
                   8806:   	    &scantron_add_delay(\@delayqueue,$line,
                   8807:  				'Unable to find a student that matches',1);
                   8808:  	    next;
                   8809:   	}
                   8810:  	if (exists $completedstudents{$uname}) {
                   8811:  	    &scantron_add_delay(\@delayqueue,$line,
                   8812:  				'Student '.$uname.' has multiple sheets',2);
                   8813:  	    next;
                   8814:  	}
1.677     raeburn  8815:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8816:         my $user = $uname.':'.$usec;
1.157     albertel 8817:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8818: 
1.677     raeburn  8819:         my $scancode;
                   8820:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8821:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8822:             $scancode = $scan_record->{'scantron.CODE'};
                   8823:         } else {
                   8824:             $scancode = '';
                   8825:         }
                   8826: 
                   8827:         my @mapresources = @resources;
1.689     raeburn  8828:         if ($randomorder || $randompick) {
1.678     raeburn  8829:             @mapresources = 
1.691     raeburn  8830:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8831:                              \%orderedforcode);
1.677     raeburn  8832:         }
1.586     raeburn  8833:         my (%partids_by_symb,$res_error);
1.677     raeburn  8834:         foreach my $resource (@mapresources) {
1.586     raeburn  8835:             my $ressymb;
                   8836:             if (ref($resource)) {
                   8837:                 $ressymb = $resource->symb();
                   8838:             } else {
                   8839:                 $res_error = 1;
                   8840:                 last;
                   8841:             }
1.557     raeburn  8842:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8843:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8844:                 my $currcode;
                   8845:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8846:                     $currcode = $scancode;
                   8847:                 }
1.557     raeburn  8848:                 my ($analysis,$parts) =
1.672     raeburn  8849:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8850:                                               $uname,$udom,undef,$bubbles_per_row,
                   8851:                                               $currcode);
1.557     raeburn  8852:                 $partids_by_symb{$ressymb} = $parts;
                   8853:             } else {
                   8854:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8855:             }
1.554     raeburn  8856:         }
                   8857: 
1.586     raeburn  8858:         if ($res_error) {
                   8859:             &scantron_add_delay(\@delayqueue,$line,
                   8860:                                 'An error occurred while grading student '.$uname,2);
                   8861:             next;
                   8862:         }
                   8863: 
1.330     albertel 8864: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8865:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8866: 
                   8867: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8868: 	    &scantron_putfile($scanlines,$scan_data);
                   8869: 	}
1.161     albertel 8870: 	
1.542     raeburn  8871:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8872:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8873:                                    $bubbles_per_row,$randomorder,$randompick,
                   8874:                                    \%respnumlookup,\%startline) 
                   8875:             eq 'ssi_error') {
1.542     raeburn  8876:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8877:             $r->print("</form>");
                   8878:             &ssi_print_error($r);
                   8879:             &Apache::lonnet::remove_lock($lock);
                   8880:             return '';      # Why return ''?  Beats me.
                   8881:         }
1.513     foxr     8882: 
1.692     raeburn  8883:         if (($scancode) && ($randomorder || $randompick)) {
                   8884:             my $parmresult =
                   8885:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8886:                                                        '0_examcode',2,$scancode,
                   8887:                                                        'string_examcode',$uname,
                   8888:                                                        $udom);
                   8889:         }
1.140     albertel 8890: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8891:         if ($env{'form.verifyrecord'}) {
                   8892:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8893:             if ($randompick) {
                   8894:                 if ($total) {
                   8895:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8896:                 }
                   8897:             }
                   8898: 
1.542     raeburn  8899:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8900:             chomp($studentdata);
                   8901:             $studentdata =~ s/\r$//;
                   8902:             my $studentrecord = '';
                   8903:             my $counter = -1;
1.677     raeburn  8904:             foreach my $resource (@mapresources) {
1.554     raeburn  8905:                 my $ressymb = $resource->symb();
1.542     raeburn  8906:                 ($counter,my $recording) =
                   8907:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8908:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8909:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8910:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8911:                 $studentrecord .= $recording;
                   8912:             }
                   8913:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8914:                 &Apache::lonxml::clear_problem_counter();
                   8915:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8916:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8917:                                            $bubbles_per_row,$randomorder,$randompick,
                   8918:                                            \%respnumlookup,\%startline) 
                   8919:                     eq 'ssi_error') {
1.554     raeburn  8920:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8921:                     $r->print("</form>");
                   8922:                     &ssi_print_error($r);
                   8923:                     &Apache::lonnet::remove_lock($lock);
                   8924:                     delete($completedstudents{$uname});
                   8925:                     return '';
                   8926:                 }
1.542     raeburn  8927:                 $counter = -1;
                   8928:                 $studentrecord = '';
1.677     raeburn  8929:                 foreach my $resource (@mapresources) {
1.554     raeburn  8930:                     my $ressymb = $resource->symb();
1.542     raeburn  8931:                     ($counter,my $recording) =
                   8932:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8933:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8934:                                                  \%scantron_config,\%lettdig,$numletts,
                   8935:                                                  $randomorder,$randompick,\%respnumlookup,
                   8936:                                                  \%startline);
1.542     raeburn  8937:                     $studentrecord .= $recording;
                   8938:                 }
                   8939:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8940:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8941:                     if ($scancode eq '') {
1.658     bisitz   8942:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8943:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8944:                     } else {
1.658     bisitz   8945:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8946:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8947:                     }
                   8948:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8949:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8950:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8951:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8952:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8953:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8954:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8955:                               &Apache::loncommon::end_data_table_row().
                   8956:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8957:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8958:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8959:                               &Apache::loncommon::end_data_table_row().
                   8960:                               &Apache::loncommon::end_data_table().'</p>');
                   8961:                 } else {
                   8962:                     $r->print('<br /><span class="LC_warning">'.
                   8963:                              &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 />'.
                   8964:                              &mt("As a consequence, this user's submission history records two tries.").
                   8965:                                  '</span><br />');
                   8966:                 }
                   8967:             }
                   8968:         }
1.543     raeburn  8969:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8970:     } continue {
1.330     albertel 8971: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8972: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8973:     }
1.140     albertel 8974:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8975:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8976: #    my $lasttime = &Time::HiRes::time()-$start;
                   8977: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8978: 
1.200     albertel 8979:     $r->print("</form>");
1.157     albertel 8980:     return '';
1.75      albertel 8981: }
1.157     albertel 8982: 
1.557     raeburn  8983: sub graders_resources_pass {
1.649     raeburn  8984:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8985:         $bubbles_per_row) = @_;
1.557     raeburn  8986:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8987:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8988:         foreach my $resource (@{$resources}) {
                   8989:             my $ressymb = $resource->symb();
                   8990:             my ($analysis,$parts) =
                   8991:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8992:                                           $env{'user.name'},$env{'user.domain'},
                   8993:                                           1,$bubbles_per_row);
1.557     raeburn  8994:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8995:             if (ref($analysis) eq 'HASH') {
                   8996:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8997:                     $grader_randomlists_by_symb->{$ressymb} =
                   8998:                         $analysis->{'parts_withrandomlist'};
                   8999:                 }
                   9000:             }
                   9001:         }
                   9002:     }
                   9003:     return;
                   9004: }
                   9005: 
1.678     raeburn  9006: =pod
                   9007: 
                   9008: =item users_order
                   9009: 
                   9010:   Returns array of resources in current map, ordered based on either CODE,
                   9011:   if this is a CODEd exam, or based on student's identity if this is a 
                   9012:   "NAMEd" exam.
                   9013: 
1.691     raeburn  9014:   Should be used when randomorder and/or randompick applied when the 
                   9015:   corresponding exam was printed, prior to students completing bubblesheets 
                   9016:   for the version of the exam the student received.
1.678     raeburn  9017: 
                   9018: =cut
                   9019: 
                   9020: sub users_order  {
1.691     raeburn  9021:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9022:     my @mapresources;
1.691     raeburn  9023:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9024:         return @mapresources;
1.691     raeburn  9025:     }
                   9026:     if ($scancode) {
                   9027:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9028:             @mapresources = @{$orderedforcode->{$scancode}};
                   9029:         } else {
                   9030:             $env{'form.CODE'} = $scancode;
                   9031:             my $actual_seq =
                   9032:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9033:                                                                $master_seq,
                   9034:                                                                $user,$scancode,1);
                   9035:             if (ref($actual_seq) eq 'ARRAY') {
                   9036:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9037:                 if (ref($orderedforcode) eq 'HASH') {
                   9038:                     if (@mapresources > 0) { 
                   9039:                         $orderedforcode->{$scancode} = \@mapresources;
                   9040:                     }
                   9041:                 }
                   9042:             }
                   9043:             delete($env{'form.CODE'});
1.678     raeburn  9044:         }
                   9045:     } else {
                   9046:         my $actual_seq =
                   9047:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9048:                                                            $master_seq,
1.688     raeburn  9049:                                                            $user,undef,1);
1.678     raeburn  9050:         if (ref($actual_seq) eq 'ARRAY') {
                   9051:             @mapresources = 
                   9052:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9053:         }
1.691     raeburn  9054:     }
                   9055:     return @mapresources;
1.678     raeburn  9056: }
                   9057: 
1.542     raeburn  9058: sub grade_student_bubbles {
1.691     raeburn  9059:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9060:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9061:     my $uselookup = 0;
                   9062:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9063:         (ref($startline) eq 'HASH')) {
                   9064:         $uselookup = 1;
                   9065:     }
                   9066: 
1.554     raeburn  9067:     if (ref($resources) eq 'ARRAY') {
                   9068:         my $count = 0;
                   9069:         foreach my $resource (@{$resources}) {
                   9070:             my $ressymb = $resource->symb();
                   9071:             my %form = ('submitted'      => 'scantron',
                   9072:                         'grade_target'   => 'grade',
                   9073:                         'grade_username' => $uname,
                   9074:                         'grade_domain'   => $udom,
                   9075:                         'grade_courseid' => $env{'request.course.id'},
                   9076:                         'grade_symb'     => $ressymb,
                   9077:                         'CODE'           => $scancode
                   9078:                        );
1.649     raeburn  9079:             if ($bubbles_per_row ne '') {
                   9080:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9081:             }
1.663     raeburn  9082:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9083:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9084:             }
1.554     raeburn  9085:             if (ref($parts) eq 'HASH') {
                   9086:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9087:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9088:                         if ($uselookup) {
                   9089:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9090:                         } else {
                   9091:                             $form{'scantron_questnum_start.'.$part} =
                   9092:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9093:                         }
1.554     raeburn  9094:                         $count++;
                   9095:                     }
                   9096:                 }
                   9097:             }
                   9098:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9099:             return 'ssi_error' if ($ssi_error);
                   9100:             last if (&Apache::loncommon::connection_aborted($r));
                   9101:         }
1.542     raeburn  9102:     }
                   9103:     return;
                   9104: }
                   9105: 
1.157     albertel 9106: sub scantron_upload_scantron_data {
1.608     www      9107:     my ($r,$symb)=@_;
1.565     raeburn  9108:     my $dom = $env{'request.role.domain'};
                   9109:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9110:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9111:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9112: 							  'domainid',
1.565     raeburn  9113: 							  'coursename',$dom);
                   9114:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9115:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9116:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9117:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9118:     &js_escape(\$nofile_alert);
1.579     raeburn  9119:     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  9120:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9121:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9122:     function checkUpload(formname) {
                   9123: 	if (formname.upfile.value == "") {
1.579     raeburn  9124: 	    alert("'.$nofile_alert.'");
1.157     albertel 9125: 	    return false;
                   9126: 	}
1.565     raeburn  9127:         if (formname.courseid.value == "") {
1.579     raeburn  9128:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9129:             return false;
                   9130:         }
1.157     albertel 9131: 	formname.submit();
                   9132:     }
1.565     raeburn  9133: 
                   9134:     function ToSyllabus() {
                   9135:         var cdom = '."'$dom'".';
                   9136:         var cnum = document.rules.courseid.value;
                   9137:         if (cdom == "" || cdom == null) {
                   9138:             return;
                   9139:         }
                   9140:         if (cnum == "" || cnum == null) {
                   9141:            return;
                   9142:         }
                   9143:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9144:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9145:         return;
                   9146:     }
                   9147: 
1.597     wenzelju 9148: '));
                   9149:     $r->print('
1.648     bisitz   9150: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9151: 
1.492     albertel 9152: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9153: '.$default_form_data.
                   9154:   &Apache::lonhtmlcommon::start_pick_box().
                   9155:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9156:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9157:   &Apache::lonhtmlcommon::row_closure().
                   9158:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9159:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9160:   &Apache::lonhtmlcommon::row_closure().
                   9161:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9162:   '<input name="domainid" type="hidden" />'.$domdesc.
                   9163:   &Apache::lonhtmlcommon::row_closure().
                   9164:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9165:   '<input type="file" name="upfile" size="50" />'.
                   9166:   &Apache::lonhtmlcommon::row_closure(1).
                   9167:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9168: 
1.492     albertel 9169: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9170: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9171: </form>
1.492     albertel 9172: ');
1.157     albertel 9173:     return '';
                   9174: }
                   9175: 
1.423     albertel 9176: 
1.157     albertel 9177: sub scantron_upload_scantron_data_save {
1.608     www      9178:     my($r,$symb)=@_;
1.182     albertel 9179:     my $doanotherupload=
                   9180: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9181: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9182: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9183: 	'</form>'."\n";
1.257     albertel 9184:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9185: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9186: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9187: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9188: 	unless ($symb) {
1.182     albertel 9189: 	    $r->print($doanotherupload);
                   9190: 	}
1.162     albertel 9191: 	return '';
                   9192:     }
1.257     albertel 9193:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9194:     my $uploadedfile;
1.710     bisitz   9195:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9196:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9197:         $r->print(
                   9198:             &Apache::lonhtmlcommon::confirm_success(
                   9199:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9200:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9201:     } else {
1.568     raeburn  9202:         my $result = 
                   9203:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   9204:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9205:         if ($result =~ m{^/uploaded/}) {
                   9206:             $r->print(
                   9207:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9208:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9209:                         (length($env{'form.upfile'})-1),
                   9210:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9211:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9212:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9213:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   9214:         } else {
                   9215:             $r->print(
                   9216:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9217:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9218:                           $result,
1.568     raeburn  9219: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9220: 	}
                   9221:     }
1.174     albertel 9222:     if ($symb) {
1.612     www      9223: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9224:     } else {
1.182     albertel 9225: 	$r->print($doanotherupload);
1.174     albertel 9226:     }
1.157     albertel 9227:     return '';
                   9228: }
                   9229: 
1.567     raeburn  9230: sub validate_uploaded_scantron_file {
                   9231:     my ($cdom,$cname,$fname) = @_;
                   9232:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9233:     my @lines;
                   9234:     if ($scanlines ne '-1') {
                   9235:         @lines=split("\n",$scanlines,-1);
                   9236:     }
                   9237:     my $output;
                   9238:     if (@lines) {
                   9239:         my (%counts,$max_match_format);
1.710     bisitz   9240:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9241:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9242:         my %idmap = &username_to_idmap($classlist);
                   9243:         foreach my $key (keys(%idmap)) {
                   9244:             my $lckey = lc($key);
                   9245:             $idmap{$lckey} = $idmap{$key};
                   9246:         }
                   9247:         my %unique_formats;
                   9248:         my @formatlines = &get_scantronformat_file();
                   9249:         foreach my $line (@formatlines) {
                   9250:             chomp($line);
                   9251:             my @config = split(/:/,$line);
                   9252:             my $idstart = $config[5];
                   9253:             my $idlength = $config[6];
                   9254:             if (($idstart ne '') && ($idlength > 0)) {
                   9255:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9256:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9257:                 } else {
                   9258:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9259:                 }
                   9260:             }
                   9261:         }
                   9262:         foreach my $key (keys(%unique_formats)) {
                   9263:             my ($idstart,$idlength) = split(':',$key);
                   9264:             %{$counts{$key}} = (
                   9265:                                'found'   => 0,
                   9266:                                'total'   => 0,
                   9267:                               );
                   9268:             foreach my $line (@lines) {
                   9269:                 next if ($line =~ /^#/);
                   9270:                 next if ($line =~ /^[\s\cz]*$/);
                   9271:                 my $id = substr($line,$idstart-1,$idlength);
                   9272:                 $id = lc($id);
                   9273:                 if (exists($idmap{$id})) {
                   9274:                     $counts{$key}{'found'} ++;
                   9275:                 }
                   9276:                 $counts{$key}{'total'} ++;
                   9277:             }
                   9278:             if ($counts{$key}{'total'}) {
                   9279:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9280:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9281:                     $max_match_pct = $percent_match;
                   9282:                     $max_match_format = $key;
1.710     bisitz   9283:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9284:                     $max_match_count = $counts{$key}{'total'};
                   9285:                 }
                   9286:             }
                   9287:         }
                   9288:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9289:             my $format_descs;
                   9290:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9291:             for (my $i=0; $i<$numwithformat; $i++) {
                   9292:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9293:                 if ($i<$numwithformat-2) {
                   9294:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9295:                 } elsif ($i==$numwithformat-2) {
                   9296:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9297:                 } elsif ($i==$numwithformat-1) {
                   9298:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9299:                 }
                   9300:             }
                   9301:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9302:             $output .= '<br />';
                   9303:             if ($found_match_count == $max_match_count) {
                   9304:                 # 100% matching entries
                   9305:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9306:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9307:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9308:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9309:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9310:                     ' in the file (for the format defined for [_3]).',
                   9311:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9312:             } else {
                   9313:                 # Not all entries matching? -> Show warning and additional info
                   9314:                 $output .=
                   9315:                     &Apache::lonhtmlcommon::confirm_success(
                   9316:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9317:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9318:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9319:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9320:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9321:                         ' in the file (for the format defined for [_3]).',
                   9322:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9323:                     '<p class="LC_info">'.
                   9324:                     &mt('A low percentage of matches results from one of the following:').
                   9325:                     '</p><ul>'.
                   9326:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9327:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9328:                                '<i>'.$cdom.'</i>').'</li>'.
                   9329:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9330:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9331:                     '</ul>';
                   9332:             }
1.567     raeburn  9333:         }
                   9334:     } else {
1.710     bisitz   9335:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9336:     }
                   9337:     return $output;
                   9338: }
                   9339: 
1.202     albertel 9340: sub valid_file {
                   9341:     my ($requested_file)=@_;
                   9342:     foreach my $filename (sort(&scantron_filenames())) {
                   9343: 	if ($requested_file eq $filename) { return 1; }
                   9344:     }
                   9345:     return 0;
                   9346: }
                   9347: 
                   9348: sub scantron_download_scantron_data {
1.608     www      9349:     my ($r,$symb)=@_;
                   9350:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9351:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9352:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9353:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9354:     if (! &valid_file($file)) {
1.492     albertel 9355: 	$r->print('
1.202     albertel 9356: 	<p>
1.686     bisitz   9357: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9358:         </p>
1.492     albertel 9359: ');
1.202     albertel 9360: 	return;
                   9361:     }
                   9362:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9363:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9364:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9365:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9366:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9367:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9368:     $r->print('
1.202     albertel 9369:     <p>
1.723     raeburn  9370: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9371: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9372:     </p>
                   9373:     <p>
1.492     albertel 9374: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9375: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9376:     </p>
                   9377:     <p>
1.492     albertel 9378: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9379: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9380:     </p>
1.492     albertel 9381: ');
1.202     albertel 9382:     return '';
                   9383: }
1.157     albertel 9384: 
1.523     raeburn  9385: sub checkscantron_results {
1.608     www      9386:     my ($r,$symb) = @_;
1.523     raeburn  9387:     if (!$symb) {return '';}
                   9388:     my $cid = $env{'request.course.id'};
1.542     raeburn  9389:     my %lettdig = &letter_to_digits();
1.523     raeburn  9390:     my $numletts = scalar(keys(%lettdig));
                   9391:     my $cnum = $env{'course.'.$cid.'.num'};
                   9392:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9393:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9394:     my %record;
                   9395:     my %scantron_config =
                   9396:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9397:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9398:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9399:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9400:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9401:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9402:     unless (ref($navmap)) {
                   9403:         $r->print(&navmap_errormsg());
                   9404:         return '';
                   9405:     }
1.523     raeburn  9406:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9407:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9408:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9409:     if (ref($map)) { 
                   9410:         $randomorder=$map->randomorder();
1.689     raeburn  9411:         $randompick=$map->randompick();
1.677     raeburn  9412:     }
1.557     raeburn  9413:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9414:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9415:     if ($nav_error) {
                   9416:         $r->print(&navmap_errormsg());
                   9417:         return '';
1.678     raeburn  9418:     }
1.673     raeburn  9419:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9420:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9421:     my ($uname,$udom);
1.523     raeburn  9422:     my (%scandata,%lastname,%bylast);
                   9423:     $r->print('
                   9424: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9425: 
                   9426:     my @delayqueue;
                   9427:     my %completedstudents;
                   9428: 
1.691     raeburn  9429:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9430:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9431:     my ($username,$domain,$started);
1.649     raeburn  9432:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9433:     if ($nav_error) {
                   9434:         $r->print(&navmap_errormsg());
                   9435:         return '';
                   9436:     }
1.523     raeburn  9437: 
1.667     www      9438:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9439:     my $start=&Time::HiRes::time();
                   9440:     my $i=-1;
                   9441: 
                   9442:     while ($i<$scanlines->{'count'}) {
                   9443:         ($username,$domain,$uname)=('','','');
                   9444:         $i++;
                   9445:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9446:         if ($line=~/^[\s\cz]*$/) { next; }
                   9447:         if ($started) {
1.667     www      9448:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9449:         }
                   9450:         $started=1;
                   9451:         my $scan_record=
                   9452:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9453:                                                      $scan_data);
1.693     raeburn  9454:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9455:                                               \%idmap,$i)) {
1.523     raeburn  9456:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9457:                                 'Unable to find a student that matches',1);
                   9458:             next;
                   9459:         }
                   9460:         if (exists $completedstudents{$uname}) {
                   9461:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9462:                                 'Student '.$uname.' has multiple sheets',2);
                   9463:             next;
                   9464:         }
                   9465:         my $pid = $scan_record->{'scantron.ID'};
                   9466:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9467:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9468:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9469:         my $user = $uname.':'.$usec;
1.523     raeburn  9470:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9471: 
1.678     raeburn  9472:         my $scancode;
1.677     raeburn  9473:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9474:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9475:             $scancode = $scan_record->{'scantron.CODE'};
                   9476:         } else {
                   9477:             $scancode = '';
                   9478:         }
                   9479: 
                   9480:         my @mapresources = @resources;
1.691     raeburn  9481:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9482:         my %respnumlookup=();
                   9483:         my %startline=();
1.689     raeburn  9484:         if ($randomorder || $randompick) {
1.678     raeburn  9485:             @mapresources =
1.691     raeburn  9486:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9487:                              \%orderedforcode);
                   9488:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9489:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9490:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9491:                                              \%respnumlookup,\%startline);
                   9492:             if ($randompick && $total) {
                   9493:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9494:             }
1.677     raeburn  9495:         }
1.691     raeburn  9496:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9497:         chomp($scandata{$pid});
                   9498:         $scandata{$pid} =~ s/\r$//;
                   9499: 
1.523     raeburn  9500:         my $counter = -1;
1.677     raeburn  9501:         foreach my $resource (@mapresources) {
1.557     raeburn  9502:             my $parts;
1.554     raeburn  9503:             my $ressymb = $resource->symb();
1.557     raeburn  9504:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9505:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9506:                 my $currcode;
                   9507:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9508:                     $currcode = $scancode;
                   9509:                 }
1.557     raeburn  9510:                 (my $analysis,$parts) =
1.672     raeburn  9511:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9512:                                               $username,$domain,undef,
1.741     raeburn  9513:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9514:             } else {
                   9515:                 $parts = $grader_partids_by_symb{$ressymb};
                   9516:             }
1.542     raeburn  9517:             ($counter,my $recording) =
                   9518:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9519:                                          $scandata{$pid},$parts,
1.691     raeburn  9520:                                          \%scantron_config,\%lettdig,$numletts,
                   9521:                                          $randomorder,$randompick,
                   9522:                                          \%respnumlookup,\%startline);
1.542     raeburn  9523:             $record{$pid} .= $recording;
1.523     raeburn  9524:         }
                   9525:     }
                   9526:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9527:     $r->print('<br />');
                   9528:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9529:     $passed = 0;
                   9530:     $failed = 0;
                   9531:     $numstudents = 0;
                   9532:     foreach my $last (sort(keys(%bylast))) {
                   9533:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9534:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9535:                 my $showscandata = $scandata{$pid};
                   9536:                 my $showrecord = $record{$pid};
                   9537:                 $showscandata =~ s/\s/&nbsp;/g;
                   9538:                 $showrecord =~ s/\s/&nbsp;/g;
                   9539:                 if ($scandata{$pid} eq $record{$pid}) {
                   9540:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9541:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9542: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9543: '</tr>'."\n".
                   9544: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9545: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9546:                     $passed ++;
                   9547:                 } else {
                   9548:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9549:                     $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  9550: '</tr>'."\n".
                   9551: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9552: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9553: '</tr>'."\n";
                   9554:                     $failed ++;
                   9555:                 }
                   9556:                 $numstudents ++;
                   9557:             }
                   9558:         }
                   9559:     }
1.648     bisitz   9560:     $r->print(
                   9561:         '<p>'
                   9562:        .&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).',
                   9563:             '<b>',
                   9564:             $numstudents,
                   9565:             '</b>',
                   9566:             $env{'form.scantron_maxbubble'})
                   9567:        .'</p>'
                   9568:     );
1.682     raeburn  9569:     $r->print('<p>'
1.683     raeburn  9570:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9571:              .'<br />'
                   9572:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9573:              .'</p>'
                   9574:     );
1.523     raeburn  9575:     if ($passed) {
1.572     www      9576:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9577:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9578:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9579:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9580:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9581:                  $okstudents."\n".
                   9582:                  &Apache::loncommon::end_data_table().'<br />');
                   9583:     }
                   9584:     if ($failed) {
1.572     www      9585:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9586:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9587:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9588:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9589:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9590:                  $badstudents."\n".
                   9591:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9592:                  &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  9593:     }
1.614     www      9594:     $r->print('</form><br />');
1.523     raeburn  9595:     return;
                   9596: }
                   9597: 
1.542     raeburn  9598: sub verify_scantron_grading {
1.554     raeburn  9599:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9600:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9601:         $respnumlookup,$startline) = @_;
1.542     raeburn  9602:     my ($record,%expected,%startpos);
                   9603:     return ($counter,$record) if (!ref($resource));
                   9604:     return ($counter,$record) if (!$resource->is_problem());
                   9605:     my $symb = $resource->symb();
1.554     raeburn  9606:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9607:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9608:         $counter ++;
                   9609:         $expected{$part_id} = 0;
1.691     raeburn  9610:         my $respnum = $counter;
                   9611:         if ($randomorder || $randompick) {
                   9612:             $respnum = $respnumlookup->{$counter};
                   9613:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9614:         } else {
                   9615:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9616:         }
                   9617:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9618:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9619:             foreach my $item (@sub_lines) {
                   9620:                 $expected{$part_id} += $item;
                   9621:             }
                   9622:         } else {
1.691     raeburn  9623:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9624:         }
                   9625:     }
                   9626:     if ($symb) {
                   9627:         my %recorded;
                   9628:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9629:         if ($returnhash{'version'}) {
                   9630:             my %lasthash=();
                   9631:             my $version;
                   9632:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9633:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9634:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9635:                 }
                   9636:             }
                   9637:             foreach my $key (keys(%lasthash)) {
                   9638:                 if ($key =~ /\.scantron$/) {
                   9639:                     my $value = &unescape($lasthash{$key});
                   9640:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9641:                     if ($value eq '') {
                   9642:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9643:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9644:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9645:                             }
                   9646:                         }
                   9647:                     } else {
                   9648:                         my @tocheck;
                   9649:                         my @items = split(//,$value);
                   9650:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9651:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9652:                             if (@items < $expected{$part_id}) {
                   9653:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9654:                                 my @singles = split(//,$fragment);
                   9655:                                 foreach my $pos (@singles) {
                   9656:                                     if ($pos eq ' ') {
                   9657:                                         push(@tocheck,$pos);
                   9658:                                     } else {
                   9659:                                         my $next = shift(@items);
                   9660:                                         push(@tocheck,$next);
                   9661:                                     }
                   9662:                                 }
                   9663:                             } else {
                   9664:                                 @tocheck = @items;
                   9665:                             }
                   9666:                             foreach my $letter (@tocheck) {
                   9667:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9668:                                     if ($letter !~ /^[A-J]$/) {
                   9669:                                         $letter = $scantron_config->{'Qoff'};
                   9670:                                     }
                   9671:                                     $recorded{$part_id} .= $letter;
                   9672:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9673:                                     my $digit;
                   9674:                                     if ($letter !~ /^[A-J]$/) {
                   9675:                                         $digit = $scantron_config->{'Qoff'};
                   9676:                                     } else {
                   9677:                                         $digit = $lettdig->{$letter};
                   9678:                                     }
                   9679:                                     $recorded{$part_id} .= $digit;
                   9680:                                 }
                   9681:                             }
                   9682:                         } else {
                   9683:                             @tocheck = @items;
                   9684:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9685:                                 my $curr_sub = shift(@tocheck);
                   9686:                                 my $digit;
                   9687:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9688:                                     $digit = $lettdig->{$curr_sub}-1;
                   9689:                                 }
                   9690:                                 if ($curr_sub eq 'J') {
                   9691:                                     $digit += scalar($numletts);
                   9692:                                 }
                   9693:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9694:                                     if ($j == $digit) {
                   9695:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9696:                                     } else {
                   9697:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9698:                                     }
                   9699:                                 }
                   9700:                             }
                   9701:                         }
                   9702:                     }
                   9703:                 }
                   9704:             }
                   9705:         }
1.554     raeburn  9706:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9707:             if ($recorded{$part_id} eq '') {
                   9708:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9709:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9710:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9711:                     }
                   9712:                 }
                   9713:             }
                   9714:             $record .= $recorded{$part_id};
                   9715:         }
                   9716:     }
                   9717:     return ($counter,$record);
                   9718: }
                   9719: 
1.691     raeburn  9720: sub letter_to_digits {
1.542     raeburn  9721:     my %lettdig = (
                   9722:                     A => 1,
                   9723:                     B => 2,
                   9724:                     C => 3,
                   9725:                     D => 4,
                   9726:                     E => 5,
                   9727:                     F => 6,
                   9728:                     G => 7,
                   9729:                     H => 8,
                   9730:                     I => 9,
                   9731:                     J => 0,
                   9732:                   );
                   9733:     return %lettdig;
                   9734: }
                   9735: 
1.423     albertel 9736: 
1.75      albertel 9737: #-------- end of section for handling grading scantron forms -------
                   9738: #
                   9739: #-------------------------------------------------------------------
                   9740: 
1.72      ng       9741: #-------------------------- Menu interface -------------------------
                   9742: #
1.614     www      9743: #--- Href with symb and command ---
                   9744: 
                   9745: sub href_symb_cmd {
                   9746:     my ($symb,$cmd)=@_;
1.669     raeburn  9747:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9748: }
                   9749: 
1.443     banghart 9750: sub grading_menu {
1.608     www      9751:     my ($request,$symb) = @_;
1.443     banghart 9752:     if (!$symb) {return '';}
                   9753: 
                   9754:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9755:                   'command'=>'individual');
1.538     schulted 9756:     
1.598     www      9757:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9758: 
                   9759:     $fields{'command'}='ungraded';
                   9760:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9761: 
                   9762:     $fields{'command'}='table';
                   9763:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9764: 
                   9765:     $fields{'command'}='all_for_one';
                   9766:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9767: 
1.621     www      9768:     $fields{'command'}='downloadfilesselect';
                   9769:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9770: 
1.443     banghart 9771:     $fields{'command'} = 'csvform';
1.538     schulted 9772:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9773:     
1.443     banghart 9774:     $fields{'command'} = 'processclicker';
1.538     schulted 9775:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9776:     
1.443     banghart 9777:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9778:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9779: 
                   9780:     $fields{'command'} = 'initialverifyreceipt';
                   9781:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9782:     
1.598     www      9783:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9784:             items =>[
1.598     www      9785:                         {	linktext => 'Select individual students to grade',
                   9786:                     		url => $url1a,
1.538     schulted 9787:                     		permission => 'F',
1.636     wenzelju 9788:                     		icon => 'grade_students.png',
1.598     www      9789:                     		linktitle => 'Grade current resource for a selection of students.'
                   9790:                         }, 
                   9791:                         {       linktext => 'Grade ungraded submissions.',
                   9792:                                 url => $url1b,
                   9793:                                 permission => 'F',
1.636     wenzelju 9794:                                 icon => 'ungrade_sub.png',
1.598     www      9795:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9796:                         },
1.598     www      9797: 
                   9798:                         {       linktext => 'Grading table',
                   9799:                                 url => $url1c,
                   9800:                                 permission => 'F',
1.636     wenzelju 9801:                                 icon => 'grading_table.png',
1.598     www      9802:                                 linktitle => 'Grade current resource for all students.'
                   9803:                         },
1.615     www      9804:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9805:                                 url => $url1d,
                   9806:                                 permission => 'F',
1.636     wenzelju 9807:                                 icon => 'grade_PageFolder.png',
1.598     www      9808:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9809:                         },
                   9810:                         {       linktext => 'Download submissions',
                   9811:                                 url => $url1e,
                   9812:                                 permission => 'F',
1.636     wenzelju 9813:                                 icon => 'download_sub.png',
1.621     www      9814:                                 linktitle => 'Download all students submissions.'
1.598     www      9815:                         }]},
                   9816:                          { categorytitle=>'Automated Grading',
                   9817:                items =>[
                   9818: 
1.538     schulted 9819:                 	    {	linktext => 'Upload Scores',
                   9820:                     		url => $url2,
                   9821:                     		permission => 'F',
                   9822:                     		icon => 'uploadscores.png',
                   9823:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9824:                 	    },
                   9825:                 	    {	linktext => 'Process Clicker',
                   9826:                     		url => $url3,
                   9827:                     		permission => 'F',
                   9828:                     		icon => 'addClickerInfoFile.png',
                   9829:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9830:                 	    },
1.587     raeburn  9831:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9832:                     		url => $url4,
                   9833:                     		permission => 'F',
1.636     wenzelju 9834:                     		icon => 'bubblesheet.png',
1.648     bisitz   9835:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9836:                 	    },
1.616     www      9837:                             {   linktext => 'Verify Receipt Number',
1.602     www      9838:                                 url => $url5,
                   9839:                                 permission => 'F',
1.636     wenzelju 9840:                                 icon => 'receipt_number.png',
1.602     www      9841:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9842:                             }
                   9843: 
1.538     schulted 9844:                     ]
                   9845:             });
                   9846: 
1.443     banghart 9847:     # Create the menu
                   9848:     my $Str;
1.445     banghart 9849:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9850:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9851:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9852: 
1.602     www      9853:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9854:     return $Str;    
                   9855: }
                   9856: 
1.598     www      9857: 
                   9858: sub ungraded {
                   9859:     my ($request)=@_;
                   9860:     &submit_options($request);
                   9861: }
                   9862: 
1.599     www      9863: sub submit_options_sequence {
1.608     www      9864:     my ($request,$symb) = @_;
1.599     www      9865:     if (!$symb) {return '';}
1.600     www      9866:     &commonJSfunctions($request);
                   9867:     my $result;
1.599     www      9868: 
1.600     www      9869:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9870:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9871:     $result.=&selectfield(0).
1.601     www      9872:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9873:             <div>
                   9874:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9875:             </div>
                   9876:         </div>
                   9877:   </form>';
                   9878:     return $result;
                   9879: }
                   9880: 
                   9881: sub submit_options_table {
1.608     www      9882:     my ($request,$symb) = @_;
1.600     www      9883:     if (!$symb) {return '';}
1.599     www      9884:     &commonJSfunctions($request);
1.746     raeburn  9885:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      9886:     my $result;
                   9887: 
                   9888:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9889:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9890: 
1.745     raeburn  9891:     $result.=&selectfield(1,$is_tool).
1.601     www      9892:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9893:             <div>
                   9894:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9895:             </div>
                   9896:         </div>
                   9897:   </form>';
                   9898:     return $result;
                   9899: }
1.443     banghart 9900: 
1.621     www      9901: sub submit_options_download {
                   9902:     my ($request,$symb) = @_;
                   9903:     if (!$symb) {return '';}
                   9904: 
1.746     raeburn  9905:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      9906:     &commonJSfunctions($request);
                   9907: 
                   9908:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9909:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9910:     $result.='
                   9911: <h2>
1.750     raeburn  9912:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  9913: </h2>'.&selectfield(1,$is_tool).'
1.621     www      9914:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9915:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9916:             </div>
                   9917:           </div>
1.600     www      9918: 
                   9919: 
1.621     www      9920:   </form>';
                   9921:     return $result;
                   9922: }
                   9923: 
1.443     banghart 9924: #--- Displays the submissions first page -------
                   9925: sub submit_options {
1.608     www      9926:     my ($request,$symb) = @_;
1.72      ng       9927:     if (!$symb) {return '';}
                   9928: 
1.746     raeburn  9929:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       9930:     &commonJSfunctions($request);
1.473     albertel 9931:     my $result;
1.533     bisitz   9932: 
1.72      ng       9933:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9934: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  9935:     $result.=&selectfield(1,$is_tool).'
1.601     www      9936:                 <input type="hidden" name="command" value="submission" /> 
                   9937: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9938:             </div>
                   9939:           </div>
                   9940: 
                   9941: 
                   9942:   </form>';
                   9943:     return $result;
                   9944: }
1.533     bisitz   9945: 
1.601     www      9946: sub selectfield {
1.745     raeburn  9947:    my ($full,$is_tool)=@_;
                   9948:    my %options;
                   9949:    if ($is_tool) {
                   9950:        %options =
                   9951:            (&transtatus_options,
                   9952:             'select_form_order' => ['yes','incorrect','all']);
                   9953:    } else {
                   9954:        %options = 
                   9955:            (&substatus_options,
                   9956:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   9957:    }
1.601     www      9958:    my $result='<div class="LC_columnSection">
1.537     harmsja  9959:   
1.533     bisitz   9960:     <fieldset>
                   9961:       <legend>
                   9962:        '.&mt('Sections').'
                   9963:       </legend>
1.601     www      9964:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9965:     </fieldset>
1.537     harmsja  9966:   
1.533     bisitz   9967:     <fieldset>
                   9968:       <legend>
                   9969:         '.&mt('Groups').'
                   9970:       </legend>
                   9971:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9972:     </fieldset>
1.537     harmsja  9973:   
1.533     bisitz   9974:     <fieldset>
                   9975:       <legend>
                   9976:         '.&mt('Access Status').'
                   9977:       </legend>
1.601     www      9978:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9979:     </fieldset>';
                   9980:     if ($full) {
1.745     raeburn  9981:         my $heading = &mt('Submission Status');
                   9982:         if ($is_tool) {
                   9983:             $heading = &mt('Transaction Status');
                   9984:         }
                   9985:         $result.='
1.533     bisitz   9986:     <fieldset>
                   9987:       <legend>
1.745     raeburn  9988:         '.$heading.'
1.601     www      9989:       </legend>'.
1.635     raeburn  9990:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9991:    '</fieldset>';
                   9992:     }
                   9993:     $result.='</div><br />';
1.44      ng       9994:     return $result;
1.2       albertel 9995: }
                   9996: 
1.738     raeburn  9997: sub substatus_options {
                   9998:     return &Apache::lonlocal::texthash(
                   9999:                                       'yes'       => 'with submissions',
                   10000:                                       'queued'    => 'in grading queue',
                   10001:                                       'graded'    => 'with ungraded submissions',
                   10002:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10003:                                       'all'       => 'with any status',
                   10004:                                       );
1.738     raeburn  10005: }
                   10006: 
1.745     raeburn  10007: sub transtatus_options {
                   10008:     return &Apache::lonlocal::texthash(
                   10009:                                        'yes'       => 'with score transactions',
                   10010:                                        'incorrect' => 'with less than full credit',
                   10011:                                        'all'       => 'with any status',
                   10012:                                       );
                   10013: }
                   10014: 
1.285     albertel 10015: sub reset_perm {
                   10016:     undef(%perm);
                   10017: }
                   10018: 
                   10019: sub init_perm {
                   10020:     &reset_perm();
1.300     albertel 10021:     foreach my $test_perm ('vgr','mgr','opa') {
                   10022: 
                   10023: 	my $scope = $env{'request.course.id'};
                   10024: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10025: 
                   10026: 	    $scope .= '/'.$env{'request.course.sec'};
                   10027: 	    if ( $perm{$test_perm}=
                   10028: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10029: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10030: 	    } else {
                   10031: 		delete($perm{$test_perm});
                   10032: 	    }
1.285     albertel 10033: 	}
                   10034:     }
                   10035: }
                   10036: 
1.674     raeburn  10037: sub init_old_essays {
                   10038:     my ($symb,$apath,$adom,$aname) = @_;
                   10039:     if ($symb ne '') {
                   10040:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10041:         if (keys(%essays) > 0) {
                   10042:             $old_essays{$symb} = \%essays;
                   10043:         }
                   10044:     }
                   10045:     return;
                   10046: }
                   10047: 
                   10048: sub reset_old_essays {
                   10049:     undef(%old_essays);
                   10050: }
                   10051: 
1.400     www      10052: sub gather_clicker_ids {
1.408     albertel 10053:     my %clicker_ids;
1.400     www      10054: 
                   10055:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10056: 
                   10057:     # Set up a couple variables.
1.407     albertel 10058:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10059:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10060:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10061: 
1.407     albertel 10062:     foreach my $student (keys(%$classlist)) {
1.438     www      10063:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10064:         my $username = $classlist->{$student}->[$username_idx];
                   10065:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10066:         my $clickers =
1.408     albertel 10067: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10068:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10069:             $id=~s/^[\#0]+//;
1.421     www      10070:             $id=~s/[\-\:]//g;
1.407     albertel 10071:             if (exists($clicker_ids{$id})) {
1.408     albertel 10072: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10073:             } else {
1.408     albertel 10074: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10075:             }
                   10076:         }
                   10077:     }
1.407     albertel 10078:     return %clicker_ids;
1.400     www      10079: }
                   10080: 
1.402     www      10081: sub gather_adv_clicker_ids {
1.408     albertel 10082:     my %clicker_ids;
1.402     www      10083:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10084:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10085:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10086:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10087:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10088:             my ($puname,$pudom)=split(/\:/,$person);
                   10089:             my $clickers =
1.408     albertel 10090: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10091:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10092: 		$id=~s/^[\#0]+//;
1.421     www      10093:                 $id=~s/[\-\:]//g;
1.408     albertel 10094: 		if (exists($clicker_ids{$id})) {
                   10095: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10096: 		} else {
                   10097: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10098: 		}
1.405     www      10099:             }
1.402     www      10100:         }
                   10101:     }
1.407     albertel 10102:     return %clicker_ids;
1.402     www      10103: }
                   10104: 
1.413     www      10105: sub clicker_grading_parameters {
                   10106:     return ('gradingmechanism' => 'scalar',
                   10107:             'upfiletype' => 'scalar',
                   10108:             'specificid' => 'scalar',
                   10109:             'pcorrect' => 'scalar',
                   10110:             'pincorrect' => 'scalar');
                   10111: }
                   10112: 
1.400     www      10113: sub process_clicker {
1.608     www      10114:     my ($r,$symb)=@_;
1.400     www      10115:     if (!$symb) {return '';}
                   10116:     my $result=&checkforfile_js();
1.632     www      10117:     $result.=&Apache::loncommon::start_data_table().
                   10118:              &Apache::loncommon::start_data_table_header_row().
                   10119:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10120:              &Apache::loncommon::end_data_table_header_row().
                   10121:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10122: # Attempt to restore parameters from last session, set defaults if not present
                   10123:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10124:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10125:                                                  \%Saveable_Parameters);
                   10126:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10127:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10128:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10129:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10130: 
                   10131:     my %checked;
1.521     www      10132:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10133:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10134:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10135:        }
                   10136:     }
                   10137: 
1.632     www      10138:     my $upload=&mt("Evaluate File");
1.400     www      10139:     my $type=&mt("Type");
1.402     www      10140:     my $attendance=&mt("Award points just for participation");
                   10141:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10142:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10143:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10144:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10145:     my $pcorrect=&mt("Percentage points for correct solution");
                   10146:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10147:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10148: 						   {'iclicker' => 'i>clicker',
1.666     www      10149:                                                     'interwrite' => 'interwrite PRS',
                   10150:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10151:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10152:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10153: function sanitycheck() {
                   10154: // Accept only integer percentages
                   10155:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10156:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10157: // Find out grading choice
                   10158:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10159:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10160:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10161:       }
                   10162:    }
                   10163: // By default, new choice equals user selection
                   10164:    newgradingchoice=gradingchoice;
                   10165: // Not good to give more points for false answers than correct ones
                   10166:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10167:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10168:    }
                   10169: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10170:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10171:       document.forms.gradesupload.pcorrect.value=100;
                   10172:       document.forms.gradesupload.pincorrect.value=100;
                   10173:    }
                   10174: // If the values are different, cannot be attendance only
                   10175:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10176:        (gradingchoice=='attendance')) {
                   10177:        newgradingchoice='personnel';
                   10178:    }
                   10179: // Change grading choice to new one
                   10180:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10181:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10182:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10183:       } else {
                   10184:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10185:       }
                   10186:    }
                   10187: // Remember the old state
                   10188:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10189: }
1.597     wenzelju 10190: ENDUPFORM
                   10191:     $result.= <<ENDUPFORM;
1.400     www      10192: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10193: <input type="hidden" name="symb" value="$symb" />
                   10194: <input type="hidden" name="command" value="processclickerfile" />
                   10195: <input type="file" name="upfile" size="50" />
                   10196: <br /><label>$type: $selectform</label>
1.632     www      10197: ENDUPFORM
                   10198:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10199:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10200:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10201: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10202: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10203: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10204: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10205: <br />&nbsp;&nbsp;&nbsp;
                   10206: <input type="text" name="givenanswer" size="50" />
1.413     www      10207: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10208: ENDGRADINGFORM
                   10209:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10210:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10211:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10212: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10213: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 10214: </form>'
1.632     www      10215: ENDPERCFORM
                   10216:     $result.='</td>'.
                   10217:              &Apache::loncommon::end_data_table_row().
                   10218:              &Apache::loncommon::end_data_table();
1.400     www      10219:     return $result;
                   10220: }
                   10221: 
                   10222: sub process_clicker_file {
1.608     www      10223:     my ($r,$symb)=@_;
1.400     www      10224:     if (!$symb) {return '';}
1.413     www      10225: 
                   10226:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10227:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10228:                                               \%Saveable_Parameters);
1.598     www      10229:     my $result='';
1.404     www      10230:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10231: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10232: 	return $result;
1.404     www      10233:     }
1.522     www      10234:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10235:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10236:         return $result;
1.521     www      10237:     }
1.522     www      10238:     my $foundgiven=0;
1.521     www      10239:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10240:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10241:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10242:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10243:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10244:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10245:         $foundgiven=$#answers+1;
1.521     www      10246:     }
1.407     albertel 10247:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10248:     my %correct_ids;
1.404     www      10249:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10250: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10251:     }
                   10252:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10253: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10254: 	   $correct_id=~tr/a-z/A-Z/;
                   10255: 	   $correct_id=~s/\s//gs;
                   10256: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10257:            $correct_id=~s/[\-\:]//g;
1.414     www      10258:            if ($correct_id) {
                   10259: 	      $correct_ids{$correct_id}='specified';
                   10260:            }
                   10261:         }
1.400     www      10262:     }
1.404     www      10263:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10264: 	$result.=&mt('Score based on attendance only');
1.521     www      10265:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10266:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10267:     } else {
1.408     albertel 10268: 	my $number=0;
1.411     www      10269: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10270: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10271: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10272: 	    if ($correct_ids{$id} eq 'specified') {
                   10273: 		$result.=&mt('specified');
                   10274: 	    } else {
                   10275: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10276: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10277: 	    }
                   10278: 	    $number++;
                   10279: 	}
1.411     www      10280:         $result.="</p>\n";
1.710     bisitz   10281:         if ($number==0) {
                   10282:             $result .=
                   10283:                  &Apache::lonhtmlcommon::confirm_success(
                   10284:                      &mt('No IDs found to determine correct answer'),1);
                   10285:             return $result;
                   10286:         }
1.404     www      10287:     }
1.405     www      10288:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10289:         $result .=
                   10290:             &Apache::lonhtmlcommon::confirm_success(
                   10291:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10292:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10293:         return $result;
1.405     www      10294:     }
1.410     www      10295: 
                   10296: # Were able to get all the info needed, now analyze the file
                   10297: 
1.411     www      10298:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10299:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10300:     $result.=&Apache::loncommon::start_data_table().
                   10301:              &Apache::loncommon::start_data_table_header_row().
                   10302:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10303:              &Apache::loncommon::end_data_table_header_row().
                   10304:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10305: <td>
1.410     www      10306: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10307: <input type="hidden" name="symb" value="$symb" />
                   10308: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10309: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10310: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10311: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10312: ENDHEADER
1.522     www      10313:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10314:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10315:     } 
1.408     albertel 10316:     my %responses;
                   10317:     my @questiontitles;
1.405     www      10318:     my $errormsg='';
                   10319:     my $number=0;
                   10320:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10321: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10322:     }
1.419     www      10323:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10324:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10325:     }
1.666     www      10326:     if ($env{'form.upfiletype'} eq 'turning') {
                   10327:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10328:     }
1.411     www      10329:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10330:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10331:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10332:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10333:              '<br />';
1.522     www      10334:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10335:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10336:        return $result;
1.522     www      10337:     } 
1.414     www      10338: # Remember Question Titles
                   10339: # FIXME: Possibly need delimiter other than ":"
                   10340:     for (my $i=0;$i<$number;$i++) {
                   10341:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10342:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10343:     }
1.411     www      10344:     my $correct_count=0;
                   10345:     my $student_count=0;
                   10346:     my $unknown_count=0;
1.414     www      10347: # Match answers with usernames
                   10348: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10349:     foreach my $id (keys(%responses)) {
1.410     www      10350:        if ($correct_ids{$id}) {
1.414     www      10351:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10352:           $correct_count++;
1.410     www      10353:        } elsif ($clicker_ids{$id}) {
1.437     www      10354:           if ($clicker_ids{$id}=~/\,/) {
                   10355: # More than one user with the same clicker!
1.632     www      10356:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10357:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10358:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10359:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10360:                            "<select name='multi".$id."'>";
                   10361:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10362:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10363:              }
                   10364:              $result.='</select>';
                   10365:              $unknown_count++;
                   10366:           } else {
                   10367: # Good: found one and only one user with the right clicker
                   10368:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10369:              $student_count++;
                   10370:           }
1.410     www      10371:        } else {
1.632     www      10372:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10373:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10374:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10375:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10376:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10377:                    "\n".&mt("Domain").": ".
                   10378:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      10379:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10380:           $unknown_count++;
1.410     www      10381:        }
1.405     www      10382:     }
1.412     www      10383:     $result.='<hr />'.
                   10384:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10385:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10386:        if ($correct_count==0) {
1.696     bisitz   10387:           $errormsg.="Found no correct answers for grading!";
1.412     www      10388:        } elsif ($correct_count>1) {
1.414     www      10389:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10390:        }
                   10391:     }
1.428     www      10392:     if ($number<1) {
                   10393:        $errormsg.="Found no questions.";
                   10394:     }
1.412     www      10395:     if ($errormsg) {
                   10396:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10397:     } else {
                   10398:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10399:     }
1.632     www      10400:     $result.='</form></td>'.
                   10401:              &Apache::loncommon::end_data_table_row().
                   10402:              &Apache::loncommon::end_data_table();
1.614     www      10403:     return $result;
1.400     www      10404: }
                   10405: 
1.405     www      10406: sub iclicker_eval {
1.406     www      10407:     my ($questiontitles,$responses)=@_;
1.405     www      10408:     my $number=0;
                   10409:     my $errormsg='';
                   10410:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10411:         my %components=&Apache::loncommon::record_sep($line);
                   10412:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10413: 	if ($entries[0] eq 'Question') {
                   10414: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10415: 		$$questiontitles[$number]=$entries[$i];
                   10416: 		$number++;
                   10417: 	    }
                   10418: 	}
                   10419: 	if ($entries[0]=~/^\#/) {
                   10420: 	    my $id=$entries[0];
                   10421: 	    my @idresponses;
                   10422: 	    $id=~s/^[\#0]+//;
                   10423: 	    for (my $i=0;$i<$number;$i++) {
                   10424: 		my $idx=3+$i*6;
1.644     www      10425:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10426: 		push(@idresponses,$entries[$idx]);
                   10427: 	    }
                   10428: 	    $$responses{$id}=join(',',@idresponses);
                   10429: 	}
1.405     www      10430:     }
                   10431:     return ($errormsg,$number);
                   10432: }
                   10433: 
1.419     www      10434: sub interwrite_eval {
                   10435:     my ($questiontitles,$responses)=@_;
                   10436:     my $number=0;
                   10437:     my $errormsg='';
1.420     www      10438:     my $skipline=1;
                   10439:     my $questionnumber=0;
                   10440:     my %idresponses=();
1.419     www      10441:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10442:         my %components=&Apache::loncommon::record_sep($line);
                   10443:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10444:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10445:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10446:         next if $skipline;
                   10447:         if ($entries[0]!=$questionnumber) {
                   10448:            $questionnumber=$entries[0];
                   10449:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10450:            $number++;
1.419     www      10451:         }
1.420     www      10452:         my $id=$entries[4];
                   10453:         $id=~s/^[\#0]+//;
1.421     www      10454:         $id=~s/^v\d*\://i;
                   10455:         $id=~s/[\-\:]//g;
1.420     www      10456:         $idresponses{$id}[$number]=$entries[6];
                   10457:     }
1.524     raeburn  10458:     foreach my $id (keys(%idresponses)) {
1.420     www      10459:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10460:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10461:     }
                   10462:     return ($errormsg,$number);
                   10463: }
                   10464: 
1.666     www      10465: sub turning_eval {
                   10466:     my ($questiontitles,$responses)=@_;
                   10467:     my $number=0;
                   10468:     my $errormsg='';
                   10469:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10470:         my %components=&Apache::loncommon::record_sep($line);
                   10471:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10472:         if ($#entries>$number) { $number=$#entries; }
                   10473:         my $id=$entries[0];
                   10474:         my @idresponses;
                   10475:         $id=~s/^[\#0]+//;
                   10476:         unless ($id) { next; }
                   10477:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10478:             $entries[$idx]=~s/\,/\;/g;
                   10479:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10480:             push(@idresponses,$entries[$idx]);
                   10481:         }
                   10482:         $$responses{$id}=join(',',@idresponses);
                   10483:     }
                   10484:     for (my $i=1; $i<=$number; $i++) {
                   10485:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10486:     }
                   10487:     return ($errormsg,$number);
                   10488: }
                   10489: 
                   10490: 
1.414     www      10491: sub assign_clicker_grades {
1.608     www      10492:     my ($r,$symb)=@_;
1.414     www      10493:     if (!$symb) {return '';}
1.416     www      10494: # See which part we are saving to
1.582     raeburn  10495:     my $res_error;
                   10496:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10497:     if ($res_error) {
                   10498:         return &navmap_errormsg();
                   10499:     }
1.416     www      10500: # FIXME: This should probably look for the first handgradeable part
                   10501:     my $part=$$partlist[0];
                   10502: # Start screen output
1.632     www      10503:     my $result=&Apache::loncommon::start_data_table().
                   10504:              &Apache::loncommon::start_data_table_header_row().
                   10505:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10506:              &Apache::loncommon::end_data_table_header_row().
                   10507:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10508: # Get correct result
                   10509: # FIXME: Possibly need delimiter other than ":"
                   10510:     my @correct=();
1.415     www      10511:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10512:     my $number=$env{'form.number'};
                   10513:     if ($gradingmechanism ne 'attendance') {
1.414     www      10514:        foreach my $key (keys(%env)) {
                   10515:           if ($key=~/^form\.correct\:/) {
                   10516:              my @input=split(/\,/,$env{$key});
                   10517:              for (my $i=0;$i<=$#input;$i++) {
                   10518:                  if (($correct[$i]) && ($input[$i]) &&
                   10519:                      ($correct[$i] ne $input[$i])) {
                   10520:                     $result.='<br /><span class="LC_warning">'.
                   10521:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10522:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10523:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10524:                     $correct[$i]=$input[$i];
                   10525:                  }
                   10526:              }
                   10527:           }
                   10528:        }
1.415     www      10529:        for (my $i=0;$i<$number;$i++) {
1.644     www      10530:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10531:              $result.='<br /><span class="LC_error">'.
                   10532:                       &mt('No correct result given for question "[_1]"!',
                   10533:                           $env{'form.question:'.$i}).'</span>';
                   10534:           }
                   10535:        }
1.644     www      10536:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10537:     }
                   10538: # Start grading
1.415     www      10539:     my $pcorrect=$env{'form.pcorrect'};
                   10540:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10541:     my $storecount=0;
1.632     www      10542:     my %users=();
1.415     www      10543:     foreach my $key (keys(%env)) {
1.420     www      10544:        my $user='';
1.415     www      10545:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10546:           $user=$1;
                   10547:        }
                   10548:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10549:           my $id=$1;
                   10550:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10551:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10552:           } elsif ($env{'form.multi'.$id}) {
                   10553:              $user=$env{'form.multi'.$id};
1.420     www      10554:           }
                   10555:        }
1.632     www      10556:        if ($user) {
                   10557:           if ($users{$user}) {
                   10558:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10559:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10560:                       '</span><br />';
                   10561:           }
                   10562:           $users{$user}=1; 
1.415     www      10563:           my @answer=split(/\,/,$env{$key});
                   10564:           my $sum=0;
1.522     www      10565:           my $realnumber=$number;
1.415     www      10566:           for (my $i=0;$i<$number;$i++) {
1.576     www      10567:              if  ($correct[$i] eq '-') {
                   10568:                 $realnumber--;
1.644     www      10569:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10570:                 if ($gradingmechanism eq 'attendance') {
                   10571:                    $sum+=$pcorrect;
1.576     www      10572:                 } elsif ($correct[$i] eq '*') {
1.522     www      10573:                    $sum+=$pcorrect;
1.415     www      10574:                 } else {
1.644     www      10575: # We actually grade if correct or not
                   10576:                    my $increment=$pincorrect;
                   10577: # Special case: numerical answer "0"
                   10578:                    if ($correct[$i] eq '0') {
                   10579:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10580:                          $increment=$pcorrect;
                   10581:                       }
                   10582: # General numerical answer, both evaluate to something non-zero
                   10583:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10584:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10585:                          $increment=$pcorrect;
                   10586:                       }
                   10587: # Must be just alphanumeric
                   10588:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10589:                       $increment=$pcorrect;
1.415     www      10590:                    }
1.644     www      10591:                    $sum+=$increment;
1.415     www      10592:                 }
                   10593:              }
                   10594:           }
1.522     www      10595:           my $ave=$sum/(100*$realnumber);
1.416     www      10596: # Store
                   10597:           my ($username,$domain)=split(/\:/,$user);
                   10598:           my %grades=();
                   10599:           $grades{"resource.$part.solved"}='correct_by_override';
                   10600:           $grades{"resource.$part.awarded"}=$ave;
                   10601:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10602:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10603:                                                  $env{'request.course.id'},
                   10604:                                                  $domain,$username);
                   10605:           if ($returncode ne 'ok') {
                   10606:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10607:           } else {
                   10608:              $storecount++;
                   10609:           }
1.415     www      10610:        }
                   10611:     }
                   10612: # We are done
1.549     hauer    10613:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10614:              '</td>'.
                   10615:              &Apache::loncommon::end_data_table_row().
                   10616:              &Apache::loncommon::end_data_table();
1.614     www      10617:     return $result;
1.414     www      10618: }
                   10619: 
1.582     raeburn  10620: sub navmap_errormsg {
                   10621:     return '<div class="LC_error">'.
                   10622:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10623:            &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  10624:            '</div>';
                   10625: }
1.607     droeschl 10626: 
1.609     www      10627: sub startpage {
1.671     raeburn  10628:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10629:     if ($nomenu) {
                   10630:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10631:     } else {
                   10632:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10633:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10634:                                                  {'bread_crumbs' => $crumbs}));
                   10635:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10636:     }
1.613     www      10637:     unless ($nodisplayflag) {
1.671     raeburn  10638:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10639:     }
1.607     droeschl 10640: }
1.582     raeburn  10641: 
1.622     www      10642: sub select_problem {
                   10643:     my ($r)=@_;
1.632     www      10644:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.745     raeburn  10645:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
1.622     www      10646:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10647:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10648: }
                   10649: 
1.1       albertel 10650: sub handler {
1.41      ng       10651:     my $request=$_[0];
1.434     albertel 10652:     &reset_caches();
1.646     raeburn  10653:     if ($request->header_only) {
                   10654:         &Apache::loncommon::content_type($request,'text/html');
                   10655:         $request->send_http_header;
                   10656:         return OK;
                   10657:     }
                   10658:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10659: 
1.664     raeburn  10660: # see what command we need to execute
                   10661: 
                   10662:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10663:     my $command=$commands[0];
                   10664: 
1.646     raeburn  10665:     &init_perm();
                   10666:     if (!$env{'request.course.id'}) {
1.664     raeburn  10667:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10668:                 ($command =~ /^scantronupload/)) {
                   10669:             # Not in a course.
                   10670:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10671:             return HTTP_NOT_ACCEPTABLE;
                   10672:         }
1.646     raeburn  10673:     } elsif (!%perm) {
                   10674:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10675:         return OK;
1.41      ng       10676:     }
1.646     raeburn  10677:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10678:     $request->send_http_header;
1.646     raeburn  10679: 
1.160     albertel 10680:     if ($#commands > 0) {
                   10681: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10682:     }
1.608     www      10683: 
                   10684: # see what the symb is
                   10685: 
                   10686:     my $symb=$env{'form.symb'};
                   10687:     unless ($symb) {
                   10688:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10689:        $symb=&Apache::lonnet::symbread($url);
                   10690:     }
1.646     raeburn  10691:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10692: 
1.513     foxr     10693:     $ssi_error = 0;
1.637     www      10694:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10695: #
1.637     www      10696: # Not called from a resource, but inside a course
1.601     www      10697: #    
1.622     www      10698:         &startpage($request,undef,[],1,1);
                   10699:         &select_problem($request);
1.41      ng       10700:     } else {
1.104     albertel 10701: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10702:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10703:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10704:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10705:                     &choose_task_version_form($symb,$env{'form.student'},
                   10706:                                               $env{'form.userdom'});
                   10707:             }
                   10708:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10709:             if ($versionform) {
                   10710:                 $request->print($versionform);
                   10711:             }
                   10712:             $request->print('<br clear="all" />');
1.611     www      10713: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10714:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10715:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10716:                 &choose_task_version_form($symb,$env{'form.student'},
                   10717:                                           $env{'form.userdom'},
                   10718:                                           $env{'form.inhibitmenu'});
                   10719:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10720:             if ($versionform) {
                   10721:                 $request->print($versionform);
                   10722:             }
                   10723:             $request->print('<br clear="all" />');
                   10724:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10725: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10726:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10727:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10728: 	    &pickStudentPage($request,$symb);
1.103     albertel 10729: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10730:             &startpage($request,$symb,
                   10731:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10732:                                        {href=>'',text=>'Select student'},
                   10733:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10734: 	    &displayPage($request,$symb);
1.104     albertel 10735: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10736:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10737:                                        {href=>'',text=>'Select student'},
                   10738:                                        {href=>'',text=>'Grade student'},
                   10739:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10740: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10741: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10742:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10743:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10744: 	    &processGroup($request,$symb);
1.104     albertel 10745: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10746:             &startpage($request,$symb);
                   10747: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10748: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10749:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10750: 	    $request->print(&submit_options($request,$symb));
1.598     www      10751:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10752:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10753:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10754:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10755:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10756:             $request->print(&submit_options_table($request,$symb));
1.598     www      10757:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10758:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10759:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10760: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10761:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10762: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10763: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10764:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10765:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10766: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10767: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10768:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10769:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10770:                                                                              text=>"Modify grades"},
                   10771:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10772: 	    $request->print(&editgrades($request,$symb));
1.602     www      10773:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10774:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10775:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10776: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10777:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10778:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10779: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10780:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10781:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10782:             $request->print(&process_clicker($request,$symb));
1.400     www      10783:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10784:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10785:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10786:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10787:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10788:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10789:                                        {href=>'', text=>'Process clicker file'},
                   10790:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10791:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10792: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10793:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10794: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10795: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10796:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10797: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10798: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10799:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10800: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10801: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10802: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10803:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10804: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10805: 	    } else {
1.257     albertel 10806: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10807: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10808: 		} else {
1.257     albertel 10809: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10810: 		}
1.627     www      10811:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10812: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10813: 	    }
1.246     albertel 10814: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10815:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10816: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10817: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10818:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10819: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10820:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10821:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10822:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10823: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10824:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10825: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10826: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10827:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10828: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10829:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10830:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10831: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10832:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10833:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10834:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10835:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10836: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10837:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10838:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10839:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10840: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10841:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10842:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10843:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10844:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10845:             $request->print(&checkscantron_results($request,$symb));
                   10846:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10847:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10848:             $request->print(&submit_options_download($request,$symb));
                   10849:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10850:             &startpage($request,$symb,
                   10851:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.750     raeburn  10852:     {href=>'', text=>'Download submitted files'}]);
1.621     www      10853:             &submit_download_link($request,$symb);
1.106     albertel 10854: 	} elsif ($command) {
1.620     www      10855:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10856: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10857: 	}
1.2       albertel 10858:     }
1.513     foxr     10859:     if ($ssi_error) {
                   10860: 	&ssi_print_error($request);
                   10861:     }
1.671     raeburn  10862:     if ($env{'form.inhibitmenu'}) {
                   10863:         $request->print(&Apache::loncommon::end_page());
                   10864:     } else {
                   10865:         &Apache::lonquickgrades::endGradeScreen($request);
                   10866:     }
1.434     albertel 10867:     &reset_caches();
1.646     raeburn  10868:     return OK;
1.44      ng       10869: }
                   10870: 
1.1       albertel 10871: 1;
                   10872: 
1.13      albertel 10873: __END__;
1.531     jms      10874: 
                   10875: 
                   10876: =head1 NAME
                   10877: 
                   10878: Apache::grades
                   10879: 
                   10880: =head1 SYNOPSIS
                   10881: 
                   10882: Handles the viewing of grades.
                   10883: 
                   10884: This is part of the LearningOnline Network with CAPA project
                   10885: described at http://www.lon-capa.org.
                   10886: 
                   10887: =head1 OVERVIEW
                   10888: 
                   10889: Do an ssi with retries:
1.715     bisitz   10890: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10891: 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
                   10892: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10893: 
                   10894: At least the logic that drives this has been pulled out into loncommon.
                   10895: 
                   10896: 
                   10897: 
                   10898: ssi_with_retries - Does the server side include of a resource.
                   10899:                      if the ssi call returns an error we'll retry it up to
                   10900:                      the number of times requested by the caller.
1.715     bisitz   10901:                      If we still have a problem, no text is appended to the
1.531     jms      10902:                      output and we set some global variables.
                   10903:                      to indicate to the caller an SSI error occurred.  
                   10904:                      All of this is supposed to deal with the issues described
1.715     bisitz   10905:                      in LON-CAPA BZ 5631 see:
1.531     jms      10906:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10907:                      by informing the user that this happened.
                   10908: 
                   10909: Parameters:
                   10910:   resource   - The resource to include.  This is passed directly, without
                   10911:                interpretation to lonnet::ssi.
                   10912:   form       - The form hash parameters that guide the interpretation of the resource
                   10913:                
                   10914:   retries    - Number of retries allowed before giving up completely.
                   10915: Returns:
                   10916:   On success, returns the rendered resource identified by the resource parameter.
                   10917: Side Effects:
                   10918:   The following global variables can be set:
                   10919:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10920:                               It is up to the caller to initialize this to false
                   10921:                               if desired.
                   10922:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10923:                               of the resource that could not be rendered by the ssi
                   10924:                               call.
                   10925:    ssi_error_message   - The error string fetched from the ssi response
                   10926:                               in the event of an error.
                   10927: 
                   10928: 
                   10929: =head1 HANDLER SUBROUTINE
                   10930: 
                   10931: ssi_with_retries()
                   10932: 
                   10933: =head1 SUBROUTINES
                   10934: 
                   10935: =over
                   10936: 
1.671     raeburn  10937: =head1 Routines to display previous version of a Task for a specific student
                   10938: 
                   10939: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10940: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10941: requires a proctor to check-in the student, a new version of the Task will
                   10942: be created when the student is checked in to the new opportunity.
                   10943: 
                   10944: If a particular student has tried two or more versions of a particular task,
                   10945: the submission screen provides a user with vgr privileges (e.g., a Course
                   10946: Coordinator) the ability to display a previous version worked on by the
                   10947: student.  By default, the current version is displayed. If a previous version
                   10948: has been selected for display, submission data are only shown that pertain
                   10949: to that particular version, and the interface to submit grades is not shown.
                   10950: 
                   10951: =over 4
                   10952: 
                   10953: =item show_previous_task_version()
                   10954: 
                   10955: Displays a specified version of a student's Task, as the student sees it.
                   10956: 
                   10957: Inputs: 2
                   10958:         request - request object
                   10959:         symb    - unique symb for current instance of resource
                   10960: 
                   10961: Output: None.
                   10962: 
                   10963: Side Effects: calls &show_problem() to print version of Task, with
                   10964:               version contained in form item: $env{'form.previousversion'}
                   10965: 
                   10966: =item choose_task_version_form()
                   10967: 
                   10968: Displays a web form used to select which version of a student's view of a
                   10969: Task should be displayed.  Either launches a pop-up window, or replaces
                   10970: content in existing pop-up, or replaces page in main window.
                   10971: 
                   10972: Inputs: 4
                   10973:         symb    - unique symb for current instance of resource
                   10974:         uname   - username of student
                   10975:         udom    - domain of student
                   10976:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10977:                   breadcrumbs etc., are displayed
                   10978: 
                   10979: Output: 4
                   10980:         current   - student's current version
                   10981:         displayed - student's version being displayed
                   10982:         result    - scalar containing HTML for web form used to switch to
                   10983:                     a different version (or a link to close window, if pop-up).
                   10984:         js        - javascript for processing selection in versions web form
                   10985: 
                   10986: Side Effects: None.
                   10987: 
                   10988: =item previous_display_javascript()
                   10989: 
                   10990: Inputs: 2
                   10991:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10992:                   breadcrumbs etc., are displayed.
                   10993:         current - student's current version number.
                   10994: 
                   10995: Output: 1
                   10996:         js      - javascript for processing selection in versions web form.
                   10997: 
                   10998: Side Effects: None.
                   10999: 
                   11000: =back
                   11001: 
                   11002: =head1 Routines to process bubblesheet data.
                   11003: 
                   11004: =over 4
                   11005: 
1.531     jms      11006: =item scantron_get_correction() : 
                   11007: 
                   11008:    Builds the interface screen to interact with the operator to fix a
                   11009:    specific error condition in a specific scanline
                   11010: 
                   11011:  Arguments:
                   11012:     $r           - Apache request object
                   11013:     $i           - number of the current scanline
                   11014:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   11015:     $scan_config - hash ref as returned from &get_scantron_config()
                   11016:     $line        - full contents of the current scanline
                   11017:     $error       - error condition, valid values are
                   11018:                    'incorrectCODE', 'duplicateCODE',
                   11019:                    'doublebubble', 'missingbubble',
                   11020:                    'duplicateID', 'incorrectID'
                   11021:     $arg         - extra information needed
                   11022:        For errors:
                   11023:          - duplicateID   - paper number that this studentID was seen before on
                   11024:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11025:                            seen on before
                   11026:          - incorrectCODE - current incorrect CODE 
                   11027:          - doublebubble  - array ref of the bubble lines that have double
                   11028:                            bubble errors
                   11029:          - missingbubble - array ref of the bubble lines that have missing
                   11030:                            bubble errors
                   11031: 
1.691     raeburn  11032:    $randomorder - True if exam folder has randomorder set
                   11033:    $randompick  - True if exam folder has randompick set
                   11034:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11035:                      for current line to question number used for same question
                   11036:                      in "Master Seqence" (as seen by Course Coordinator).
                   11037:    $startline   - Reference to hash where key is question number (0 is first)
                   11038:                   and value is number of first bubble line for current student
                   11039:                   or code-based randompick and/or randomorder.
                   11040: 
                   11041: 
                   11042: 
1.531     jms      11043: =item  scantron_get_maxbubble() : 
                   11044: 
1.582     raeburn  11045:    Arguments:
                   11046:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11047:                       failure to retrieve a navmap object.
                   11048:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11049:        calling routine should trap the error condition and display the warning
                   11050:        found in &navmap_errormsg().
                   11051: 
1.649     raeburn  11052:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11053: 
1.531     jms      11054:    Returns the maximum number of bubble lines that are expected to
                   11055:    occur. Does this by walking the selected sequence rendering the
                   11056:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11057:    for what the current value of the problem counter is.
                   11058: 
                   11059:    Caches the results to $env{'form.scantron_maxbubble'},
                   11060:    $env{'form.scantron.bubble_lines.n'}, 
                   11061:    $env{'form.scantron.first_bubble_line.n'} and
                   11062:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11063:    which are the total number of bubble lines, the number of bubble
1.531     jms      11064:    lines for response n and number of the first bubble line for response n,
                   11065:    and a comma separated list of numbers of bubble lines for sub-questions
                   11066:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11067: 
                   11068: 
                   11069: =item  scantron_validate_missingbubbles() : 
                   11070: 
                   11071:    Validates all scanlines in the selected file to not have any
                   11072:     answers that don't have bubbles that have not been verified
                   11073:     to be bubble free.
                   11074: 
                   11075: =item  scantron_process_students() : 
                   11076: 
1.659     raeburn  11077:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11078: 
                   11079:    The parsed scanline hash is added to %env 
                   11080: 
                   11081:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11082:    foreach resource , with the form data of
                   11083: 
                   11084: 	'submitted'     =>'scantron' 
                   11085: 	'grade_target'  =>'grade',
                   11086: 	'grade_username'=> username of student
                   11087: 	'grade_domain'  => domain of student
                   11088: 	'grade_courseid'=> of course
                   11089: 	'grade_symb'    => symb of resource to grade
                   11090: 
                   11091:     This triggers a grading pass. The problem grading code takes care
                   11092:     of converting the bubbled letter information (now in %env) into a
                   11093:     valid submission.
                   11094: 
                   11095: =item  scantron_upload_scantron_data() :
                   11096: 
1.659     raeburn  11097:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11098: 
                   11099: =item  scantron_upload_scantron_data_save() : 
                   11100: 
                   11101:    Adds a provided bubble information data file to the course if user
                   11102:    has the correct privileges to do so. 
                   11103: 
                   11104: =item  valid_file() :
                   11105: 
                   11106:    Validates that the requested bubble data file exists in the course.
                   11107: 
                   11108: =item  scantron_download_scantron_data() : 
                   11109: 
                   11110:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11111:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11112:    course.
                   11113: 
                   11114: =item  scantron_validate_ID() : 
                   11115: 
                   11116:    Validates all scanlines in the selected file to not have any
1.556     weissno  11117:    invalid or underspecified student/employee IDs
1.531     jms      11118: 
1.582     raeburn  11119: =item navmap_errormsg() :
                   11120: 
                   11121:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11122:    Should be called whenever the request to instantiate a navmap object fails.
                   11123: 
                   11124: =back
1.582     raeburn  11125: 
1.531     jms      11126: =back
                   11127: 
                   11128: =cut

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