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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.749   ! raeburn     4: # $Id: grades.pm,v 1.748 2017/12/31 13:29:53 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
1.745     raeburn   119:     my $toolsymb;
                    120:     if ($url =~ /ext\.tool$/) {
                    121:         $toolsymb = $symb;
                    122:     }
                    123:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  124: 
1.146     albertel  125:     my @stores;
1.439     albertel  126:     foreach my $part (@{ $partlist }) {
1.146     albertel  127: 	foreach my $key (@metakeys) {
                    128: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    129: 	}
                    130:     }
                    131:     return @stores;
1.2       albertel  132: }
                    133: 
1.129     ng        134: #--- Format fullname, username:domain if different for display
                    135: #--- Use anywhere where the student names are listed
                    136: sub nameUserString {
                    137:     my ($type,$fullname,$uname,$udom) = @_;
                    138:     if ($type eq 'header') {
1.485     albertel  139: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        140:     } else {
1.398     albertel  141: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    142: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        143:     }
                    144: }
                    145: 
1.44      ng        146: #--- Get the partlist and the response type for a given problem. ---
                    147: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       148: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        149: sub response_type {
1.582     raeburn   150:     my ($symb,$response_error) = @_;
1.377     albertel  151: 
                    152:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   153:     unless (ref($navmap)) {
                    154:         if (ref($response_error)) {
                    155:             $$response_error = 1;
                    156:         }
                    157:         return;
                    158:     }
1.377     albertel  159:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   160:     unless (ref($res)) {
                    161:         $$response_error = 1;
                    162:         return;
                    163:     }
1.377     albertel  164:     my $partlist = $res->parts();
1.392     albertel  165:     my %vPart = 
                    166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  167:     my (%response_types,%handgrade);
                    168:     foreach my $part (@{ $partlist }) {
1.392     albertel  169: 	next if (%vPart && !exists($vPart{$part}));
                    170: 
1.377     albertel  171: 	my @types = $res->responseType($part);
                    172: 	my @ids = $res->responseIds($part);
                    173: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    174: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    175: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    176: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    177: 				     '.handgrade',$symb);
1.41      ng        178: 	}
                    179:     }
1.377     albertel  180:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        181: }
                    182: 
1.375     albertel  183: sub flatten_responseType {
                    184:     my ($responseType) = @_;
                    185:     my @part_response_id =
                    186: 	map { 
                    187: 	    my $part = $_;
                    188: 	    map {
                    189: 		[$part,$_]
                    190: 		} sort(keys(%{ $responseType->{$part} }));
                    191: 	} sort(keys(%$responseType));
                    192:     return @part_response_id;
                    193: }
                    194: 
1.207     albertel  195: sub get_display_part {
1.324     albertel  196:     my ($partID,$symb)=@_;
1.207     albertel  197:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    198:     if (defined($display) and $display ne '') {
1.577     bisitz    199:         $display.= ' (<span class="LC_internal_info">'
                    200:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  201:     } else {
                    202: 	$display=$partID;
                    203:     }
                    204:     return $display;
                    205: }
1.269     raeburn   206: 
1.434     albertel  207: sub reset_caches {
                    208:     &reset_analyze_cache();
                    209:     &reset_perm();
1.674     raeburn   210:     &reset_old_essays();
1.434     albertel  211: }
                    212: 
                    213: {
                    214:     my %analyze_cache;
1.557     raeburn   215:     my %analyze_cache_formkeys;
1.148     albertel  216: 
1.434     albertel  217:     sub reset_analyze_cache {
                    218: 	undef(%analyze_cache);
1.557     raeburn   219:         undef(%analyze_cache_formkeys);
1.434     albertel  220:     }
                    221: 
                    222:     sub get_analyze {
1.649     raeburn   223: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  224: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   225:         if ($type eq 'randomizetry') {
                    226:             if ($trial ne '') {
                    227:                 $key .= "\0".$trial;
                    228:             }
                    229:         }
1.557     raeburn   230: 	if (exists($analyze_cache{$key})) {
                    231:             my $getupdate = 0;
                    232:             if (ref($add_to_hash) eq 'HASH') {
                    233:                 foreach my $item (keys(%{$add_to_hash})) {
                    234:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    235:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    236:                             $getupdate = 1;
                    237:                             last;
                    238:                         }
                    239:                     } else {
                    240:                         $getupdate = 1;
                    241:                     }
                    242:                 }
                    243:             }
                    244:             if (!$getupdate) {
                    245:                 return $analyze_cache{$key};
                    246:             }
                    247:         }
1.434     albertel  248: 
                    249: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    250: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   251:         my %form = ('grade_target'      => 'analyze',
                    252:                     'grade_domain'      => $udom,
                    253:                     'grade_symb'        => $symb,
                    254:                     'grade_courseid'    =>  $env{'request.course.id'},
                    255:                     'grade_username'    => $uname,
                    256:                     'grade_noincrement' => $no_increment);
1.649     raeburn   257:         if ($bubbles_per_row ne '') {
                    258:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    259:         }
1.640     raeburn   260:         if ($type eq 'randomizetry') {
                    261:             $form{'grade_questiontype'} = $type;
                    262:             if ($rndseed ne '') {
                    263:                 $form{'grade_rndseed'} = $rndseed;
                    264:             }
                    265:         }
1.557     raeburn   266:         if (ref($add_to_hash)) {
                    267:             %form = (%form,%{$add_to_hash});
1.640     raeburn   268:         }
1.557     raeburn   269: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  270: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    271: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   272:         if (ref($add_to_hash) eq 'HASH') {
                    273:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    274:         } else {
                    275:             $analyze_cache_formkeys{$key} = {};
                    276:         }
1.434     albertel  277: 	return $analyze_cache{$key} = \%analyze;
                    278:     }
                    279: 
                    280:     sub get_order {
1.640     raeburn   281: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    282: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  283: 	return $analyze->{"$partid.$respid.shown"};
                    284:     }
                    285: 
                    286:     sub get_radiobutton_correct_foil {
1.640     raeburn   287: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    288: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    289:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   290:         if (ref($foils) eq 'ARRAY') {
                    291: 	    foreach my $foil (@{$foils}) {
                    292: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    293: 		    return $foil;
                    294: 	        }
1.434     albertel  295: 	    }
                    296: 	}
                    297:     }
1.554     raeburn   298: 
                    299:     sub scantron_partids_tograde {
1.741     raeburn   300:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   301:         my (%analysis,@parts);
                    302:         if (ref($resource)) {
                    303:             my $symb = $resource->symb();
1.557     raeburn   304:             my $add_to_form;
                    305:             if ($check_for_randomlist) {
                    306:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    307:             }
1.741     raeburn   308:             if ($scancode) {
                    309:                 if (ref($add_to_form) eq 'HASH') {
                    310:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    311:                 } else {
                    312:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    313:                 }
                    314:             }
1.649     raeburn   315:             my $analyze = 
                    316:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    317:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   318:             if (ref($analyze) eq 'HASH') {
                    319:                 %analysis = %{$analyze};
                    320:             }
                    321:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    322:                 foreach my $part (@{$analysis{'parts'}}) {
                    323:                     my ($id,$respid) = split(/\./,$part);
                    324:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    325:                         push(@parts,$part);
                    326:                     }
                    327:                 }
                    328:             }
                    329:         }
                    330:         return (\%analysis,\@parts);
                    331:     }
                    332: 
1.148     albertel  333: }
1.434     albertel  334: 
1.118     ng        335: #--- Clean response type for display
1.335     albertel  336: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    337: #        response types only.
1.118     ng        338: sub cleanRecord {
1.336     albertel  339:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   340: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  341:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  342:     if ($response =~ /^(option|rank)$/) {
                    343: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     344:         my @answer = %answer;
                    345:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    347: 	my ($toprow,$bottomrow);
                    348: 	foreach my $foil (@$order) {
                    349: 	    if ($grading{$foil} == 1) {
                    350: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    351: 	    } else {
                    352: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    353: 	    }
1.398     albertel  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  355: 	}
                    356: 	return '<blockquote><table border="1">'.
1.466     albertel  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   359: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  360:     } elsif ($response eq 'match') {
                    361: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     362:         my @answer = %answer;
                    363:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  364: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    365: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    366: 	my ($toprow,$middlerow,$bottomrow);
                    367: 	foreach my $foil (@$order) {
                    368: 	    my $item=shift(@items);
                    369: 	    if ($grading{$foil} == 1) {
                    370: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  371: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  372: 	    } else {
                    373: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  374: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  375: 	    }
1.398     albertel  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        377: 	}
1.126     ng        378: 	return '<blockquote><table border="1">'.
1.466     albertel  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  381: 	    $middlerow.'</tr>'.
1.466     albertel  382: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   383: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  384:     } elsif ($response eq 'radiobutton') {
                    385: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     386:         my @answer = %answer;
                    387:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  388: 	my ($toprow,$bottomrow);
1.434     albertel  389: 	my $correct = 
1.640     raeburn   390: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  391: 	foreach my $foil (@$order) {
1.148     albertel  392: 	    if (exists($answer{$foil})) {
1.434     albertel  393: 		if ($foil eq $correct) {
1.466     albertel  394: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  395: 		} else {
1.466     albertel  396: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  397: 		}
                    398: 	    } else {
1.466     albertel  399: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  400: 	    }
1.398     albertel  401: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  402: 	}
                    403: 	return '<blockquote><table border="1">'.
1.466     albertel  404: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    405: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   406: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  407:     } elsif ($response eq 'essay') {
1.257     albertel  408: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        409: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  410: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    411: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        412: 
1.257     albertel  413: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    414: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    415: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    416: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    417: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    418: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        419: 	}
1.730     kruse     420: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     421: 
1.268     albertel  422:     } elsif ( $response eq 'organic') {
1.721     bisitz    423:         my $result=&mt('Smile representation: [_1]',
                    424:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  425: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    426: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    427: 	return $result;
1.335     albertel  428:     } elsif ( $response eq 'Task') {
                    429: 	if ( $answer eq 'SUBMITTED') {
                    430: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  431: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  432: 	    return $result;
                    433: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    434: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    435: 			       keys(%{$record}));
                    436: 	    return join('<br />',($version,@matches));
                    437: 			       
                    438: 			       
                    439: 	} else {
                    440: 	    my $result =
                    441: 		'<p>'
                    442: 		.&mt('Overall result: [_1]',
                    443: 		     $record->{$version."resource.$respid.$partid.status"})
                    444: 		.'</p>';
                    445: 	    
                    446: 	    $result .= '<ul>';
                    447: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    448: 			     keys(%{$record}));
                    449: 	    foreach my $grade (sort(@grade)) {
                    450: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    451: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    452: 				     $dim, $record->{$grade}).
                    453: 			  '</li>';
                    454: 	    }
                    455: 	    $result.='</ul>';
                    456: 	    return $result;
                    457: 	}
1.716     bisitz    458:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    459:         # Respect multiple input fields, see Bug #5409
1.440     albertel  460: 	$answer = 
                    461: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    462: 							      $answer);
1.720     kruse     463: 	return $answer;
1.122     ng        464:     }
1.720     kruse     465:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        466: }
                    467: 
                    468: #-- A couple of common js functions
                    469: sub commonJSfunctions {
                    470:     my $request = shift;
1.597     wenzelju  471:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        472:     function radioSelection(radioButton) {
                    473: 	var selection=null;
                    474: 	if (radioButton.length > 1) {
                    475: 	    for (var i=0; i<radioButton.length; i++) {
                    476: 		if (radioButton[i].checked) {
                    477: 		    return radioButton[i].value;
                    478: 		}
                    479: 	    }
                    480: 	} else {
                    481: 	    if (radioButton.checked) return radioButton.value;
                    482: 	}
                    483: 	return selection;
                    484:     }
                    485: 
                    486:     function pullDownSelection(selectOne) {
                    487: 	var selection="";
                    488: 	if (selectOne.length > 1) {
                    489: 	    for (var i=0; i<selectOne.length; i++) {
                    490: 		if (selectOne[i].selected) {
                    491: 		    return selectOne[i].value;
                    492: 		}
                    493: 	    }
                    494: 	} else {
1.138     albertel  495:             // only one value it must be the selected one
                    496: 	    return selectOne.value;
1.118     ng        497: 	}
                    498:     }
                    499: COMMONJSFUNCTIONS
                    500: }
                    501: 
1.44      ng        502: #--- Dumps the class list with usernames,list of sections,
                    503: #--- section, ids and fullnames for each user.
                    504: sub getclasslist {
1.449     banghart  505:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  506:     my @getsec;
1.450     banghart  507:     my @getgroup;
1.442     banghart  508:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  509:     if (!ref($getsec)) {
                    510: 	if ($getsec ne '' && $getsec ne 'all') {
                    511: 	    @getsec=($getsec);
                    512: 	}
                    513:     } else {
                    514: 	@getsec=@{$getsec};
                    515:     }
                    516:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  517:     if (!ref($getgroup)) {
                    518: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    519: 	    @getgroup=($getgroup);
                    520: 	}
                    521:     } else {
                    522: 	@getgroup=@{$getgroup};
                    523:     }
                    524:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  525: 
1.449     banghart  526:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  527:     # Bail out if we were unable to get the classlist
1.56      matthew   528:     return if (! defined($classlist));
1.449     banghart  529:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   530:     #
                    531:     my %sections;
                    532:     my %fullnames;
1.205     matthew   533:     foreach my $student (keys(%$classlist)) {
                    534:         my $end      = 
                    535:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    536:         my $start    = 
                    537:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    538:         my $id       = 
                    539:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    540:         my $section  = 
                    541:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    542:         my $fullname = 
                    543:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    544:         my $status   = 
                    545:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  546:         my $group   = 
                    547:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        548: 	# filter students according to status selected
1.442     banghart  549: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    550: 	    if (!($stu_status =~ $status)) {
1.450     banghart  551: 		delete($classlist->{$student});
1.76      ng        552: 		next;
                    553: 	    }
                    554: 	}
1.450     banghart  555: 	# filter students according to groups selected
1.453     banghart  556: 	my @stu_groups = split(/,/,$group);
1.450     banghart  557: 	if (@getgroup) {
                    558: 	    my $exclude = 1;
1.454     banghart  559: 	    foreach my $grp (@getgroup) {
                    560: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  561: 	            if ($stu_group eq $grp) {
                    562: 	                $exclude = 0;
                    563:     	            } 
1.450     banghart  564: 	        }
1.453     banghart  565:     	        if (($grp eq 'none') && !$group) {
                    566:         	        $exclude = 0;
                    567:         	}
1.450     banghart  568: 	    }
                    569: 	    if ($exclude) {
                    570: 	        delete($classlist->{$student});
                    571: 	    }
                    572: 	}
1.205     matthew   573: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  574: 	if (&canview($section)) {
1.291     albertel  575: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  576: 		$sections{$section}++;
1.450     banghart  577: 		if ($classlist->{$student}) {
                    578: 		    $fullnames{$student}=$fullname;
                    579: 		}
1.103     albertel  580: 	    } else {
1.205     matthew   581: 		delete($classlist->{$student});
1.103     albertel  582: 	    }
                    583: 	} else {
1.205     matthew   584: 	    delete($classlist->{$student});
1.103     albertel  585: 	}
1.44      ng        586:     }
                    587:     my %seen = ();
1.56      matthew   588:     my @sections = sort(keys(%sections));
                    589:     return ($classlist,\@sections,\%fullnames);
1.44      ng        590: }
                    591: 
1.103     albertel  592: sub canmodify {
                    593:     my ($sec)=@_;
                    594:     if ($perm{'mgr'}) {
                    595: 	if (!defined($perm{'mgr_section'})) {
                    596: 	    # can modify whole class
                    597: 	    return 1;
                    598: 	} else {
                    599: 	    if ($sec eq $perm{'mgr_section'}) {
                    600: 		#can modify the requested section
                    601: 		return 1;
                    602: 	    } else {
                    603: 		# can't modify the request section
                    604: 		return 0;
                    605: 	    }
                    606: 	}
                    607:     }
                    608:     #can't modify
                    609:     return 0;
                    610: }
                    611: 
                    612: sub canview {
                    613:     my ($sec)=@_;
                    614:     if ($perm{'vgr'}) {
                    615: 	if (!defined($perm{'vgr_section'})) {
                    616: 	    # can modify whole class
                    617: 	    return 1;
                    618: 	} else {
                    619: 	    if ($sec eq $perm{'vgr_section'}) {
                    620: 		#can modify the requested section
                    621: 		return 1;
                    622: 	    } else {
                    623: 		# can't modify the request section
                    624: 		return 0;
                    625: 	    }
                    626: 	}
                    627:     }
                    628:     #can't modify
                    629:     return 0;
                    630: }
                    631: 
1.44      ng        632: #--- Retrieve the grade status of a student for all the parts
                    633: sub student_gradeStatus {
1.324     albertel  634:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  635:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        636:     my %partstatus = ();
                    637:     foreach (@$partlist) {
1.128     ng        638: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        639: 	$status              = 'nothing' if ($status eq '');
                    640: 	$partstatus{$_}      = $status;
                    641: 	my $subkey           = "resource.$_.submitted_by";
                    642: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    643:     }
                    644:     return %partstatus;
                    645: }
                    646: 
1.45      ng        647: # hidden form and javascript that calls the form
                    648: # Use by verifyscript and viewgrades
                    649: # Shows a student's view of problem and submission
                    650: sub jscriptNform {
1.324     albertel  651:     my ($symb) = @_;
1.442     banghart  652:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  653:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        654: 	'    function viewOneStudent(user,domain) {'."\n".
                    655: 	'	document.onestudent.student.value = user;'."\n".
                    656: 	'	document.onestudent.userdom.value = domain;'."\n".
                    657: 	'	document.onestudent.submit();'."\n".
                    658: 	'    }'."\n".
1.597     wenzelju  659: 	"\n");
1.45      ng        660:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  661: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  662: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        663: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    664: 	'<input type="hidden" name="student" value="" />'."\n".
                    665: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    666: 	'</form>'."\n";
                    667:     return $jscript;
                    668: }
1.39      ng        669: 
1.447     foxr      670: 
                    671: 
1.315     bowersj2  672: # Given the score (as a number [0-1] and the weight) what is the final
                    673: # point value? This function will round to the nearest tenth, third,
                    674: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  675: sub compute_points {
1.315     bowersj2  676:     my ($score, $weight) = @_;
                    677:     
                    678:     my $tolerance = .00001;
                    679:     my $points = $score * $weight;
                    680: 
                    681:     # Check for nearness to 1/x.
                    682:     my $check_for_nearness = sub {
                    683:         my ($factor) = @_;
                    684:         my $num = ($points * $factor) + $tolerance;
                    685:         my $floored_num = floor($num);
1.316     albertel  686:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  687:             return $floored_num / $factor;
                    688:         }
                    689:         return $points;
                    690:     };
                    691: 
                    692:     $points = $check_for_nearness->(10);
                    693:     $points = $check_for_nearness->(3);
                    694:     $points = $check_for_nearness->(4);
                    695:     
                    696:     return $points;
                    697: }
                    698: 
1.44      ng        699: #------------------ End of general use routines --------------------
1.87      www       700: 
                    701: #
                    702: # Find most similar essay
                    703: #
                    704: 
                    705: sub most_similar {
1.674     raeburn   706:     my ($uname,$udom,$symb,$uessay)=@_;
                    707: 
                    708:     unless ($symb) { return ''; }
                    709: 
                    710:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       711: 
                    712: # ignore spaces and punctuation
                    713: 
                    714:     $uessay=~s/\W+/ /gs;
                    715: 
1.282     www       716: # ignore empty submissions (occuring when only files are sent)
                    717: 
1.598     www       718:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       719: 
1.87      www       720: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       721:     my $limit=0.6;
1.87      www       722:     my $sname='';
                    723:     my $sdom='';
                    724:     my $scrsid='';
                    725:     my $sessay='';
                    726: # go through all essays ...
1.674     raeburn   727:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  728: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       729: # ... except the same student
1.426     albertel  730:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   731: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  732: 	$tessay=~s/\W+/ /gs;
1.87      www       733: # String similarity gives up if not even limit
1.426     albertel  734: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       735: # Found one
1.426     albertel  736: 	if ($tsimilar>$limit) {
                    737: 	    $limit=$tsimilar;
                    738: 	    $sname=$tname;
                    739: 	    $sdom=$tdom;
                    740: 	    $scrsid=$tcrsid;
1.674     raeburn   741: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  742: 	}
1.87      www       743:     }
1.88      www       744:     if ($limit>0.6) {
1.87      www       745:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    746:     } else {
                    747:        return ('','','','',0);
                    748:     }
                    749: }
                    750: 
1.44      ng        751: #-------------------------------------------------------------------
                    752: 
                    753: #------------------------------------ Receipt Verification Routines
1.45      ng        754: #
1.602     www       755: 
                    756: sub initialverifyreceipt {
1.608     www       757:    my ($request,$symb) = @_;
1.602     www       758:    &commonJSfunctions($request);
1.694     bisitz    759:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       760:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    761:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       762:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    763:         '<input type="hidden" name="command" value="verify" />'.
                    764:         "</form>\n";
1.602     www       765: }
                    766: 
1.44      ng        767: #--- Check whether a receipt number is valid.---
                    768: sub verifyreceipt {
1.608     www       769:     my ($request,$symb)  = @_;
1.44      ng        770: 
1.257     albertel  771:     my $courseid = $env{'request.course.id'};
1.184     www       772:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  773: 	$env{'form.receipt'};
1.44      ng        774:     $receipt     =~ s/[^\-\d]//g;
                    775: 
1.487     albertel  776:     my $title.=
                    777: 	'<h3><span class="LC_info">'.
1.605     www       778: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    779: 	'</span></h3>'."\n";
1.44      ng        780: 
                    781:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   782:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  783:     
                    784:     my $receiptparts=0;
1.390     albertel  785:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    786: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  787:     my $parts=['0'];
1.582     raeburn   788:     if ($receiptparts) {
                    789:         my $res_error; 
                    790:         ($parts)=&response_type($symb,\$res_error);
                    791:         if ($res_error) {
                    792:             return &navmap_errormsg();
                    793:         } 
                    794:     }
1.486     albertel  795:     
                    796:     my $header = 
                    797: 	&Apache::loncommon::start_data_table().
                    798: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  799: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    800: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    801: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  802:     if ($receiptparts) {
1.487     albertel  803: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  804:     }
                    805:     $header.=
                    806: 	&Apache::loncommon::end_data_table_header_row();
                    807: 
1.294     albertel  808:     foreach (sort 
                    809: 	     {
                    810: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    811: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    812: 		 }
                    813: 		 return $a cmp $b;
                    814: 	     } (keys(%$fullname))) {
1.44      ng        815: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  816: 	foreach my $part (@$parts) {
                    817: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  818: 		$contents.=
                    819: 		    &Apache::loncommon::start_data_table_row().
                    820: 		    '<td>&nbsp;'."\n".
1.177     albertel  821: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  822: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  823: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    824: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    825: 		if ($receiptparts) {
                    826: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    827: 		}
1.486     albertel  828: 		$contents.= 
                    829: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  830: 		
                    831: 		$matches++;
                    832: 	    }
1.44      ng        833: 	}
                    834:     }
                    835:     if ($matches == 0) {
1.584     bisitz    836:         $string = $title
                    837:                  .'<p class="LC_warning">'
                    838:                  .&mt('No match found for the above receipt number.')
                    839:                  .'</p>';
1.44      ng        840:     } else {
1.324     albertel  841: 	$string = &jscriptNform($symb).$title.
1.487     albertel  842: 	    '<p>'.
1.584     bisitz    843: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  844: 	    '</p>'.
1.486     albertel  845: 	    $header.
                    846: 	    $contents.
                    847: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        848:     }
1.614     www       849:     return $string;
1.44      ng        850: }
                    851: 
                    852: #--- This is called by a number of programs.
                    853: #--- Called from the Grading Menu - View/Grade an individual student
                    854: #--- Also called directly when one clicks on the subm button 
                    855: #    on the problem page.
1.30      ng        856: sub listStudents {
1.617     www       857:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  858: 
1.747     raeburn   859:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel  860:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    861:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    862:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  863:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       864:     unless ($submitonly) {
                    865:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    866:     }
1.49      albertel  867: 
1.632     www       868:     my $result='';
1.623     www       869:     my $res_error;
                    870:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  871: 
1.736     damieng   872:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   873: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    874: 		'single'   => 'Please select the student before clicking on the Next button.',
                    875: 	     );
1.736     damieng   876:     &js_escape(\%js_lt);
1.597     wenzelju  877:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        878:     function checkSelect(checkBox) {
                    879: 	var ctr=0;
                    880: 	var sense="";
                    881: 	if (checkBox.length > 1) {
                    882: 	    for (var i=0; i<checkBox.length; i++) {
                    883: 		if (checkBox[i].checked) {
                    884: 		    ctr++;
                    885: 		}
                    886: 	    }
1.736     damieng   887: 	    sense = '$js_lt{'multiple'}';
1.110     ng        888: 	} else {
                    889: 	    if (checkBox.checked) {
                    890: 		ctr = 1;
                    891: 	    }
1.736     damieng   892: 	    sense = '$js_lt{'single'}';
1.110     ng        893: 	}
                    894: 	if (ctr == 0) {
1.485     albertel  895: 	    alert(sense);
1.110     ng        896: 	    return false;
                    897: 	}
                    898: 	document.gradesub.submit();
                    899:     }
                    900: 
                    901:     function reLoadList(formname) {
1.112     ng        902: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        903: 	formname.command.value = 'submission';
                    904: 	formname.submit();
                    905:     }
1.45      ng        906: LISTJAVASCRIPT
                    907: 
1.118     ng        908:     &commonJSfunctions($request);
1.41      ng        909:     $request->print($result);
1.39      ng        910: 
1.154     albertel  911:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       912: 	"\n";
1.485     albertel  913: 	
1.561     bisitz    914:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn   915:     unless ($is_tool) {
                    916:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    917:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    918:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    919:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    920:                       .&Apache::lonhtmlcommon::row_closure();
                    921:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    922:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    923:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    924:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    925:                       .&Apache::lonhtmlcommon::row_closure();
                    926:     }
1.485     albertel  927: 
                    928:     my $submission_options;
1.442     banghart  929:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    930:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  931:     $env{'form.Status'} = $saveStatus;
1.745     raeburn   932:     my %optiontext;
                    933:     if ($is_tool) {
                    934:         %optiontext = &Apache::lonlocal::texthash (
                    935:                           lastonly => 'last transaction',
                    936:                           last     => 'last transaction with details',
                    937:                           datesub  => 'all transactions',
                    938:                           all      => 'all transactions with details',
                    939:                       );
                    940:     } else {
                    941:         %optiontext = &Apache::lonlocal::texthash (
                    942:                           lastonly => 'last submission',
                    943:                           last     => 'last submission with details',
                    944:                           datesub  => 'all submissions',
                    945:                           all      => 'all submissions with details',
                    946:                       );
                    947:     }
1.485     albertel  948:     $submission_options.=
1.592     bisitz    949:         '<span class="LC_nobreak">'.
1.624     www       950:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn   951:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz    952:         '<span class="LC_nobreak">'.
                    953:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn   954:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz    955:         '<span class="LC_nobreak">'.
1.628     www       956:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn   957:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz    958:         '<span class="LC_nobreak">'.
                    959:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn   960:         $optiontext{'all'}.'</label></span>';
                    961:     my $viewtitle;
                    962:     if ($is_tool) {
                    963:         $viewtitle = &mt('View Transactions');
                    964:     } else {
                    965:         $viewtitle = &mt('View Submissions');
                    966:     }
                    967:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz    968:                   .$submission_options
                    969:                   .&Apache::lonhtmlcommon::row_closure();
                    970: 
1.745     raeburn   971:     my $closure;
                    972:     if (($is_tool) && (exists($env{'form.Status'}))) {
                    973:         $closure = 1;
                    974:     }
1.561     bisitz    975:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    976:                   .'<select name="increment">'
                    977:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    978:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    979:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    980:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    981:                   .'</select>'
1.745     raeburn   982:                   .&Apache::lonhtmlcommon::row_closure($closure);
1.485     albertel  983: 
                    984:     $gradeTable .= 
1.432     banghart  985:         &build_section_inputs().
1.45      ng        986: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  987: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        988: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    989: 
1.618     www       990:     if (exists($env{'form.Status'})) {
1.561     bisitz    991: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        992:     } else {
1.745     raeburn   993:         if ($is_tool) {
                    994:             $closure = 1;
                    995:         }
1.561     bisitz    996:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    997:                       .&Apache::lonhtmlcommon::StatusOptions(
                    998:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1.745     raeburn   999:                       .&Apache::lonhtmlcommon::row_closure($closure);
1.124     ng       1000:     }
1.112     ng       1001: 
1.745     raeburn  1002:     unless ($is_tool) {
                   1003:         $closure = 1;
                   1004:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1005:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1006:                       .&Apache::lonhtmlcommon::row_closure($closure);
                   1007:     }
                   1008:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
                   1009:     my $regrademsg;
                   1010:     if ($is_tool) {
                   1011:         $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.");
                   1012:     } else {
                   1013:         $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.");
                   1014:     }
1.561     bisitz   1015:     $gradeTable .= '<p>'
1.745     raeburn  1016:                   .$regrademsg."\n"
1.561     bisitz   1017:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1018:                   .'</p>';
1.249     albertel 1019: 
                   1020: # checkall buttons
                   1021:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1022:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1023:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1024:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1025:     $gradeTable.=&check_buttons();
1.450     banghart 1026:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1027:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1028: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1029:     my $loop = 0;
                   1030:     while ($loop < 2) {
1.485     albertel 1031: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1032: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1033: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1034: 	    foreach my $part (sort(@$partlist)) {
                   1035: 		my $display_part=
                   1036: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1037: 		$gradeTable.=
                   1038: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1039: 	    }
1.301     albertel 1040: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1041: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1042: 	}
                   1043: 	$loop++;
1.126     ng       1044: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1045:     }
1.474     albertel 1046:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1047: 
1.45      ng       1048:     my $ctr = 0;
1.294     albertel 1049:     foreach my $student (sort 
                   1050: 			 {
                   1051: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1052: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1053: 			     }
                   1054: 			     return $a cmp $b;
                   1055: 			 }
                   1056: 			 (keys(%$fullname))) {
1.41      ng       1057: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1058: 
1.110     ng       1059: 	my %status = ();
1.301     albertel 1060: 
                   1061: 	if ($submitonly eq 'queued') {
                   1062: 	    my %queue_status = 
                   1063: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1064: 							$udom,$uname);
                   1065: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1066: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1067: 	}
                   1068: 
1.618     www      1069: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1070: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1071: 	    my $submitted = 0;
1.164     albertel 1072: 	    my $graded = 0;
1.248     albertel 1073: 	    my $incorrect = 0;
1.110     ng       1074: 	    foreach (keys(%status)) {
1.145     albertel 1075: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1076: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1077: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1078: 		
1.110     ng       1079: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1080: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1081: 		    $submitted = 0;
1.150     albertel 1082: 		    my ($part)=split(/\./,$partid);
1.110     ng       1083: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1084: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1085: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1086: 		}
1.41      ng       1087: 	    }
1.248     albertel 1088: 	    
1.156     albertel 1089: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1090: 				     $submitonly eq 'incorrect' ||
                   1091: 				     $submitonly eq 'graded'));
1.248     albertel 1092: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1093: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1094: 	}
1.34      ng       1095: 
1.45      ng       1096: 	$ctr++;
1.249     albertel 1097: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1098:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1099: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1100: 	    if ($ctr%2 ==1) {
                   1101: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1102: 	    }
1.126     ng       1103: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1104:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1105:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1106: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1107: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1108: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1109: 
1.618     www      1110: 	    if ($submitonly ne 'all') {
1.524     raeburn  1111: 		foreach (sort(keys(%status))) {
1.485     albertel 1112: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1113: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1114: 		}
1.41      ng       1115: 	    }
1.126     ng       1116: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1117: 	    if ($ctr%2 ==0) {
                   1118: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1119: 	    }
1.41      ng       1120: 	}
                   1121:     }
1.110     ng       1122:     if ($ctr%2 ==1) {
1.126     ng       1123: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1124: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1125: 		foreach (@$partlist) {
                   1126: 		    $gradeTable.='<td>&nbsp;</td>';
                   1127: 		}
1.301     albertel 1128: 	    } elsif ($submitonly eq 'queued') {
                   1129: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1130: 	    }
1.474     albertel 1131: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1132:     }
                   1133: 
1.474     albertel 1134:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1135:         '<input type="button" '.
                   1136:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1137:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1138:     if ($ctr == 0) {
1.96      albertel 1139: 	my $num_students=(scalar(keys(%$fullname)));
                   1140: 	if ($num_students eq 0) {
1.485     albertel 1141: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1142: 	} else {
1.171     albertel 1143: 	    my $submissions='submissions';
                   1144: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1145: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1146: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1147: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1148: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1149: 		    $num_students).
                   1150: 		'</span><br />';
1.96      albertel 1151: 	}
1.46      ng       1152:     } elsif ($ctr == 1) {
1.474     albertel 1153: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1154:     }
                   1155:     $request->print($gradeTable);
1.44      ng       1156:     return '';
1.10      ng       1157: }
                   1158: 
1.44      ng       1159: #---- Called from the listStudents routine
1.249     albertel 1160: 
                   1161: sub check_script {
                   1162:     my ($form, $type)=@_;
1.597     wenzelju 1163:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1164:     function checkall() {
                   1165:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1166:             ele = document.forms.'.$form.'.elements[i];
                   1167:             if (ele.name == "'.$type.'") {
                   1168:             document.forms.'.$form.'.elements[i].checked=true;
                   1169:                                        }
                   1170:         }
                   1171:     }
                   1172: 
                   1173:     function checksec() {
                   1174:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1175:             ele = document.forms.'.$form.'.elements[i];
                   1176:            string = document.forms.'.$form.'.chksec.value;
                   1177:            if
                   1178:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1179:               document.forms.'.$form.'.elements[i].checked=true;
                   1180:             }
                   1181:         }
                   1182:     }
                   1183: 
                   1184: 
                   1185:     function uncheckall() {
                   1186:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1187:             ele = document.forms.'.$form.'.elements[i];
                   1188:             if (ele.name == "'.$type.'") {
                   1189:             document.forms.'.$form.'.elements[i].checked=false;
                   1190:                                        }
                   1191:         }
                   1192:     }
                   1193: 
1.597     wenzelju 1194: '."\n");
1.249     albertel 1195:     return $chkallscript;
                   1196: }
                   1197: 
                   1198: sub check_buttons {
1.485     albertel 1199:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1200:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1201:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1202:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1203:     return $buttons;
                   1204: }
                   1205: 
1.44      ng       1206: #     Displays the submissions for one student or a group of students
1.34      ng       1207: sub processGroup {
1.619     www      1208:     my ($request,$symb)  = @_;
1.41      ng       1209:     my $ctr        = 0;
1.155     albertel 1210:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1211:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1212: 
1.396     banghart 1213:     foreach my $student (@stuchecked) {
                   1214: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1215: 	$env{'form.student'}        = $uname;
                   1216: 	$env{'form.userdom'}        = $udom;
                   1217: 	$env{'form.fullname'}       = $fullname;
1.619     www      1218: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1219: 	$ctr++;
                   1220:     }
                   1221:     return '';
1.35      ng       1222: }
1.34      ng       1223: 
1.44      ng       1224: #------------------------------------------------------------------------------------
                   1225: #
                   1226: #-------------------------- Next few routines handles grading by student, essentially
                   1227: #                           handles essay response type problem/part
                   1228: #
                   1229: #--- Javascript to handle the submission page functionality ---
                   1230: sub sub_page_js {
                   1231:     my $request = shift;
1.736     damieng  1232:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1233:     &js_escape(\$alertmsg);
1.597     wenzelju 1234:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1235:     function updateRadio(formname,id,weight) {
1.125     ng       1236: 	var gradeBox = formname["GD_BOX"+id];
                   1237: 	var radioButton = formname["RADVAL"+id];
                   1238: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1239: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1240: 	gradeBox.value = pts;
                   1241: 	var resetbox = false;
                   1242: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1243: 	    alert("$alertmsg"+pts);
1.71      ng       1244: 	    for (var i=0; i<radioButton.length; i++) {
                   1245: 		if (radioButton[i].checked) {
                   1246: 		    gradeBox.value = i;
                   1247: 		    resetbox = true;
                   1248: 		}
                   1249: 	    }
                   1250: 	    if (!resetbox) {
                   1251: 		formtextbox.value = "";
                   1252: 	    }
                   1253: 	    return;
1.44      ng       1254: 	}
1.71      ng       1255: 
                   1256: 	if (pts > weight) {
                   1257: 	    var resp = confirm("You entered a value ("+pts+
                   1258: 			       ") greater than the weight for the part. Accept?");
                   1259: 	    if (resp == false) {
1.125     ng       1260: 		gradeBox.value = oldpts;
1.71      ng       1261: 		return;
                   1262: 	    }
1.44      ng       1263: 	}
1.13      albertel 1264: 
1.71      ng       1265: 	for (var i=0; i<radioButton.length; i++) {
                   1266: 	    radioButton[i].checked=false;
                   1267: 	    if (pts == i && pts != "") {
                   1268: 		radioButton[i].checked=true;
                   1269: 	    }
                   1270: 	}
                   1271: 	updateSelect(formname,id);
1.125     ng       1272: 	formname["stores"+id].value = "0";
1.41      ng       1273:     }
1.5       albertel 1274: 
1.72      ng       1275:     function writeBox(formname,id,pts) {
1.125     ng       1276: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1277: 	if (checkSolved(formname,id) == 'update') {
                   1278: 	    gradeBox.value = pts;
                   1279: 	} else {
1.125     ng       1280: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1281: 	    gradeBox.value = oldpts;
1.125     ng       1282: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1283: 	    for (var i=0; i<radioButton.length; i++) {
                   1284: 		radioButton[i].checked=false;
1.72      ng       1285: 		if (i == oldpts) {
1.71      ng       1286: 		    radioButton[i].checked=true;
                   1287: 		}
                   1288: 	    }
1.41      ng       1289: 	}
1.125     ng       1290: 	formname["stores"+id].value = "0";
1.71      ng       1291: 	updateSelect(formname,id);
                   1292: 	return;
1.41      ng       1293:     }
1.44      ng       1294: 
1.71      ng       1295:     function clearRadBox(formname,id) {
                   1296: 	if (checkSolved(formname,id) == 'noupdate') {
                   1297: 	    updateSelect(formname,id);
                   1298: 	    return;
                   1299: 	}
1.125     ng       1300: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1301: 	for (var i=0; i<gradeSelect.length; i++) {
                   1302: 	    if (gradeSelect[i].selected) {
                   1303: 		var selectx=i;
                   1304: 	    }
                   1305: 	}
1.125     ng       1306: 	var stores = formname["stores"+id];
1.71      ng       1307: 	if (selectx == stores.value) { return };
1.125     ng       1308: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1309: 	gradeBox.value = "";
1.125     ng       1310: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1311: 	for (var i=0; i<radioButton.length; i++) {
                   1312: 	    radioButton[i].checked=false;
                   1313: 	}
                   1314: 	stores.value = selectx;
                   1315:     }
1.5       albertel 1316: 
1.71      ng       1317:     function checkSolved(formname,id) {
1.125     ng       1318: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1319: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1320: 	    if (!reply) {return "noupdate";}
1.120     ng       1321: 	    formname.overRideScore.value = 'yes';
1.41      ng       1322: 	}
1.71      ng       1323: 	return "update";
1.13      albertel 1324:     }
1.71      ng       1325: 
                   1326:     function updateSelect(formname,id) {
1.125     ng       1327: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1328: 	return;
1.41      ng       1329:     }
1.33      ng       1330: 
1.121     ng       1331: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1332:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1333: 	formname.gradeOpt.value = val;
1.71      ng       1334: 	if (val == "Save & Next") {
                   1335: 	    for (i=0;i<=total;i++) {
                   1336: 		for (j=0;j<parttot;j++) {
1.125     ng       1337: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1338: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1339: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1340: 			if (points == "") {
1.125     ng       1341: 			    var name = formname["name"+i].value;
1.129     ng       1342: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1343: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1344: 					       ", part "+partid+". Continue?");
1.71      ng       1345: 			    if (resp == false) {
1.125     ng       1346: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1347: 				return false;
                   1348: 			    }
                   1349: 			}
                   1350: 		    }
                   1351: 		}
                   1352: 	    }
                   1353: 	}
1.120     ng       1354: 	formname.submit();
                   1355:     }
                   1356: 
1.71      ng       1357: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1358:     function checkSubmitPage(formname,total) {
                   1359: 	noscore = new Array(100);
                   1360: 	var ptr = 0;
                   1361: 	for (i=1;i<total;i++) {
1.125     ng       1362: 	    var partid = formname["q_"+i].value;
1.127     ng       1363: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1364: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1365: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1366: 		if (points == "" && status != "correct_by_student") {
                   1367: 		    noscore[ptr] = i;
                   1368: 		    ptr++;
                   1369: 		}
                   1370: 	    }
                   1371: 	}
                   1372: 	if (ptr != 0) {
                   1373: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1374: 	    var prolist = "";
                   1375: 	    if (ptr == 1) {
                   1376: 		prolist = noscore[0];
                   1377: 	    } else {
                   1378: 		var i = 0;
                   1379: 		while (i < ptr-1) {
                   1380: 		    prolist += noscore[i]+", ";
                   1381: 		    i++;
                   1382: 		}
                   1383: 		prolist += "and "+noscore[i];
                   1384: 	    }
                   1385: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1386: 	    if (resp == false) {
                   1387: 		return false;
                   1388: 	    }
                   1389: 	}
1.45      ng       1390: 
1.71      ng       1391: 	formname.submit();
                   1392:     }
                   1393: SUBJAVASCRIPT
                   1394: }
1.45      ng       1395: 
1.71      ng       1396: #--- javascript for essay type problem --
                   1397: sub sub_page_kw_js {
                   1398:     my $request = shift;
1.80      ng       1399:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1400:     &commonJSfunctions($request);
1.350     albertel 1401: 
1.629     www      1402:     my $inner_js_msg_central= (<<INNERJS);
                   1403: <script type="text/javascript">
1.350     albertel 1404:     function checkInput() {
                   1405:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1406:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1407:       var usrctr = document.msgcenter.usrctr.value;
                   1408:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1409:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1410: 
                   1411:       var msgchk = "";
                   1412:       if (document.msgcenter.subchk.checked) {
                   1413:          msgchk = "msgsub,";
                   1414:       }
                   1415:       var includemsg = 0;
                   1416:       for (var i=1; i<=nmsg; i++) {
                   1417:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1418:           var frmmsg = document.msgcenter["msg"+i];
                   1419:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1420:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1421:           showflg.value = "1";
                   1422:           var chkbox = document.msgcenter["msgn"+i];
                   1423:           if (chkbox.checked) {
                   1424:              msgchk += "savemsg"+i+",";
                   1425:              includemsg = 1;
                   1426:           }
                   1427:       }
                   1428:       if (document.msgcenter.newmsgchk.checked) {
                   1429:          msgchk += "newmsg"+usrctr;
                   1430:          includemsg = 1;
                   1431:       }
                   1432:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1433:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1434:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1435:       includemsg.value = msgchk;
                   1436: 
                   1437:       self.close()
                   1438: 
                   1439:     }
1.629     www      1440: </script>
1.350     albertel 1441: INNERJS
                   1442: 
1.629     www      1443:     my $inner_js_highlight_central= (<<INNERJS);
                   1444: <script type="text/javascript">
1.351     albertel 1445:     function updateChoice(flag) {
                   1446:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1447:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1448:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1449:       opener.document.SCORE.refresh.value = "on";
                   1450:       if (opener.document.SCORE.keywords.value!=""){
                   1451:          opener.document.SCORE.submit();
                   1452:       }
                   1453:       self.close()
                   1454:     }
1.629     www      1455: </script>
1.351     albertel 1456: INNERJS
                   1457: 
                   1458:     my $start_page_msg_central = 
                   1459:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1460: 				       {'js_ready'  => 1,
                   1461: 					'only_body' => 1,
                   1462: 					'bgcolor'   =>'#FFFFFF',});
                   1463:     my $end_page_msg_central = 
                   1464: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1465: 
                   1466: 
                   1467:     my $start_page_highlight_central = 
                   1468:         &Apache::loncommon::start_page('Highlight Central',
                   1469: 				       $inner_js_highlight_central,
1.350     albertel 1470: 				       {'js_ready'  => 1,
                   1471: 					'only_body' => 1,
                   1472: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1473:     my $end_page_highlight_central = 
1.350     albertel 1474: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1475: 
1.219     www      1476:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1477:     $docopen=~s/^document\.//;
1.736     damieng  1478:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1479:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1480:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1481:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1482:                 col1 => 'red',
                   1483:                 col2 => 'green',
                   1484:                 col3 => 'blue',
                   1485:                 siz1 => 'normal',
                   1486:                 siz2 => '+1',
                   1487:                 siz3 => '+2',
                   1488:                 sty1 => 'normal',
                   1489:                 sty2 => 'italic',
                   1490:                 sty3 => 'bold',
                   1491:              );
                   1492:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1493:                 comp => 'Compose Message for: ',
                   1494:                 incl => 'Include',
1.656     raeburn  1495:                 type => 'Type',
1.652     raeburn  1496:                 subj => 'Subject',
                   1497:                 mesa => 'Message',
                   1498:                 new  => 'New',
                   1499:                 save => 'Save',
                   1500:                 canc => 'Cancel',
                   1501:                 kehi => 'Keyword Highlight Options',
                   1502:                 txtc => 'Text Color',
                   1503:                 font => 'Font Size',
1.656     raeburn  1504:                 fnst => 'Font Style',
1.652     raeburn  1505:              );
1.736     damieng  1506:     &js_escape(\%js_lt);
                   1507:     &html_escape(\%html_js_lt);
                   1508:     &js_escape(\%html_js_lt);
1.597     wenzelju 1509:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1510: 
1.44      ng       1511: //===================== Show list of keywords ====================
1.122     ng       1512:   function keywords(formname) {
1.736     damieng  1513:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1514:     if (nret==null) return;
1.122     ng       1515:     formname.keywords.value = nret;
1.44      ng       1516: 
1.122     ng       1517:     if (formname.keywords.value != "") {
1.128     ng       1518: 	formname.refresh.value = "on";
1.122     ng       1519: 	formname.submit();
1.44      ng       1520:     }
                   1521:     return;
                   1522:   }
                   1523: 
                   1524: //===================== Script to view submitted by ==================
                   1525:   function viewSubmitter(submitter) {
                   1526:     document.SCORE.refresh.value = "on";
                   1527:     document.SCORE.NCT.value = "1";
                   1528:     document.SCORE.unamedom0.value = submitter;
                   1529:     document.SCORE.submit();
                   1530:     return;
                   1531:   }
                   1532: 
                   1533: //===================== Script to add keyword(s) ==================
                   1534:   function getSel() {
                   1535:     if (document.getSelection) txt = document.getSelection();
                   1536:     else if (document.selection) txt = document.selection.createRange().text;
                   1537:     else return;
                   1538:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1539:     if (cleantxt=="") {
1.736     damieng  1540: 	alert("$js_lt{'plse'}");
1.44      ng       1541: 	return;
                   1542:     }
1.736     damieng  1543:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1544:     if (nret==null) return;
1.127     ng       1545:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1546:     if (document.SCORE.keywords.value != "") {
1.127     ng       1547: 	document.SCORE.refresh.value = "on";
1.44      ng       1548: 	document.SCORE.submit();
                   1549:     }
                   1550:     return;
                   1551:   }
                   1552: 
                   1553: //====================== Script for composing message ==============
1.80      ng       1554:    // preload images
                   1555:    img1 = new Image();
                   1556:    img1.src = "$iconpath/mailbkgrd.gif";
                   1557:    img2 = new Image();
                   1558:    img2.src = "$iconpath/mailto.gif";
                   1559: 
1.44      ng       1560:   function msgCenter(msgform,usrctr,fullname) {
                   1561:     var Nmsg  = msgform.savemsgN.value;
                   1562:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1563:     var subject = msgform.msgsub.value;
1.127     ng       1564:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1565:     re = /msgsub/;
                   1566:     var shwsel = "";
                   1567:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1568:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1569:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1570:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1571: 	var testmsg = "savemsg"+i+",";
                   1572: 	re = new RegExp(testmsg,"g");
1.44      ng       1573: 	shwsel = "";
                   1574: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1575: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1576: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1577: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1578: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1579:     }
1.125     ng       1580:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1581:     shwsel = "";
                   1582:     re = /newmsg/;
                   1583:     if (re.test(msgchk)) { shwsel = "checked" }
                   1584:     newMsg(newmsg,shwsel);
                   1585:     msgTail(); 
                   1586:     return;
                   1587:   }
                   1588: 
1.123     ng       1589:   function checkEntities(strx) {
                   1590:     if (strx.length == 0) return strx;
                   1591:     var orgStr = ["&", "<", ">", '"']; 
                   1592:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1593:     var counter = 0;
                   1594:     while (counter < 4) {
                   1595: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1596: 	counter++;
                   1597:     }
                   1598:     return strx;
                   1599:   }
                   1600: 
                   1601:   function strReplace(strx, orgStr, newStr) {
                   1602:     return strx.split(orgStr).join(newStr);
                   1603:   }
                   1604: 
1.44      ng       1605:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1606:     var height = 70*Nmsg+250;
1.44      ng       1607:     if (height > 600) {
                   1608: 	height = 600;
                   1609:     }
1.118     ng       1610:     var xpos = (screen.width-600)/2;
                   1611:     xpos = (xpos < 0) ? '0' : xpos;
                   1612:     var ypos = (screen.height-height)/2-30;
                   1613:     ypos = (ypos < 0) ? '0' : ypos;
                   1614: 
1.668     www      1615:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1616:     pWin.focus();
                   1617:     pDoc = pWin.document;
1.219     www      1618:     pDoc.$docopen;
1.351     albertel 1619:     pDoc.write('$start_page_msg_central');
1.76      ng       1620: 
                   1621:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1622:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1623:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1624: 
1.676     golterma 1625:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1626:     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       1627: }
                   1628:     function displaySubject(msg,shwsel) {
1.76      ng       1629:     pDoc = pWin.document;
1.676     golterma 1630:     pDoc.write("<tr>");
                   1631:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1632:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1633:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1634: }
                   1635: 
1.72      ng       1636:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1637:     pDoc = pWin.document;
1.676     golterma 1638:     pDoc.write("<tr>");
                   1639:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1640:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1641:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1642: }
                   1643: 
                   1644:   function newMsg(newmsg,shwsel) {
1.76      ng       1645:     pDoc = pWin.document;
1.676     golterma 1646:     pDoc.write("<tr>");
                   1647:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1648:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1649:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1650: }
                   1651: 
                   1652:   function msgTail() {
1.76      ng       1653:     pDoc = pWin.document;
1.676     golterma 1654:     //pDoc.write("<\\/table>");
1.465     albertel 1655:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1656:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1657:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1658:     pDoc.write("<\\/form>");
1.351     albertel 1659:     pDoc.write('$end_page_msg_central');
1.128     ng       1660:     pDoc.close();
1.44      ng       1661: }
                   1662: 
                   1663: //====================== Script for keyword highlight options ==============
                   1664:   function kwhighlight() {
                   1665:     var kwclr    = document.SCORE.kwclr.value;
                   1666:     var kwsize   = document.SCORE.kwsize.value;
                   1667:     var kwstyle  = document.SCORE.kwstyle.value;
                   1668:     var redsel = "";
                   1669:     var grnsel = "";
                   1670:     var blusel = "";
1.736     damieng  1671:     var txtcol1 = "$js_lt{'col1'}";
                   1672:     var txtcol2 = "$js_lt{'col2'}";
                   1673:     var txtcol3 = "$js_lt{'col3'}";
                   1674:     var txtsiz1 = "$js_lt{'siz1'}";
                   1675:     var txtsiz2 = "$js_lt{'siz2'}";
                   1676:     var txtsiz3 = "$js_lt{'siz3'}";
                   1677:     var txtsty1 = "$js_lt{'sty1'}";
                   1678:     var txtsty2 = "$js_lt{'sty2'}";
                   1679:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1680:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1681:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1682:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1683:     var sznsel = "";
                   1684:     var sz1sel = "";
                   1685:     var sz2sel = "";
1.718     bisitz   1686:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1687:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1688:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1689:     var synsel = "";
                   1690:     var syisel = "";
                   1691:     var sybsel = "";
1.718     bisitz   1692:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1693:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1694:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1695:     highlightCentral();
1.718     bisitz   1696:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1697:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1698:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1699:     highlightend();
                   1700:     return;
                   1701:   }
                   1702: 
                   1703:   function highlightCentral() {
1.76      ng       1704: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1705:     var xpos = (screen.width-400)/2;
                   1706:     xpos = (xpos < 0) ? '0' : xpos;
                   1707:     var ypos = (screen.height-330)/2-30;
                   1708:     ypos = (ypos < 0) ? '0' : ypos;
                   1709: 
1.206     albertel 1710:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1711:     hwdWin.focus();
                   1712:     var hDoc = hwdWin.document;
1.219     www      1713:     hDoc.$docopen;
1.351     albertel 1714:     hDoc.write('$start_page_highlight_central');
1.76      ng       1715:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1716:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1717: 
1.718     bisitz   1718:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1719:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1720:   }
                   1721: 
                   1722:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1723:     var hDoc = hwdWin.document;
1.718     bisitz   1724:     hDoc.write("<tr>");
1.76      ng       1725:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1726:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1727:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1728:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1729:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1730:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1731:     hDoc.write("<\\/tr>");
1.44      ng       1732:   }
                   1733: 
                   1734:   function highlightend() { 
1.76      ng       1735:     var hDoc = hwdWin.document;
1.718     bisitz   1736:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1737:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1738:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1739:     hDoc.write("<\\/form>");
1.351     albertel 1740:     hDoc.write('$end_page_highlight_central');
1.128     ng       1741:     hDoc.close();
1.44      ng       1742:   }
                   1743: 
                   1744: SUBJAVASCRIPT
                   1745: }
                   1746: 
1.349     albertel 1747: sub get_increment {
1.348     bowersj2 1748:     my $increment = $env{'form.increment'};
                   1749:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1750:         $increment != .1) {
                   1751:         $increment = 1;
                   1752:     }
                   1753:     return $increment;
                   1754: }
                   1755: 
1.585     bisitz   1756: sub gradeBox_start {
                   1757:     return (
                   1758:         &Apache::loncommon::start_data_table()
                   1759:        .&Apache::loncommon::start_data_table_header_row()
                   1760:        .'<th>'.&mt('Part').'</th>'
                   1761:        .'<th>'.&mt('Points').'</th>'
                   1762:        .'<th>&nbsp;</th>'
                   1763:        .'<th>'.&mt('Assign Grade').'</th>'
                   1764:        .'<th>'.&mt('Weight').'</th>'
                   1765:        .'<th>'.&mt('Grade Status').'</th>'
                   1766:        .&Apache::loncommon::end_data_table_header_row()
                   1767:     );
                   1768: }
                   1769: 
                   1770: sub gradeBox_end {
                   1771:     return (
                   1772:         &Apache::loncommon::end_data_table()
                   1773:     );
                   1774: }
1.71      ng       1775: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1776: sub gradeBox {
1.322     albertel 1777:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1778:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1779: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1780:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1781:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1782:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1783:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1784:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1785: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1786:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1787:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1788:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1789: 				       [$partid]);
                   1790:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1791:     if ($last_resets{$partid}) {
                   1792:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1793:     }
1.695     bisitz   1794:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1795:     my $ctr = 0;
1.348     bowersj2 1796:     my $thisweight = 0;
1.349     albertel 1797:     my $increment = &get_increment();
1.485     albertel 1798: 
                   1799:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1800:     while ($thisweight<=$wgt) {
1.532     bisitz   1801: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1802:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1803: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1804: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1805: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1806:         $thisweight += $increment;
1.71      ng       1807: 	$ctr++;
                   1808:     }
1.485     albertel 1809:     $radio.='</tr></table>';
                   1810: 
                   1811:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1812: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1813: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1814: 	$wgt.')" /></td>'."\n";
1.485     albertel 1815:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1816: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1817: 	' </td>'."\n";
                   1818:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1819: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1820:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1821: 	$line.='<option></option>'.
                   1822: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1823:     } else {
1.485     albertel 1824: 	$line.='<option selected="selected"></option>'.
                   1825: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1826:     }
1.485     albertel 1827:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1828: 
                   1829: 
                   1830:     $result .= 
1.695     bisitz   1831: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1832:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1833:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1834:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1835: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1836: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1837: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1838:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1839:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1840:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1841:         $aggtries.'" />'."\n";
1.582     raeburn  1842:     my $res_error;
                   1843:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1844:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1845:     if ($res_error) {
                   1846:         return &navmap_errormsg();
                   1847:     }
1.318     banghart 1848:     return $result;
                   1849: }
1.322     albertel 1850: 
                   1851: sub handback_box {
1.623     www      1852:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1853:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1854:     my (@respids);
1.652     raeburn  1855:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1856:     foreach my $part_response_id (@part_response_id) {
                   1857:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1858:         if ($part eq $partid) {
1.375     albertel 1859:             push(@respids,$resp);
1.323     banghart 1860:         }
                   1861:     }
1.318     banghart 1862:     my $result;
1.323     banghart 1863:     foreach my $respid (@respids) {
1.322     albertel 1864: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1865: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1866: 	next if (!@$files);
1.654     raeburn  1867: 	my $file_counter = 0;
1.313     banghart 1868: 	foreach my $file (@$files) {
1.368     banghart 1869: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1870:                 $file_counter++;
1.368     banghart 1871:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1872:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1873:     	        $file_disp = "$name.$ext";
                   1874:     	        $file = $file_path.$file_disp;
                   1875:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1876:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1877:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1878:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1879: 	    }
1.322     albertel 1880: 	}
1.654     raeburn  1881:         if ($file_counter) {
                   1882:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1883:                        '<span class="LC_info">'.
                   1884:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1885:         }
1.313     banghart 1886:     }
1.318     banghart 1887:     return $result;    
1.71      ng       1888: }
1.44      ng       1889: 
1.58      albertel 1890: sub show_problem {
1.382     albertel 1891:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1892:     my $rendered;
1.382     albertel 1893:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1894:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1895:     if ($mode eq 'both' or $mode eq 'text') {
                   1896: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1897: 						       $env{'request.course.id'},
                   1898: 						       undef,\%form);
1.144     albertel 1899:     }
1.58      albertel 1900:     if ($removeform) {
                   1901: 	$rendered=~s|<form(.*?)>||g;
                   1902: 	$rendered=~s|</form>||g;
1.374     albertel 1903: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1904:     }
1.144     albertel 1905:     my $companswer;
                   1906:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1907: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1908: 	$companswer=
                   1909: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1910: 						    $env{'request.course.id'},
                   1911: 						    %form);
1.144     albertel 1912:     }
1.58      albertel 1913:     if ($removeform) {
                   1914: 	$companswer=~s|<form(.*?)>||g;
                   1915: 	$companswer=~s|</form>||g;
1.144     albertel 1916: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1917:     }
1.671     raeburn  1918:     my $renderheading = &mt('View of the problem');
                   1919:     my $answerheading = &mt('Correct answer');
                   1920:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1921:         my $stu_fullname = $env{'form.fullname'};
                   1922:         if ($stu_fullname eq '') {
                   1923:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1924:         }
                   1925:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1926:         if ($forwhom ne '') {
                   1927:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1928:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1929:         }
                   1930:     }
1.468     albertel 1931:     $rendered=
1.588     bisitz   1932:         '<div class="LC_Box">'
1.671     raeburn  1933:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1934:        .$rendered
                   1935:        .'</div>';
1.468     albertel 1936:     $companswer=
1.588     bisitz   1937:         '<div class="LC_Box">'
1.671     raeburn  1938:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1939:        .$companswer
                   1940:        .'</div>';
1.468     albertel 1941:     my $result;
1.144     albertel 1942:     if ($mode eq 'both') {
1.588     bisitz   1943:         $result=$rendered.$companswer;
1.144     albertel 1944:     } elsif ($mode eq 'text') {
1.588     bisitz   1945:         $result=$rendered;
1.144     albertel 1946:     } elsif ($mode eq 'answer') {
1.588     bisitz   1947:         $result=$companswer;
1.144     albertel 1948:     }
1.71      ng       1949:     return $result;
1.58      albertel 1950: }
1.397     albertel 1951: 
1.396     banghart 1952: sub files_exist {
                   1953:     my ($r, $symb) = @_;
                   1954:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1955: 
1.396     banghart 1956:     foreach my $student (@students) {
                   1957:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1958:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1959: 					      $udom,$uname);
1.396     banghart 1960:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1961:         foreach my $submission (@$string) {
                   1962:             my ($partid,$respid) =
                   1963: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1964:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1965: 					   \%record);
                   1966:             return 1 if (@$files);
1.396     banghart 1967:         }
                   1968:     }
1.397     albertel 1969:     return 0;
1.396     banghart 1970: }
1.397     albertel 1971: 
1.394     banghart 1972: sub download_all_link {
                   1973:     my ($r,$symb) = @_;
1.621     www      1974:     unless (&files_exist($r, $symb)) {
                   1975:        $r->print(&mt('There are currently no submitted documents.'));
                   1976:        return;
                   1977:     }
                   1978: 
1.395     albertel 1979:     my $all_students = 
                   1980: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1981: 
                   1982:     my $parts =
                   1983: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1984: 
1.394     banghart 1985:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1986:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1987:                              'cgi.'.$identifier.'.symb' => $symb,
                   1988:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1989:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1990: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1991:     return;
                   1992: }
                   1993: 
                   1994: sub submit_download_link {
                   1995:     my ($request,$symb) = @_;
                   1996:     if (!$symb) { return ''; }
                   1997: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1998:     &download_all_link($request,$symb);
1.394     banghart 1999: }
1.395     albertel 2000: 
1.432     banghart 2001: sub build_section_inputs {
                   2002:     my $section_inputs;
                   2003:     if ($env{'form.section'} eq '') {
                   2004:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2005:     } else {
                   2006:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2007:         foreach my $section (@sections) {
1.432     banghart 2008:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2009:         }
                   2010:     }
                   2011:     return $section_inputs;
                   2012: }
                   2013: 
1.44      ng       2014: # --------------------------- show submissions of a student, option to grade 
                   2015: sub submission {
1.608     www      2016:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2017:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2018:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2019:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2020:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2021: 
1.605     www      2022:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2023:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2024:     my $is_tool = ($symb =~ /ext\.tool$/);
1.104     albertel 2025: 
                   2026:     if (!&canview($usec)) {
1.712     bisitz   2027:         $request->print(
                   2028:             '<span class="LC_warning">'.
1.713     bisitz   2029:             &mt('Unable to view requested student.').
1.712     bisitz   2030:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2031:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2032:             '</span>');
1.104     albertel 2033: 	return;
                   2034:     }
                   2035: 
1.257     albertel 2036:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2037:     unless ($is_tool) { 
                   2038:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2039:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2040:     }
1.257     albertel 2041:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2042:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2043: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2044: 	'/check.gif" height="16" border="0" />';
1.41      ng       2045: 
                   2046:     # header info
                   2047:     if ($counter == 0) {
                   2048: 	&sub_page_js($request);
1.621     www      2049: 	&sub_page_kw_js($request);
1.118     ng       2050: 
1.44      ng       2051: 	# option to display problem, only once else it cause problems 
                   2052:         # with the form later since the problem has a form.
1.257     albertel 2053: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2054: 	    my $mode;
1.257     albertel 2055: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2056: 		$mode='both';
1.257     albertel 2057: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2058: 		$mode='text';
1.257     albertel 2059: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2060: 		$mode='answer';
                   2061: 	    }
1.329     albertel 2062: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2063: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2064: 	}
1.441     www      2065: 
1.704     raeburn  2066: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2067:         # if this subroutine has been called once.
1.41      ng       2068: 	my %keyhash = ();
1.624     www      2069: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2070:         if (1) {
1.41      ng       2071: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2072: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2073: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2074: 
1.257     albertel 2075: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2076: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2077: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2078: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2079: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2080: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2081: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2082: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2083: 	}
1.257     albertel 2084: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2085: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2086: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2087: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2088: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2089: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2090: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2091: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2092: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2093: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2094: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2095: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2096: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2097: 			&build_section_inputs().
1.326     albertel 2098: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2099: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2100: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2101: #	if ($env{'form.handgrade'} eq 'yes') {
                   2102:         if (1) {
1.257     albertel 2103: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2104: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2105: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2106: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2107: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2108: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2109: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2110: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2111: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2112: 	    }
1.123     ng       2113: 	}
1.41      ng       2114: 	
                   2115: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2116: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2117: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2118: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2119: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2120: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2121: 		'" />'."\n".
                   2122: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2123: 	    $cts++;
                   2124: 	}
                   2125: 	$request->print($prnmsg);
1.32      ng       2126: 
1.624     www      2127: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2128:         unless ($is_tool) {
1.652     raeburn  2129: 
                   2130:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2131:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2132:                           keyw => 'Keyword Options',
1.655     raeburn  2133:                           list => 'List',
1.652     raeburn  2134:                           past => 'Paste Selection to List',
1.661     www      2135:                           high => 'Highlight Attribute',
1.652     raeburn  2136:                      );    
1.88      www      2137: #
                   2138: # Print out the keyword options line
                   2139: #
1.718     bisitz   2140: 	    $request->print(
                   2141:                 '<div class="LC_columnSection">'
                   2142:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2143:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2144:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2145:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2146:  class="page">'.$lt{'past'}.'</a>',
                   2147:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2148:                     {legend => $lt{'keyw'}})
                   2149:                .'</fieldset></div>'
                   2150:             );
                   2151: 
1.88      www      2152: #
                   2153: # Load the other essays for similarity check
                   2154: #
1.324     albertel 2155:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2156: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2157: 	    $apath=&escape($apath);
1.88      www      2158: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2159:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2160:         }
                   2161:     }
1.44      ng       2162: 
1.441     www      2163: # This is where output for one specific student would start
1.592     bisitz   2164:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2165:     $request->print(
                   2166:         "\n\n"
                   2167:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2168:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2169:        ."\n"
                   2170:     );
1.441     www      2171: 
1.592     bisitz   2172:     # Show additional functions if allowed
                   2173:     if ($perm{'vgr'}) {
                   2174:         $request->print(
                   2175:             &Apache::loncommon::track_student_link(
1.708     bisitz   2176:                 'View recent activity',
1.592     bisitz   2177:                 $uname,$udom,'check')
                   2178:            .' '
                   2179:         );
                   2180:     }
                   2181:     if ($perm{'opa'}) {
                   2182:         $request->print(
                   2183:             &Apache::loncommon::pprmlink(
                   2184:                 &mt('Set/Change parameters'),
                   2185:                 $uname,$udom,$symb,'check'));
                   2186:     }
                   2187: 
                   2188:     # Show Problem
1.257     albertel 2189:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2190: 	my $mode;
1.257     albertel 2191: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2192: 	    $mode='both';
1.257     albertel 2193: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2194: 	    $mode='text';
1.257     albertel 2195: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2196: 	    $mode='answer';
                   2197: 	}
1.329     albertel 2198: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2199: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2200:     }
1.144     albertel 2201: 
1.257     albertel 2202:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2203:     my $res_error;
                   2204:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2205:     if ($res_error) {
                   2206:         $request->print(&navmap_errormsg());
                   2207:         return;
                   2208:     }
1.41      ng       2209: 
1.44      ng       2210:     # Display student info
1.41      ng       2211:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2212: 
1.745     raeburn  2213:     my $boxtitle = &mt('Submissions');
                   2214:     if ($is_tool) {
                   2215:         $boxtitle = &mt('Transactions')
                   2216:     }
1.590     bisitz   2217:     my $result='<div class="LC_Box">'
1.745     raeburn  2218:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2219:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2220:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2221: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2222:     unless ($is_tool) {
1.588     bisitz   2223:         $result.='<p class="LC_info">'
                   2224:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2225:                 ."</p>\n";
1.469     albertel 2226:     }
                   2227: 
1.118     ng       2228:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2229:     my $fullname;
                   2230:     my $col_fullnames = [];
1.624     www      2231: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2232:     unless ($is_tool) {
1.464     albertel 2233: 	(my $sub_result,$fullname,$col_fullnames)=
                   2234: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2235: 				 $counter);
                   2236: 	$result.=$sub_result;
1.41      ng       2237:     }
1.44      ng       2238:     $request->print($result."\n");
1.702     kruse    2239:     
1.44      ng       2240:     # print student answer/submission
1.588     bisitz   2241:     # Options are (1) Handgraded submission only
1.44      ng       2242:     #             (2) Last submission, includes submission that is not handgraded 
                   2243:     #                  (for multi-response type part)
                   2244:     #             (3) Last submission plus the parts info
                   2245:     #             (4) The whole record for this student
1.702     kruse    2246:     
1.745     raeburn  2247:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2248: 	
1.702     kruse    2249:     my $lastsubonly;
1.468     albertel 2250: 
1.702     kruse    2251:     if ($$timestamp eq '') {
                   2252:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2253:     } elsif ($is_tool) {
                   2254:         $lastsubonly =
                   2255:             '<div class="LC_grade_submissions_body">'
                   2256:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2257:     } else {
                   2258:         $lastsubonly =
                   2259:             '<div class="LC_grade_submissions_body">'
                   2260:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2261: 
                   2262: 	my %seenparts;
                   2263: 	my @part_response_id = &flatten_responseType($responseType);
                   2264: 	foreach my $part (@part_response_id) {
                   2265: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2266: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2267: 
1.702     kruse    2268: 	    my ($partid,$respid) = @{ $part };
                   2269: 	    my $display_part=&get_display_part($partid,$symb);
                   2270: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2271: 		if (exists($seenparts{$partid})) { next; }
                   2272: 		$seenparts{$partid}=1;
                   2273:                 $request->print(
                   2274:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2275:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2276:                                '<a href="javascript:viewSubmitter(\''.
                   2277:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2278:                                '\');" target="_self">'.
                   2279:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2280:                     '<br />');
                   2281: 		next;
                   2282: 		}
                   2283: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2284: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2285:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2286:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2287:                     ' <span class="LC_internal_info">'.
                   2288:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2289:                     '</span>&nbsp; &nbsp;'.
                   2290: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2291: 		next;
                   2292: 	    }
                   2293: 	    foreach my $submission (@$string) {
                   2294: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2295: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2296: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2297: 		# Similarity check
                   2298:                 my $similar='';
                   2299:                 my ($type,$trial,$rndseed);
                   2300:                 if ($hide eq 'rand') {
                   2301:                     $type = 'randomizetry';
                   2302:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2303:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2304:                 }
                   2305: 	        if ($env{'form.checkPlag'}) {
                   2306:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2307: 		        &most_similar($uname,$udom,$symb,$subval);
                   2308: 		    if ($osim) {
                   2309: 			$osim=int($osim*100.0);
                   2310: 			my %old_course_desc = 
                   2311: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2312: 							{'one_time' => 1});
                   2313: 
                   2314:                         if ($hide eq 'anon') {
                   2315:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2316:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2317:                         } else {
                   2318: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2319: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2320: 				    $osim,
                   2321: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2322: 				        $old_course_desc{'description'},
                   2323: 				        $old_course_desc{'num'},
                   2324: 				        $old_course_desc{'domain'}).
                   2325: 				    '</span></h3><blockquote><i>'.
                   2326: 				    &keywords_highlight($oessay).
                   2327: 				    '</i></blockquote><hr />';
1.702     kruse    2328:                         }
                   2329: 	            }
                   2330: 		}
                   2331: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2332:                                      undef,$type,$trial,$rndseed);
                   2333:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2334: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2335: 		    my $display_part=&get_display_part($partid,$symb);
                   2336:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2337:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2338:                         ' <span class="LC_internal_info">'.
                   2339:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2340:                         '</span>&nbsp; &nbsp;';
                   2341: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2342:                         
                   2343: 		    if (@$files) {
                   2344:                         if ($hide eq 'anon') {
                   2345:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2346:                         } else {
                   2347:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2348:                                         .'<br /><span class="LC_warning">';
                   2349:                             if(@$files == 1) {
                   2350:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2351:                             } else {
1.702     kruse    2352:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2353:                             }
                   2354:                             $lastsubonly .= '</span>';                         
                   2355:                             foreach my $file (@$files) {
                   2356:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2357:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2358:                             }
                   2359:                         }
1.702     kruse    2360: 			$lastsubonly.='<br />';
                   2361:                     }
                   2362:                     if ($hide eq 'anon') {
                   2363:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2364:                     } else {
1.724     raeburn  2365:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2366:                         if ($draft) {
                   2367:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2368:                         }
                   2369:                         $subval =
1.702     kruse    2370: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2371: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2372:                         if ($responsetype eq 'essay') {
                   2373:                             $subval =~ s{\n}{<br />}g;
                   2374:                         }
                   2375:                         $lastsubonly.=$subval."\n";
1.702     kruse    2376:                     }
                   2377: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2378: 		    $lastsubonly.='</div>';
1.41      ng       2379: 		}
1.702     kruse    2380:             }
1.151     albertel 2381: 	}
1.702     kruse    2382: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2383:     }
                   2384:     $request->print($lastsubonly);
                   2385:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2386:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2387: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2388:   
1.702     kruse    2389:     } 
                   2390:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2391:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2392:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2393: 								 $env{'request.course.id'},
1.44      ng       2394: 								 $last,'.submission',
1.726     raeburn  2395: 								 'Apache::grades::keywords_highlight',
                   2396:                                                                  $usec,$identifier));
1.41      ng       2397:     }
1.121     ng       2398:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2399: 	.$udom.'" />'."\n");
1.44      ng       2400:     # return if view submission with no grading option
1.618     www      2401:     if (!&canmodify($usec)) {
1.633     www      2402: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2403: 	return;
1.180     albertel 2404:     } else {
1.468     albertel 2405: 	$request->print('</div>'."\n");
1.41      ng       2406:     }
1.33      ng       2407: 
1.121     ng       2408:     # essay grading message center
1.624     www      2409: #    if ($env{'form.handgrade'} eq 'yes') {
                   2410:     if (1) {
1.468     albertel 2411: 	my $result='<div class="LC_grade_message_center">';
                   2412:     
                   2413: 	$result.='<div class="LC_grade_message_center_header">'.
                   2414: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2415: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2416: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2417: 	if (scalar(@$col_fullnames) > 0) {
                   2418: 	    my $lastone = pop(@$col_fullnames);
                   2419: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2420: 	}
                   2421: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2422: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2423: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2424: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2425: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2426: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2427: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2428: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2429: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2430: 	    '<br />&nbsp;('.
1.468     albertel 2431: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2432: 	$result.='</div></div>';
1.121     ng       2433: 	$request->print($result);
1.118     ng       2434:     }
1.41      ng       2435: 
                   2436:     my %seen = ();
                   2437:     my @partlist;
1.129     ng       2438:     my @gradePartRespid;
1.745     raeburn  2439:     my @part_response_id;
                   2440:     if ($is_tool) {
                   2441:         @part_response_id = ([0,'']);
                   2442:     } else {
                   2443:         @part_response_id = &flatten_responseType($responseType);
                   2444:     }
1.585     bisitz   2445:     $request->print(
1.588     bisitz   2446:         '<div class="LC_Box">'
                   2447:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2448:     );
1.592     bisitz   2449:     $request->print(&gradeBox_start());
1.375     albertel 2450:     foreach my $part_response_id (@part_response_id) {
                   2451:     	my ($partid,$respid) = @{ $part_response_id };
                   2452: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2453: 	next if ($seen{$partid} > 0);
1.41      ng       2454: 	$seen{$partid}++;
1.393     albertel 2455: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2456: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2457: 	push(@partlist,$partid);
                   2458: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2459: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2460:     }
1.585     bisitz   2461:     $request->print(&gradeBox_end()); # </div>
                   2462:     $request->print('</div>');
1.468     albertel 2463: 
                   2464:     $request->print('<div class="LC_grade_info_links">');
                   2465:     $request->print('</div>');
                   2466: 
1.45      ng       2467:     $result='<input type="hidden" name="partlist'.$counter.
                   2468: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2469:     $result.='<input type="hidden" name="gradePartRespid'.
                   2470: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2471:     my $ctr = 0;
                   2472:     while ($ctr < scalar(@partlist)) {
                   2473: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2474: 	    $partlist[$ctr].'" />'."\n";
                   2475: 	$ctr++;
                   2476:     }
1.468     albertel 2477:     $request->print($result.''."\n");
1.41      ng       2478: 
1.441     www      2479: # Done with printing info for one student
                   2480: 
1.468     albertel 2481:     $request->print('</div>');#LC_grade_show_user
1.441     www      2482: 
                   2483: 
1.41      ng       2484:     # print end of form
                   2485:     if ($counter == $total) {
1.592     bisitz   2486:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2487: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2488: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2489: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2490: 	my $ntstu ='<select name="NTSTU">'.
                   2491: 	    '<option>1</option><option>2</option>'.
                   2492: 	    '<option>3</option><option>5</option>'.
                   2493: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2494: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2495: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2496:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2497: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2498: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2499: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2500: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2501:         $endform.='<span class="LC_warning">'.
                   2502:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2503:                   '</span>'."\n" ;
1.349     albertel 2504:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2505:             "' name='increment' />";
1.485     albertel 2506: 	$endform.='</td></tr></table></form>';
1.41      ng       2507: 	$request->print($endform);
                   2508:     }
                   2509:     return '';
1.38      ng       2510: }
                   2511: 
1.464     albertel 2512: sub check_collaborators {
                   2513:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2514:     my ($result,@col_fullnames);
                   2515:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2516:     foreach my $part (keys(%$handgrade)) {
                   2517: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2518: 					'.maxcollaborators',
                   2519: 					$symb,$udom,$uname);
                   2520: 	next if ($ncol <= 0);
                   2521: 	$part =~ s/\_/\./g;
                   2522: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2523: 	my (@good_collaborators, @bad_collaborators);
                   2524: 	foreach my $possible_collaborator
1.630     www      2525: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2526: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2527: 	    next if ($possible_collaborator eq '');
1.631     www      2528: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2529: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2530: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2531: 	    # Doing this grep allows 'fuzzy' specification
                   2532: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2533: 			       keys(%$classlist));
                   2534: 	    if (! scalar(@matches)) {
                   2535: 		push(@bad_collaborators, $possible_collaborator);
                   2536: 	    } else {
                   2537: 		push(@good_collaborators, @matches);
                   2538: 	    }
                   2539: 	}
                   2540: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2541: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2542: 	    foreach my $name (@good_collaborators) {
                   2543: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2544: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2545: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2546: 	    }
1.630     www      2547: 	    $result.='</ol><br />'."\n";
1.466     albertel 2548: 	    my ($part)=split(/\./,$part);
1.464     albertel 2549: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2550: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2551: 		"\n";
                   2552: 	}
                   2553: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2554: 	    $result.='<div class="LC_warning">';
1.464     albertel 2555: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2556: 	    $result .= '</div>';
                   2557: 	}         
                   2558: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2559: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2560: 	    $result .= &mt('This student has submitted too many '.
                   2561: 		'collaborators.  Maximum is [_1].',$ncol);
                   2562: 	    $result .= '</div>';
                   2563: 	}
                   2564:     }
                   2565:     return ($result,$fullname,\@col_fullnames);
                   2566: }
                   2567: 
1.44      ng       2568: #--- Retrieve the last submission for all the parts
1.38      ng       2569: sub get_last_submission {
1.745     raeburn  2570:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2571:     my (@string,$timestamp,%lasthidden);
1.119     ng       2572:     if ($$returnhash{'version'}) {
1.46      ng       2573: 	my %lasthash=();
                   2574: 	my ($version);
1.119     ng       2575: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2576: 	    foreach my $key (sort(split(/\:/,
                   2577: 					$$returnhash{$version.':keys'}))) {
                   2578: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2579: 		$timestamp = 
1.545     raeburn  2580: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2581: 	    }
                   2582: 	}
1.640     raeburn  2583:         my (%typeparts,%randombytry);
1.596     raeburn  2584:         my $showsurv = 
                   2585:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2586:         foreach my $key (sort(keys(%lasthash))) {
                   2587:             if ($key =~ /\.type$/) {
                   2588:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2589:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2590:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2591:                     my ($ign,@parts) = split(/\./,$key);
                   2592:                     pop(@parts);
1.641     raeburn  2593:                     my $id = join('.',@parts);
1.640     raeburn  2594:                     if ($lasthash{$key} eq 'randomizetry') {
                   2595:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2596:                     } else {
                   2597:                         unless ($showsurv) {
                   2598:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2599:                         }
1.596     raeburn  2600:                     }
                   2601:                     delete($lasthash{$key});
                   2602:                 }
                   2603:             }
                   2604:         }
                   2605:         my @hidden = keys(%typeparts);
1.640     raeburn  2606:         my @randomize = keys(%randombytry);
1.397     albertel 2607: 	foreach my $key (keys(%lasthash)) {
                   2608: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2609:             my $hide;
                   2610:             if (@hidden) {
                   2611:                 foreach my $id (@hidden) {
                   2612:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2613:                         $hide = 'anon';
1.596     raeburn  2614:                         last;
                   2615:                     }
                   2616:                 }
                   2617:             }
1.640     raeburn  2618:             unless ($hide) {
                   2619:                 if (@randomize) {
1.732     raeburn  2620:                     foreach my $id (@randomize) {
1.640     raeburn  2621:                         if ($key =~ /^\Q$id\E/) {
                   2622:                             $hide = 'rand';
                   2623:                             last;
                   2624:                         }
                   2625:                     }
                   2626:                 }
                   2627:             }
1.397     albertel 2628: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2629: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2630:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2631:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2632:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2633: 	}
                   2634:     }
1.397     albertel 2635:     if (!@string) {
1.745     raeburn  2636:         my $msg;
                   2637:         if ($is_tool) {
1.747     raeburn  2638:             $msg = &mt('No grade passed back.');
1.745     raeburn  2639:         } else {
                   2640:             $msg = &mt('Nothing submitted - no attempts.');
                   2641:         }
1.397     albertel 2642: 	$string[0] =
1.745     raeburn  2643: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2644:     }
                   2645:     return (\@string,\$timestamp);
1.38      ng       2646: }
1.35      ng       2647: 
1.44      ng       2648: #--- High light keywords, with style choosen by user.
1.38      ng       2649: sub keywords_highlight {
1.44      ng       2650:     my $string    = shift;
1.257     albertel 2651:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2652:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2653:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2654:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2655:     foreach my $keyword (@keylist) {
                   2656: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2657:     }
                   2658:     return $string;
1.38      ng       2659: }
1.36      ng       2660: 
1.671     raeburn  2661: # For Tasks provide a mechanism to display previous version for one specific student
                   2662: 
                   2663: sub show_previous_task_version {
                   2664:     my ($request,$symb) = @_;
                   2665:     if ($symb eq '') {
1.717     bisitz   2666:         $request->print(
                   2667:             '<span class="LC_error">'.
                   2668:             &mt('Unable to handle ambiguous references.').
                   2669:             '</span>');
1.671     raeburn  2670:         return '';
                   2671:     }
                   2672:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2673:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2674:     if (!&canview($usec)) {
1.712     bisitz   2675:         $request->print(
                   2676:             '<span class="LC_warning">'.
1.713     bisitz   2677:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2678:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2679:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2680:             '</span>');
1.671     raeburn  2681:         return;
                   2682:     }
                   2683:     my $mode = 'both';
                   2684:     my $isTask = ($symb =~/\.task$/);
                   2685:     if ($isTask) {
                   2686:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2687:             if ($env{'form.fullname'} eq '') {
                   2688:                 $env{'form.fullname'} =
                   2689:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2690:             }
                   2691:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2692:             $request->print("\n\n".
                   2693:                             '<div class="LC_grade_show_user">'.
                   2694:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2695:                             '</h2>'."\n");
                   2696:             &Apache::lonxml::clear_problem_counter();
                   2697:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2698:                             {'previousversion' => $env{'form.previousversion'} }));
                   2699:             $request->print("\n</div>");
                   2700:         }
                   2701:     }
                   2702:     return;
                   2703: }
                   2704: 
                   2705: sub choose_task_version_form {
                   2706:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2707:     my $isTask = ($symb =~/\.task$/);
                   2708:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2709:     if ($isTask) {
                   2710:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2711:                                               $udom,$uname);
                   2712:         if (($record{'resource.0.version'} eq '') ||
                   2713:             ($record{'resource.0.version'} < 2)) {
                   2714:             return ($record{'resource.0.version'},
                   2715:                     $record{'resource.0.version'},$result,$js);
                   2716:         } else {
                   2717:             $current = $record{'resource.0.version'};
                   2718:         }
                   2719:         if ($env{'form.previousversion'}) {
                   2720:             $displayed = $env{'form.previousversion'};
                   2721:             $rowtitle = &mt('Choose another version:')
                   2722:         } else {
                   2723:             $displayed = $current;
                   2724:             $rowtitle = &mt('Show earlier version:');
                   2725:         }
                   2726:         $result = '<div class="LC_left_float">';
                   2727:         my $list;
                   2728:         my $numversions = 0;
                   2729:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2730:             if ($i == $current) {
                   2731:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2732:                     next;
                   2733:                 } else {
                   2734:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2735:                     $numversions ++;
                   2736:                 }
                   2737:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2738:                 unless ($i == $env{'form.previousversion'}) {
                   2739:                     $numversions ++;
                   2740:                 }
                   2741:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2742:             }
                   2743:         }
                   2744:         if ($numversions) {
                   2745:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2746:             $result .=
                   2747:                 '<form name="getprev" method="post" action=""'.
                   2748:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2749:                 &Apache::loncommon::start_data_table().
                   2750:                 &Apache::loncommon::start_data_table_row().
                   2751:                 '<th align="left">'.$rowtitle.'</th>'.
                   2752:                 '<td><select name="version">'.
                   2753:                 '<option>'.&mt('Select').'</option>'.
                   2754:                 $list.
                   2755:                 '</select></td>'.
                   2756:                 &Apache::loncommon::end_data_table_row();
                   2757:             unless ($nomenu) {
                   2758:                 $result .= &Apache::loncommon::start_data_table_row().
                   2759:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2760:                 '<td><span class="LC_nobreak">'.
                   2761:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2762:                 &mt('Yes').'</label>'.
                   2763:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2764:                 '</span></td>'.
                   2765:                 &Apache::loncommon::end_data_table_row();
                   2766:             }
                   2767:             $result .=
                   2768:                 &Apache::loncommon::start_data_table_row().
                   2769:                 '<th align="left">&nbsp;</th>'.
                   2770:                 '<td>'.
                   2771:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2772:                 '</td>'.
                   2773:                 &Apache::loncommon::end_data_table_row().
                   2774:                 &Apache::loncommon::end_data_table().
                   2775:                 '</form>';
                   2776:             $js = &previous_display_javascript($nomenu,$current);
                   2777:         } elsif ($displayed && $nomenu) {
                   2778:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2779:         } else {
                   2780:             $result .= &mt('No previous versions to show for this student');
                   2781:         }
                   2782:         $result .= '</div>';
                   2783:     }
                   2784:     return ($current,$displayed,$result,$js);
                   2785: }
                   2786: 
                   2787: sub previous_display_javascript {
                   2788:     my ($nomenu,$current) = @_;
                   2789:     my $js = <<"JSONE";
                   2790: <script type="text/javascript">
                   2791: // <![CDATA[
                   2792: function previousVersion(uname,udom,symb) {
                   2793:     var current = '$current';
                   2794:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2795:     var prevstr = new RegExp("^\\\\d+\$");
                   2796:     if (!prevstr.test(version)) {
                   2797:         return false;
                   2798:     }
                   2799:     var url = '';
                   2800:     if (version == current) {
                   2801:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2802:     } else {
                   2803:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2804:     }
                   2805: JSONE
                   2806:     if ($nomenu) {
                   2807:         $js .= <<"JSTWO";
                   2808:     document.location.href = url;
                   2809: JSTWO
                   2810:     } else {
                   2811:         $js .= <<"JSTHREE";
                   2812:     var newwin = 0;
                   2813:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2814:         if (document.getprev.prevwin[i].checked == true) {
                   2815:             newwin = document.getprev.prevwin[i].value;
                   2816:         }
                   2817:     }
                   2818:     if (newwin == 1) {
                   2819:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2820:         url = url+'&inhibitmenu=yes';
                   2821:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2822:             previousWin = window.open(url,'',options,1);
                   2823:         } else {
                   2824:             previousWin.location.href = url;
                   2825:         }
                   2826:         previousWin.focus();
                   2827:         return false;
                   2828:     } else {
                   2829:         document.location.href = url;
                   2830:         return false;
                   2831:     }
                   2832: JSTHREE
                   2833:     }
                   2834:     $js .= <<"ENDJS";
                   2835:     return false;
                   2836: }
                   2837: // ]]>
                   2838: </script>
                   2839: ENDJS
                   2840: 
                   2841: }
                   2842: 
1.44      ng       2843: #--- Called from submission routine
1.38      ng       2844: sub processHandGrade {
1.608     www      2845:     my ($request,$symb) = @_;
1.324     albertel 2846:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2847:     my $button = $env{'form.gradeOpt'};
                   2848:     my $ngrade = $env{'form.NCT'};
                   2849:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2850:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2851:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2852: 
1.44      ng       2853:     if ($button eq 'Save & Next') {
                   2854: 	my $ctr = 0;
                   2855: 	while ($ctr < $ngrade) {
1.257     albertel 2856: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2857: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2858:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2859: 	    if ($errorflag eq 'no_score') {
                   2860: 		$ctr++;
                   2861: 		next;
                   2862: 	    }
1.104     albertel 2863: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2864: 		$request->print(
                   2865:                     '<span class="LC_error">'
                   2866:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2867:                    .'</span>');
1.104     albertel 2868: 		$ctr++;
                   2869: 		next;
                   2870: 	    }
1.726     raeburn  2871:             if ($numhidden) {
                   2872:                 $request->print(
                   2873:                     '<span class="LC_info">'
                   2874:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2875:                    .'</span><br />');
                   2876:             }
1.257     albertel 2877: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2878: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2879: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2880:             my ($feedurl,$showsymb) =
                   2881: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2882: 	    my $messagetail;
1.62      albertel 2883: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2884: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2885: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2886: 		$subject.=' ['.$restitle.']';
1.44      ng       2887: 		my (@msgnum) = split(/,/,$includemsg);
                   2888: 		foreach (@msgnum) {
1.257     albertel 2889: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2890: 		}
1.80      ng       2891: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2892: 		if ($env{'form.withgrades'.$ctr}) {
                   2893: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2894: 		    $messagetail = " for <a href=\"".
1.605     www      2895: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2896: 		}
                   2897: 		$msgstatus = 
                   2898:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2899: 						     $message.$messagetail,
1.418     albertel 2900:                                                      undef,$feedurl,undef,
1.386     raeburn  2901:                                                      undef,undef,$showsymb,
                   2902:                                                      $restitle);
1.574     bisitz   2903: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2904: 				$msgstatus.'<br />');
1.44      ng       2905: 	    }
1.257     albertel 2906: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2907: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2908: 		foreach my $collabstr (@collabstrs) {
                   2909: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2910: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2911: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2912: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2913: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2914: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2915: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2916: 			    next;
1.418     albertel 2917: 			} elsif ($message ne '') {
                   2918: 			    my ($baseurl,$showsymb) = 
                   2919: 				&get_feedurl_and_symb($symb,$collaborator,
                   2920: 						      $udom);
                   2921: 			    if ($env{'form.withgrades'.$ctr}) {
                   2922: 				$messagetail = " for <a href=\"".
1.605     www      2923:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2924: 			    }
1.418     albertel 2925: 			    $msgstatus = 
                   2926: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2927: 			}
1.44      ng       2928: 		    }
                   2929: 		}
                   2930: 	    }
                   2931: 	    $ctr++;
                   2932: 	}
                   2933:     }
                   2934: 
1.624     www      2935: #    if ($env{'form.handgrade'} eq 'yes') {
                   2936:     if (1) {
1.119     ng       2937: 	# Keywords sorted in alphabatical order
1.257     albertel 2938: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2939: 	my %keyhash = ();
1.257     albertel 2940: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2941: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2942: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2943: 	$env{'form.keywords'} = join(' ',@keywords);
                   2944: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2945: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2946: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2947: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2948: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2949: 
                   2950: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2951: 	# New messages are saved in env for the next student.
1.119     ng       2952: 	# All messages are saved in nohist_handgrade.db
                   2953: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2954: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2955: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2956: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2957: 		$idx++;
                   2958: 	    }
                   2959: 	    $ctr++;
1.41      ng       2960: 	}
1.119     ng       2961: 	$ctr = 0;
                   2962: 	while ($ctr < $ngrade) {
1.257     albertel 2963: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2964: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2965: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2966: 		$idx++;
                   2967: 	    }
                   2968: 	    $ctr++;
1.41      ng       2969: 	}
1.257     albertel 2970: 	$env{'form.savemsgN'} = --$idx;
                   2971: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2972: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2973: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2974:     }
1.44      ng       2975:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2976:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2977:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2978: 	my ($ctr,$total) = (0,0);
                   2979: 	while ($ctr < $ngrade) {
1.257     albertel 2980: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2981: 	    $ctr++;
                   2982: 	}
1.257     albertel 2983: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2984: 	$ctr = 0;
                   2985: 	while ($ctr < $total) {
1.257     albertel 2986: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2987: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2988: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2989: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2990: 	    $ctr++;
                   2991: 	}
                   2992: 	return '';
                   2993:     }
1.36      ng       2994: 
1.44      ng       2995:     # Get the next/previous one or group of students
1.257     albertel 2996:     my $firststu = $env{'form.unamedom0'};
                   2997:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2998:     my $ctr = 2;
1.41      ng       2999:     while ($laststu eq '') {
1.257     albertel 3000: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3001: 	$ctr++;
                   3002: 	$laststu = $firststu if ($ctr > $ngrade);
                   3003:     }
1.44      ng       3004: 
1.41      ng       3005:     my (@parsedlist,@nextlist);
                   3006:     my ($nextflg) = 0;
1.524     raeburn  3007:     foreach my $item (sort 
1.294     albertel 3008: 	     {
                   3009: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3010: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3011: 		 }
                   3012: 		 return $a cmp $b;
                   3013: 	     } (keys(%$fullname))) {
1.605     www      3014: # FIXME: this is fishy, looks like the button label
1.41      ng       3015: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3016: 	    push(@parsedlist,$item);
1.41      ng       3017: 	}
1.524     raeburn  3018: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3019: 	if ($button eq 'Previous') {
1.524     raeburn  3020: 	    last if ($item eq $firststu);
                   3021: 	    push(@parsedlist,$item);
1.41      ng       3022: 	}
                   3023:     }
                   3024:     $ctr = 0;
1.605     www      3025: # FIXME: this is fishy, looks like the button label
1.41      ng       3026:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3027:     my $res_error;
                   3028:     my ($partlist) = &response_type($symb,\$res_error);
                   3029:     if ($res_error) {
                   3030:         $request->print(&navmap_errormsg());
                   3031:         return;
                   3032:     }
1.41      ng       3033:     foreach my $student (@parsedlist) {
1.257     albertel 3034: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3035: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3036: 	
                   3037: 	if ($submitonly eq 'queued') {
                   3038: 	    my %queue_status = 
                   3039: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3040: 							$udom,$uname);
                   3041: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3042: 	}
                   3043: 
1.156     albertel 3044: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3045: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3046: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3047: 	    my $submitted = 0;
1.248     albertel 3048: 	    my $ungraded = 0;
                   3049: 	    my $incorrect = 0;
1.524     raeburn  3050: 	    foreach my $item (keys(%status)) {
                   3051: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3052: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3053: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3054: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3055: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3056: 		    $submitted = 0;
                   3057: 		}
1.41      ng       3058: 	    }
1.156     albertel 3059: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3060: 				     $submitonly eq 'incorrect' ||
                   3061: 				     $submitonly eq 'graded'));
1.248     albertel 3062: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3063: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3064: 	}
1.524     raeburn  3065: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3066: 	last if ($ctr == $ntstu);
1.41      ng       3067: 	$ctr++;
                   3068:     }
1.36      ng       3069: 
1.41      ng       3070:     $ctr = 0;
                   3071:     my $total = scalar(@nextlist)-1;
1.39      ng       3072: 
1.524     raeburn  3073:     foreach (sort(@nextlist)) {
1.41      ng       3074: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3075: 	$env{'form.student'}  = $uname;
                   3076: 	$env{'form.userdom'}  = $udom;
                   3077: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3078: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3079: 	$ctr++;
                   3080:     }
                   3081:     if ($total < 0) {
1.653     raeburn  3082: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3083: 	$request->print($the_end);
                   3084:     }
                   3085:     return '';
1.38      ng       3086: }
1.36      ng       3087: 
1.44      ng       3088: #---- Save the score and award for each student, if changed
1.38      ng       3089: sub saveHandGrade {
1.324     albertel 3090:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3091:     my @version_parts;
1.104     albertel 3092:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3093: 					   $env{'request.course.id'});
1.104     albertel 3094:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3095:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3096:     my @parts_graded;
1.77      ng       3097:     my %newrecord  = ();
1.726     raeburn  3098:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3099:     my %aggregate = ();
                   3100:     my $aggregateflag = 0;
1.726     raeburn  3101:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3102:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3103:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3104:         $totchg += $numchgs;
                   3105:     }
1.301     albertel 3106:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3107:     foreach my $new_part (@parts) {
1.337     banghart 3108: 	#collaborator ($submi may vary for different parts
1.259     banghart 3109: 	if ($submitter && $new_part ne $part) { next; }
                   3110: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3111: 	if ($dropMenu eq 'excused') {
1.259     banghart 3112: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3113: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3114: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3115: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3116: 		}
1.364     banghart 3117: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3118: 	    }
1.125     ng       3119: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3120: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3121: 	    foreach my $key (keys(%record)) {
1.259     banghart 3122: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3123: 	    }
1.259     banghart 3124: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3125: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3126:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3127: 
                   3128:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3129: 					       [$new_part]);
                   3130:             my $aggtries =$totaltries;
1.269     raeburn  3131:             if ($last_resets{$new_part}) {
1.270     albertel 3132:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3133: 					   $new_part);
1.269     raeburn  3134:             }
1.270     albertel 3135: 
                   3136:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3137:             if ($aggtries > 0) {
1.327     albertel 3138:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3139:                 $aggregateflag = 1;
                   3140:             }
1.125     ng       3141: 	} elsif ($dropMenu eq '') {
1.259     banghart 3142: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3143: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3144: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3145: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3146: 		next;
                   3147: 	    }
1.259     banghart 3148: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3149: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3150: 	    my $partial= $pts/$wgt;
1.259     banghart 3151: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3152: 		#do not update score for part if not changed.
1.346     banghart 3153:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3154: 		next;
1.251     banghart 3155: 	    } else {
1.524     raeburn  3156: 	        push(@parts_graded,$new_part);
1.153     albertel 3157: 	    }
1.259     banghart 3158: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3159: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3160: 	    }
1.259     banghart 3161: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3162: 	    if ($partial == 0) {
1.153     albertel 3163: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3164: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3165: 		}
1.41      ng       3166: 	    } else {
1.153     albertel 3167: 		if ($record{$reckey} ne 'correct_by_override') {
                   3168: 		    $newrecord{$reckey} = 'correct_by_override';
                   3169: 		}
                   3170: 	    }	    
                   3171: 	    if ($submitter && 
1.259     banghart 3172: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3173: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3174: 	    }
1.259     banghart 3175: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3176: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3177: 	}
1.259     banghart 3178: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3179: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3180: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3181: 	        $dropMenu eq 'reset status')
                   3182: 	   {
1.524     raeburn  3183: 	    push(@version_parts,$new_part);
1.259     banghart 3184: 	}
1.41      ng       3185:     }
1.301     albertel 3186:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3187:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3188: 
1.344     albertel 3189:     if (%newrecord) {
                   3190:         if (@version_parts) {
1.364     banghart 3191:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3192:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3193: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3194: 	    foreach my $new_part (@version_parts) {
                   3195: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3196: 				$new_part,\%newrecord);
                   3197: 	    }
1.259     banghart 3198:         }
1.44      ng       3199: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3200: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3201: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3202: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3203:     }
1.269     raeburn  3204:     if ($aggregateflag) {
                   3205:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3206: 			      $cdom,$cnum);
1.269     raeburn  3207:     }
1.726     raeburn  3208:     return ('',$pts,$wgt,$totchg);
                   3209: }
                   3210: 
                   3211: sub makehidden {
1.728     raeburn  3212:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3213:     return unless (ref($record) eq 'HASH');
                   3214:     my %modified;
                   3215:     my $numchanged = 0;
                   3216:     if (exists($record->{$version.':keys'})) {
                   3217:         my $partsregexp = $parts;
                   3218:         $partsregexp =~ s/,/|/g;
                   3219:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3220:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3221:                  my $item = $1;
                   3222:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3223:                      $modified{$key} = $record->{$version.':'.$key};
                   3224:                  }
                   3225:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3226:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3227:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3228:                 $modified{$key} = $record->{$version.':'.$key};
                   3229:             }
                   3230:         }
                   3231:         if (keys(%modified)) {
                   3232:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3233:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3234:                 $numchanged ++;
                   3235:             }
                   3236:         }
                   3237:     }
                   3238:     return $numchanged;
1.36      ng       3239: }
1.322     albertel 3240: 
1.380     albertel 3241: sub check_and_remove_from_queue {
                   3242:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3243:     my @ungraded_parts;
                   3244:     foreach my $part (@{$parts}) {
                   3245: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3246: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3247: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3248: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3249: 		) {
                   3250: 	    push(@ungraded_parts, $part);
                   3251: 	}
                   3252:     }
                   3253:     if ( !@ungraded_parts ) {
                   3254: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3255: 					       $cnum,$domain,$stuname);
                   3256:     }
                   3257: }
                   3258: 
1.337     banghart 3259: sub handback_files {
                   3260:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3261:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3262:     my $res_error;
                   3263:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3264:     if ($res_error) {
                   3265:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3266:         return;
                   3267:     }
1.654     raeburn  3268:     my @handedback;
                   3269:     my $file_msg;
1.375     albertel 3270:     my @part_response_id = &flatten_responseType($responseType);
                   3271:     foreach my $part_response_id (@part_response_id) {
                   3272:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3273: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3274:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3275:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3276:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3277:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3278:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3279:                     my ($directory,$answer_file) = 
1.654     raeburn  3280:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3281:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3282: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3283: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3284:                     my $getpropath = 1;
1.662     raeburn  3285:                     my ($dir_list,$listerror) = 
                   3286:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3287:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3288: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3289:                     # fix filename
1.355     banghart 3290:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3291:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3292:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3293:             	                                $save_file_name);
1.337     banghart 3294:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3295:                         $request->print('<br /><span class="LC_error">'.
                   3296:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3297:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3298:                                         '</span>');
1.356     banghart 3299:                     } else {
1.360     banghart 3300:                         # mark the file as read only
1.654     raeburn  3301:                         push(@handedback,$save_file_name);
1.367     albertel 3302: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3303: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3304: 			}
                   3305:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3306: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3307:                     }
1.686     bisitz   3308:                     $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 3309:                 }
                   3310:             }
                   3311:         }
1.654     raeburn  3312:     }
                   3313:     if (@handedback > 0) {
                   3314:         $request->print('<br />');
                   3315:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3316:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3317:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3318:         my ($subject,$message);
                   3319:         if (scalar(@handedback) == 1) {
                   3320:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3321:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3322:         } else {
                   3323:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3324:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3325:         }
                   3326:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3327:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3328:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3329:         my ($feedurl,$showsymb) =
                   3330:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3331:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3332:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3333:         my $msgstatus =
                   3334:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3335:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3336:                  $restitle);
                   3337:         if ($msgstatus) {
                   3338:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3339:         }
                   3340:     }
1.338     banghart 3341:     return;
1.337     banghart 3342: }
                   3343: 
1.418     albertel 3344: sub get_feedurl_and_symb {
                   3345:     my ($symb,$uname,$udom) = @_;
                   3346:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3347:     $url = &Apache::lonnet::clutter($url);
                   3348:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3349: 					$symb,$udom,$uname);
                   3350:     if ($encrypturl =~ /^yes$/i) {
                   3351: 	&Apache::lonenc::encrypted(\$url,1);
                   3352: 	&Apache::lonenc::encrypted(\$symb,1);
                   3353:     }
                   3354:     return ($url,$symb);
                   3355: }
                   3356: 
1.313     banghart 3357: sub get_submitted_files {
                   3358:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3359:     my @files;
                   3360:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3361:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3362:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3363:     	    push(@files,$file_url.$file);
                   3364:         }
                   3365:     }
                   3366:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3367:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3368:     }
                   3369:     return (\@files);
                   3370: }
1.322     albertel 3371: 
1.269     raeburn  3372: # ----------- Provides number of tries since last reset.
                   3373: sub get_num_tries {
                   3374:     my ($record,$last_reset,$part) = @_;
                   3375:     my $timestamp = '';
                   3376:     my $num_tries = 0;
                   3377:     if ($$record{'version'}) {
                   3378:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3379:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3380:                 $timestamp = $$record{$version.':timestamp'};
                   3381:                 if ($timestamp > $last_reset) {
                   3382:                     $num_tries ++;
                   3383:                 } else {
                   3384:                     last;
                   3385:                 }
                   3386:             }
                   3387:         }
                   3388:     }
                   3389:     return $num_tries;
                   3390: }
                   3391: 
                   3392: # ----------- Determine decrements required in aggregate totals 
                   3393: sub decrement_aggs {
                   3394:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3395:     my %decrement = (
                   3396:                         attempts => 0,
                   3397:                         users => 0,
                   3398:                         correct => 0
                   3399:                     );
                   3400:     $decrement{'attempts'} = $aggtries;
                   3401:     if ($solvedstatus =~ /^correct/) {
                   3402:         $decrement{'correct'} = 1;
                   3403:     }
                   3404:     if ($aggtries == $totaltries) {
                   3405:         $decrement{'users'} = 1;
                   3406:     }
1.524     raeburn  3407:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3408:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3409:     }
                   3410:     return;
                   3411: }
                   3412: 
                   3413: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3414: sub get_last_resets {
1.270     albertel 3415:     my ($symb,$courseid,$partids) =@_;
                   3416:     my %last_resets;
1.269     raeburn  3417:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3418:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3419:     my @keys;
                   3420:     foreach my $part (@{$partids}) {
                   3421: 	push(@keys,"$symb\0$part\0resettime");
                   3422:     }
                   3423:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3424: 				     $cdom,$cname);
                   3425:     foreach my $part (@{$partids}) {
                   3426: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3427:     }
1.270     albertel 3428:     return %last_resets;
1.269     raeburn  3429: }
                   3430: 
1.251     banghart 3431: # ----------- Handles creating versions for portfolio files as answers
                   3432: sub version_portfiles {
1.343     banghart 3433:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3434:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3435:     my @returned_keys;
1.255     banghart 3436:     my $parts = join('|', @$parts_graded);
1.277     albertel 3437:     foreach my $key (keys(%$record)) {
1.259     banghart 3438:         my $new_portfiles;
1.263     banghart 3439:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3440:             my @versioned_portfiles;
1.367     albertel 3441:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3442:             if (@portfiles) {
                   3443:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3444:                                                       \@versioned_portfiles);
1.252     banghart 3445:             }
1.343     banghart 3446:             $$record{$key} = join(',',@versioned_portfiles);
                   3447:             push(@returned_keys,$key);
1.251     banghart 3448:         }
                   3449:     } 
1.343     banghart 3450:     return (@returned_keys);   
1.305     banghart 3451: }
                   3452: 
1.44      ng       3453: #--------------------------------------------------------------------------------------
                   3454: #
                   3455: #-------------------------- Next few routines handles grading by section or whole class
                   3456: #
                   3457: #--- Javascript to handle grading by section or whole class
1.42      ng       3458: sub viewgrades_js {
                   3459:     my ($request) = shift;
                   3460: 
1.539     riegler  3461:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3462:     &js_escape(\$alertmsg);
1.597     wenzelju 3463:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3464:    function writePoint(partid,weight,point) {
1.125     ng       3465: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3466: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3467: 	if (point == "textval") {
1.125     ng       3468: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3469: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3470: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3471: 		var resetbox = false;
                   3472: 		for (var i=0; i<radioButton.length; i++) {
                   3473: 		    if (radioButton[i].checked) {
                   3474: 			textbox.value = i;
                   3475: 			resetbox = true;
                   3476: 		    }
                   3477: 		}
                   3478: 		if (!resetbox) {
                   3479: 		    textbox.value = "";
                   3480: 		}
                   3481: 		return;
                   3482: 	    }
1.109     matthew  3483: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3484: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3485: 				   ") greater than the weight for the part. Accept?");
                   3486: 		if (resp == false) {
                   3487: 		    textbox.value = "";
                   3488: 		    return;
                   3489: 		}
                   3490: 	    }
1.42      ng       3491: 	    for (var i=0; i<radioButton.length; i++) {
                   3492: 		radioButton[i].checked=false;
1.109     matthew  3493: 		if (parseFloat(point) == i) {
1.42      ng       3494: 		    radioButton[i].checked=true;
                   3495: 		}
                   3496: 	    }
1.41      ng       3497: 
1.42      ng       3498: 	} else {
1.125     ng       3499: 	    textbox.value = parseFloat(point);
1.42      ng       3500: 	}
1.41      ng       3501: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3502: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3503: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3504: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3505: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3506: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3507: 	    if (saveval != "correct") {
                   3508: 		scorename.value = point;
1.43      ng       3509: 		if (selname[0].selected != true) {
                   3510: 		    selname[0].selected = true;
                   3511: 		}
1.42      ng       3512: 	    }
                   3513: 	}
1.125     ng       3514: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3515:     }
                   3516: 
                   3517:     function writeRadText(partid,weight) {
1.125     ng       3518: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3519: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3520:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3521: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3522: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3523: 	    for (var i=0; i<radioButton.length; i++) {
                   3524: 		radioButton[i].checked=false;
                   3525: 
                   3526: 	    }
                   3527: 	    textbox.value = "";
                   3528: 
                   3529: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3530: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3531: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3532: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3533: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3534: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3535: 		if ((saveval != "correct") || override) {
1.42      ng       3536: 		    scorename.value = "";
1.125     ng       3537: 		    if (selval[1].selected) {
                   3538: 			selname[1].selected = true;
                   3539: 		    } else {
                   3540: 			selname[2].selected = true;
                   3541: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3542: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3543: 		    }
1.42      ng       3544: 		}
                   3545: 	    }
1.43      ng       3546: 	} else {
                   3547: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3548: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3549: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3550: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3551: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3552: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3553: 		if ((saveval != "correct") || override) {
1.125     ng       3554: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3555: 		    selname[0].selected = true;
                   3556: 		}
                   3557: 	    }
                   3558: 	}	    
1.42      ng       3559:     }
                   3560: 
                   3561:     function changeSelect(partid,user) {
1.125     ng       3562: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3563: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3564: 	var point  = textbox.value;
1.125     ng       3565: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3566: 
1.109     matthew  3567: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3568: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3569: 	    textbox.value = "";
                   3570: 	    return;
                   3571: 	}
1.109     matthew  3572: 	if (parseFloat(point) > parseFloat(weight)) {
                   3573: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3574: 			       ") greater than the weight of the part. Accept?");
                   3575: 	    if (resp == false) {
                   3576: 		textbox.value = "";
                   3577: 		return;
                   3578: 	    }
                   3579: 	}
1.42      ng       3580: 	selval[0].selected = true;
                   3581:     }
                   3582: 
                   3583:     function changeOneScore(partid,user) {
1.125     ng       3584: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3585: 	if (selval[1].selected || selval[2].selected) {
                   3586: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3587: 	    if (selval[2].selected) {
                   3588: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3589: 	    }
1.269     raeburn  3590:         }
1.42      ng       3591:     }
                   3592: 
                   3593:     function resetEntry(numpart) {
                   3594: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3595: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3596: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3597: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3598: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3599: 	    for (var i=0; i<radioButton.length; i++) {
                   3600: 		radioButton[i].checked=false;
                   3601: 
                   3602: 	    }
                   3603: 	    textbox.value = "";
                   3604: 	    selval[0].selected = true;
                   3605: 
                   3606: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3607: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3608: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3609: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3610: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3611: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3612: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3613: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3614: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3615: 		if (saveselval == "excused") {
1.43      ng       3616: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3617: 		} else {
1.43      ng       3618: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3619: 		}
                   3620: 	    }
1.41      ng       3621: 	}
1.42      ng       3622:     }
                   3623: 
1.41      ng       3624: VIEWJAVASCRIPT
1.42      ng       3625: }
                   3626: 
1.44      ng       3627: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3628: sub viewgrades {
1.608     www      3629:     my ($request,$symb) = @_;
1.745     raeburn  3630:     my ($is_tool,$toolsymb);
                   3631:     if ($symb =~ /ext\.tool$/) {
                   3632:         $is_tool = 1;
                   3633:         $toolsymb = $symb;
                   3634:     }
1.42      ng       3635:     &viewgrades_js($request);
1.41      ng       3636: 
1.168     albertel 3637:     #need to make sure we have the correct data for later EXT calls, 
                   3638:     #thus invalidate the cache
                   3639:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3640:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3641:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3642:     &Apache::lonnet::clear_EXT_cache_status();
                   3643: 
1.398     albertel 3644:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3645: 
                   3646:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3647:     $result.=&jscriptNform($symb);
1.41      ng       3648: 
1.44      ng       3649:     #beginning of class grading form
1.442     banghart 3650:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3651:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3652: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3653: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3654: 	&build_section_inputs().
1.442     banghart 3655: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3656: 
1.738     raeburn  3657:     #retrieve selected groups
                   3658:     my (@groups,$group_display);
                   3659:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3660:     if (grep(/^all$/,@groups)) {
                   3661:         @groups = ('all');
                   3662:     } elsif (grep(/^none$/,@groups)) {
                   3663:         @groups = ('none');
                   3664:     } elsif (@groups > 0) {
                   3665:         $group_display = join(', ',@groups);
                   3666:     }
                   3667: 
                   3668:     my ($common_header,$specific_header,@sections,$section_display);
                   3669:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3670:     if (grep(/^all$/,@sections)) {
                   3671:         @sections = ('all');
                   3672:         if ($group_display) {
                   3673:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3674:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3675:         } elsif (grep(/^none$/,@groups)) {
                   3676:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3677:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3678:         } else {
                   3679: 	    $common_header = &mt('Assign Common Grade to Class');
                   3680:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3681:         }
                   3682:     } elsif (grep(/^none$/,@sections)) {
                   3683:         @sections = ('none');
                   3684:         if ($group_display) {
                   3685:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3686:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3687:         } elsif (grep(/^none$/,@groups)) {
                   3688:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3689:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3690:         } else {
                   3691:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3692: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3693:         }
                   3694:     } else {
                   3695:         $section_display = join (", ",@sections);
                   3696:         if ($group_display) {
                   3697:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3698:                                  $section_display,$group_display);
                   3699:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3700:                                    $section_display,$group_display);
                   3701:         } elsif (grep(/^none$/,@groups)) {
                   3702:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3703:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3704:         } else {
                   3705:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3706: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3707:         }
                   3708:     }
                   3709:     my %submit_types = &substatus_options();
                   3710:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3711: 
                   3712:     if ($env{'form.submitonly'} eq 'all') {
                   3713:         $result.= '<h3>'.$common_header.'</h3>';
                   3714:     } else {
1.745     raeburn  3715:         my $text;
                   3716:         if ($is_tool) {
                   3717:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3718:         } else {
                   3719:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3720:         }
                   3721:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3722:     }
1.738     raeburn  3723:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3724:     #radio buttons/text box for assigning points for a section or class.
                   3725:     #handles different parts of a problem
1.582     raeburn  3726:     my $res_error;
                   3727:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3728:     if ($res_error) {
                   3729:         return &navmap_errormsg();
                   3730:     }
1.42      ng       3731:     my %weight = ();
                   3732:     my $ctsparts = 0;
1.45      ng       3733:     my %seen = ();
1.745     raeburn  3734:     my @part_response_id;
                   3735:     if ($is_tool) {
                   3736:         @part_response_id = ([0,'']);
                   3737:     } else {
                   3738:         @part_response_id = &flatten_responseType($responseType);
                   3739:     }
1.375     albertel 3740:     foreach my $part_response_id (@part_response_id) {
                   3741:     	my ($partid,$respid) = @{ $part_response_id };
                   3742: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3743: 	next if $seen{$partid};
                   3744: 	$seen{$partid}++;
1.744     raeburn  3745: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3746: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3747: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3748: 
1.324     albertel 3749: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3750: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3751: 	my $ctr = 0;
1.42      ng       3752: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3753: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3754: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3755: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3756: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3757: 	    $ctr++;
                   3758: 	}
1.485     albertel 3759: 	$radio.='</tr></table>';
                   3760: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3761: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3762: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3763: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3764:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3765:             '<select name="SELVAL_'.$partid.'" '.
                   3766:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3767:                 $weight{$partid}.')"> '.
1.401     albertel 3768: 	    '<option selected="selected"> </option>'.
1.485     albertel 3769: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3770: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3771: 	    '</select></td>'.
                   3772:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3773: 	$line.='<input type="hidden" name="partid_'.
                   3774: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3775: 	$line.='<input type="hidden" name="weight_'.
                   3776: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3777: 
                   3778: 	$result.=
                   3779: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3780: 	    '<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 3781: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3782: 	$ctsparts++;
1.41      ng       3783:     }
1.474     albertel 3784:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3785: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3786:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3787: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3788: 
1.44      ng       3789:     #table listing all the students in a section/class
                   3790:     #header of table
1.738     raeburn  3791:     if ($env{'form.submitonly'} eq 'all') {
                   3792:         $result.= '<h3>'.$specific_header.'</h3>';
                   3793:     } else {
1.745     raeburn  3794:         my $text;
                   3795:         if ($is_tool) {
                   3796:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3797:         } else {
                   3798:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3799:         }
                   3800:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3801:     }
                   3802:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3803: 	      &Apache::loncommon::start_data_table_header_row().
                   3804: 	      '<th>'.&mt('No.').'</th>'.
                   3805: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3806:     my $partserror;
                   3807:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3808:     if ($partserror) {
                   3809:         return &navmap_errormsg();
                   3810:     }
1.324     albertel 3811:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3812:     my @partids = ();
1.41      ng       3813:     foreach my $part (@parts) {
1.745     raeburn  3814: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3815:         my $narrowtext = &mt('Tries');
                   3816: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3817: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3818: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3819:         push(@partids,$partid);
1.628     www      3820: #
                   3821: # FIXME: Looks like $display looks at English text
                   3822: #
1.324     albertel 3823: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3824: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3825: 	    $result.='<th>'.
1.697     bisitz   3826: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3827: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3828: 	    next;
1.485     albertel 3829: 	    
1.207     albertel 3830: 	} else {
1.485     albertel 3831: 	    if ($display =~ /Problem Status/) {
                   3832: 		my $grade_status_mt = &mt('Grade Status');
                   3833: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3834: 	    }
                   3835: 	    my $part_mt = &mt('Part:');
                   3836: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3837: 	}
1.485     albertel 3838: 
1.474     albertel 3839: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3840:     }
1.474     albertel 3841:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3842: 
1.270     albertel 3843:     my %last_resets = 
                   3844: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3845: 
1.41      ng       3846:     #get info for each student
1.44      ng       3847:     #list all the students - with points and grade status
1.738     raeburn  3848:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3849:     my $ctr = 0;
1.294     albertel 3850:     foreach (sort 
                   3851: 	     {
                   3852: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3853: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3854: 		 }
                   3855: 		 return $a cmp $b;
                   3856: 	     } (keys(%$fullname))) {
1.324     albertel 3857: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  3858: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       3859:     }
1.474     albertel 3860:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3861:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3862:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3863: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  3864:     if ($ctr == 0) {
1.442     banghart 3865:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  3866:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3867:                 '<span class="LC_warning">';
                   3868:         if ($env{'form.submitonly'} eq 'all') {
                   3869:             if (grep(/^all$/,@sections)) {
                   3870:                 if (grep(/^all$/,@groups)) {
                   3871:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3872:                                    $stu_status);
                   3873:                 } elsif (grep(/^none$/,@groups)) {
                   3874:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3875:                                    $stu_status); 
                   3876:                 } else {
                   3877:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3878:                                    $group_display,$stu_status);
                   3879:                 }
                   3880:             } elsif (grep(/^none$/,@sections)) {
                   3881:                 if (grep(/^all$/,@groups)) {
                   3882:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3883:                                    $stu_status);
                   3884:                 } elsif (grep(/^none$/,@groups)) {
                   3885:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3886:                                    $stu_status);
                   3887:                 } else {
                   3888:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3889:                                    $group_display,$stu_status);
                   3890:                 }
                   3891:             } else {
                   3892:                 if (grep(/^all$/,@groups)) {
                   3893:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3894:                                    $section_display,$stu_status);
                   3895:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  3896:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  3897:                                    $section_display,$stu_status);
                   3898:                 } else {
                   3899:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3900:                                    $section_display,$group_display,$stu_status);
                   3901:                 }
                   3902:             }
                   3903:         } else {
                   3904:             if (grep(/^all$/,@sections)) {
                   3905:                 if (grep(/^all$/,@groups)) {
                   3906:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3907:                                    $stu_status,$submission_status);
                   3908:                 } elsif (grep(/^none$/,@groups)) {
                   3909:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3910:                                    $stu_status,$submission_status);
                   3911:                 } else {
                   3912:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   3913:                                    $group_display,$stu_status,$submission_status);
                   3914:                 }
                   3915:             } elsif (grep(/^none$/,@sections)) {
                   3916:                 if (grep(/^all$/,@groups)) {
                   3917:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3918:                                    $stu_status,$submission_status);
                   3919:                 } elsif (grep(/^none$/,@groups)) {
                   3920:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3921:                                    $stu_status,$submission_status);
                   3922:                 } else {
                   3923:                     $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.',
                   3924:                                    $group_display,$stu_status,$submission_status);
                   3925:                 }
                   3926:             } else {
                   3927:                 if (grep(/^all$/,@groups)) {
                   3928: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   3929: 	                           $section_display,$stu_status,$submission_status);
                   3930:                 } elsif (grep(/^none$/,@groups)) {
                   3931:                     $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.',
                   3932:                                    $section_display,$stu_status,$submission_status);
                   3933:                 } else {
                   3934:                     $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.',
                   3935:                                    $section_display,$group_display,$stu_status,$submission_status);
                   3936:                 }
                   3937:             }
                   3938:         }
                   3939: 	$result .= '</span><br />';
1.96      albertel 3940:     }
1.41      ng       3941:     return $result;
                   3942: }
                   3943: 
1.738     raeburn  3944: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       3945: sub viewstudentgrade {
1.745     raeburn  3946:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       3947:     my ($uname,$udom) = split(/:/,$student);
                   3948:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  3949:     my $submitonly = $env{'form.submitonly'};
                   3950:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   3951:         my %partstatus = ();
                   3952:         if (ref($parts) eq 'ARRAY') {
                   3953:             foreach my $apart (@{$parts}) {
                   3954:                 my ($part,$type) = &split_part_type($apart);
                   3955:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   3956:                 $status = 'nothing' if ($status eq '');
                   3957:                 $partstatus{$part}      = $status;
                   3958:                 my $subkey = "resource.$part.submitted_by";
                   3959:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   3960:             }
                   3961:             my $submitted = 0;
                   3962:             my $graded = 0;
                   3963:             my $incorrect = 0;
                   3964:             foreach my $key (keys(%partstatus)) {
                   3965:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   3966:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   3967:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   3968: 
                   3969:                 my $partid = (split(/\./,$key))[1];
                   3970:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   3971:                     $submitted = 0;
                   3972:                 }
                   3973:             }
                   3974:             return if (!$submitted && ($submitonly eq 'yes' ||
                   3975:                                        $submitonly eq 'incorrect' ||
                   3976:                                        $submitonly eq 'graded'));
                   3977:             return if (!$graded && ($submitonly eq 'graded'));
                   3978:             return if (!$incorrect && $submitonly eq 'incorrect');
                   3979:         }
                   3980:     }
                   3981:     if ($submitonly eq 'queued') {
                   3982:         my ($cdom,$cnum) = split(/_/,$courseid);
                   3983:         my %queue_status =
                   3984:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3985:                                                     $udom,$uname);
                   3986:         return if (!defined($queue_status{'gradingqueue'}));
                   3987:     }
                   3988:     $$ctr++;
                   3989:     my %aggregates = ();
1.474     albertel 3990:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  3991: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   3992: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3993: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3994: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3995: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3996:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3997:     foreach my $apart (@$parts) {
                   3998: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3999: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4000:         $result.='<td align="center">';
1.269     raeburn  4001:         my ($aggtries,$totaltries);
                   4002:         unless (exists($aggregates{$part})) {
1.270     albertel 4003: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4004: 	    $aggtries = $totaltries;
1.269     raeburn  4005:             if ($$last_resets{$part}) {  
1.270     albertel 4006:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4007: 					   $part);
                   4008:             }
1.269     raeburn  4009:             $result.='<input type="hidden" name="'.
                   4010:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4011:             $result.='<input type="hidden" name="'.
                   4012:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4013:             $aggregates{$part} = 1;
                   4014:         }
1.41      ng       4015: 	if ($type eq 'awarded') {
1.320     albertel 4016: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4017: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4018: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4019: 	    $result.='<input type="text" name="'.
1.89      albertel 4020: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4021:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4022: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4023: 	} elsif ($type eq 'solved') {
                   4024: 	    my ($status,$foo)=split(/_/,$score,2);
                   4025: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4026: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4027: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4028: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4029: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4030:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4031: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4032: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4033: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4034: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4035: 	} else {
                   4036: 	    $result.='<input type="hidden" name="'.
                   4037: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4038: 		    "\n";
1.233     albertel 4039: 	    $result.='<input type="text" name="'.
1.122     ng       4040: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4041: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4042: 	}
                   4043:     }
1.474     albertel 4044:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4045:     return $result;
1.38      ng       4046: }
                   4047: 
1.44      ng       4048: #--- change scores for all the students in a section/class
                   4049: #    record does not get update if unchanged
1.38      ng       4050: sub editgrades {
1.608     www      4051:     my ($request,$symb) = @_;
1.745     raeburn  4052:     my $toolsymb;
                   4053:     if ($symb =~ /ext\.tool$/) {
                   4054:         $toolsymb = $symb;
                   4055:     }
1.41      ng       4056: 
1.433     banghart 4057:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4058:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 4059:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       4060: 
1.477     albertel 4061:     my $result= &Apache::loncommon::start_data_table().
                   4062: 	&Apache::loncommon::start_data_table_header_row().
                   4063: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4064: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4065:     my %scoreptr = (
                   4066: 		    'correct'  =>'correct_by_override',
                   4067: 		    'incorrect'=>'incorrect_by_override',
                   4068: 		    'excused'  =>'excused',
                   4069: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4070:                     'credited' =>'credit_attempted',
1.43      ng       4071: 		    'nothing'  => '',
                   4072: 		    );
1.257     albertel 4073:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4074: 
1.44      ng       4075:     my (@partid);
                   4076:     my %weight = ();
1.54      albertel 4077:     my %columns = ();
1.44      ng       4078:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4079: 
1.582     raeburn  4080:     my $partserror;
                   4081:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4082:     if ($partserror) {
                   4083:         return &navmap_errormsg();
                   4084:     }
1.54      albertel 4085:     my $header;
1.257     albertel 4086:     while ($ctr < $env{'form.totalparts'}) {
                   4087: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4088: 	push(@partid,$partid);
1.257     albertel 4089: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4090: 	$ctr++;
1.54      albertel 4091:     }
1.324     albertel 4092:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4093:     my $totcolspan = 0;
1.54      albertel 4094:     foreach my $partid (@partid) {
1.478     albertel 4095: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4096: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4097: 	$columns{$partid}=2;
                   4098: 	foreach my $stores (@parts) {
                   4099: 	    my ($part,$type) = &split_part_type($stores);
                   4100: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4101: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4102: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4103: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4104:             my $narrowtext = &mt('Tries');
                   4105: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4106: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4107: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4108: 	    $columns{$partid}+=2;
                   4109: 	}
1.748     raeburn  4110:         $totcolspan += $columns{$partid};
1.54      albertel 4111:     }
                   4112:     foreach my $partid (@partid) {
1.324     albertel 4113: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4114: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4115: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4116: 	    '</th>';
1.54      albertel 4117: 
1.44      ng       4118:     }
1.477     albertel 4119:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4120: 	&Apache::loncommon::start_data_table_header_row().
                   4121: 	$header.
                   4122: 	&Apache::loncommon::end_data_table_header_row();
                   4123:     my @noupdate;
1.126     ng       4124:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4125:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4126: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4127: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4128: 	my %newrecord;
                   4129: 	my $updateflag = 0;
1.108     albertel 4130: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4131: 	my $canmodify = &canmodify($usec);
                   4132: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4133: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4134: 	if (!$canmodify) {
1.477     albertel 4135: 	    push(@noupdate,
1.748     raeburn  4136: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4137: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4138: 	    next;
                   4139: 	}
1.269     raeburn  4140:         my %aggregate = ();
                   4141:         my $aggregateflag = 0;
1.281     albertel 4142: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4143: 	foreach (@partid) {
1.257     albertel 4144: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4145: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4146: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4147: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4148: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4149: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4150: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4151: 	    my $score;
                   4152: 	    if ($partial eq '') {
1.257     albertel 4153: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4154: 	    } elsif ($partial > 0) {
                   4155: 		$score = 'correct_by_override';
                   4156: 	    } elsif ($partial == 0) {
                   4157: 		$score = 'incorrect_by_override';
                   4158: 	    }
1.257     albertel 4159: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4160: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4161: 
1.292     albertel 4162: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4163: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4164: 	    if ($dropMenu eq 'reset status' &&
                   4165: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4166: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4167: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4168: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4169: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4170: 		$updateflag = 1;
1.269     raeburn  4171:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4172:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4173:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4174:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4175:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4176:                     $aggregateflag = 1;
                   4177:                 }
1.139     albertel 4178: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4179: 		$updateflag = 1;
                   4180: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4181: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4182: 		$rec_update++;
1.125     ng       4183: 	    }
                   4184: 
1.93      albertel 4185: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4186: 		'<td align="center">'.$awarded.
                   4187: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4188: 
1.54      albertel 4189: 
                   4190: 	    my $partid=$_;
                   4191: 	    foreach my $stores (@parts) {
                   4192: 		my ($part,$type) = &split_part_type($stores);
                   4193: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4194: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4195: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4196: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4197: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4198: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4199: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4200: 		    $updateflag=1;
                   4201: 		}
1.93      albertel 4202: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4203: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4204: 	    }
1.44      ng       4205: 	}
1.477     albertel 4206: 	$line.="\n";
1.301     albertel 4207: 
                   4208: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4209: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4210: 
1.44      ng       4211: 	if ($updateflag) {
                   4212: 	    $count++;
1.257     albertel 4213: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4214: 				    $udom,$uname);
1.301     albertel 4215: 
                   4216: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4217: 					      $cnum,$udom,$uname)) {
                   4218: 		# need to figure out if should be in queue.
                   4219: 		my %record =  
                   4220: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4221: 					     $udom,$uname);
                   4222: 		my $all_graded = 1;
                   4223: 		my $none_graded = 1;
                   4224: 		foreach my $part (@parts) {
                   4225: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4226: 			$all_graded = 0;
                   4227: 		    } else {
                   4228: 			$none_graded = 0;
                   4229: 		    }
                   4230: 		}
                   4231: 
                   4232: 		if ($all_graded || $none_graded) {
                   4233: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4234: 							   $symb,$cdom,$cnum,
                   4235: 							   $udom,$uname);
                   4236: 		}
                   4237: 	    }
                   4238: 
1.477     albertel 4239: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4240: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4241: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4242: 	    $updateCtr++;
1.93      albertel 4243: 	} else {
1.477     albertel 4244: 	    push(@noupdate,
                   4245: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4246: 	    $noupdateCtr++;
1.44      ng       4247: 	}
1.269     raeburn  4248:         if ($aggregateflag) {
                   4249:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4250: 				  $cdom,$cnum);
1.269     raeburn  4251:         }
1.93      albertel 4252:     }
1.477     albertel 4253:     if (@noupdate) {
1.748     raeburn  4254:         my $numcols=$totcolspan+2;
1.477     albertel 4255: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4256: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4257: 	    &mt('No Changes Occurred For the Students Below').
                   4258: 	    '</td>'.
1.477     albertel 4259: 	    &Apache::loncommon::end_data_table_row();
                   4260: 	foreach my $line (@noupdate) {
                   4261: 	    $result.=
                   4262: 		&Apache::loncommon::start_data_table_row().
                   4263: 		$line.
                   4264: 		&Apache::loncommon::end_data_table_row();
                   4265: 	}
1.44      ng       4266:     }
1.614     www      4267:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4268:     my $msg = '<p><b>'.
                   4269: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4270: 	    $rec_update,$count).'</b><br />'.
                   4271: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4272: 	'</b></p>';
1.44      ng       4273:     return $title.$msg.$result;
1.5       albertel 4274: }
1.54      albertel 4275: 
                   4276: sub split_part_type {
                   4277:     my ($partstr) = @_;
                   4278:     my ($temp,@allparts)=split(/_/,$partstr);
                   4279:     my $type=pop(@allparts);
1.439     albertel 4280:     my $part=join('_',@allparts);
1.54      albertel 4281:     return ($part,$type);
                   4282: }
                   4283: 
1.44      ng       4284: #------------- end of section for handling grading by section/class ---------
                   4285: #
                   4286: #----------------------------------------------------------------------------
                   4287: 
1.5       albertel 4288: 
1.44      ng       4289: #----------------------------------------------------------------------------
                   4290: #
                   4291: #-------------------------- Next few routines handles grading by csv upload
                   4292: #
                   4293: #--- Javascript to handle csv upload
1.27      albertel 4294: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4295:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4296:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4297:   &js_escape(\$error1);
                   4298:   &js_escape(\$error2);
1.27      albertel 4299:   return(<<ENDPICK);
                   4300:   function verify(vf) {
                   4301:     var foundsomething=0;
                   4302:     var founduname=0;
1.243     albertel 4303:     var foundID=0;
1.743     raeburn  4304:     var foundclicker=0;
1.27      albertel 4305:     for (i=0;i<=vf.nfields.value;i++) {
                   4306:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4307:       if (i==0 && tw!=0) { foundID=1; }
                   4308:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4309:       if (i==2 && tw!=0) { foundclicker=1; }
                   4310:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4311:     }
1.743     raeburn  4312:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4313: 	alert('$error1');
                   4314: 	return;
1.27      albertel 4315:     }
                   4316:     if (foundsomething==0) {
1.246     albertel 4317: 	alert('$error2');
                   4318: 	return;
1.27      albertel 4319:     }
                   4320:     vf.submit();
                   4321:   }
                   4322:   function flip(vf,tf) {
                   4323:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4324:     var i;
                   4325:     for (i=0;i<=vf.nfields.value;i++) {
                   4326:       //can not pick the same destination field for both name and domain
                   4327:       if (((i ==0)||(i ==1)) && 
                   4328:           ((tf==0)||(tf==1)) && 
                   4329:           (i!=tf) &&
                   4330:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4331:         eval('vf.f'+i+'.selectedIndex=0;')
                   4332:       }
                   4333:     }
                   4334:   }
                   4335: ENDPICK
                   4336: }
                   4337: 
                   4338: sub csvupload_javascript_forward_associate {
1.743     raeburn  4339:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4340:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4341:   &js_escape(\$error1);
                   4342:   &js_escape(\$error2);
1.27      albertel 4343:   return(<<ENDPICK);
                   4344:   function verify(vf) {
                   4345:     var foundsomething=0;
                   4346:     var founduname=0;
1.243     albertel 4347:     var foundID=0;
1.743     raeburn  4348:     var foundclicker=0;
1.27      albertel 4349:     for (i=0;i<=vf.nfields.value;i++) {
                   4350:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4351:       if (tw==1) { foundID=1; }
                   4352:       if (tw==2) { founduname=1; }
1.745     raeburn  4353:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4354:       if (tw>4) { foundsomething=1; }
1.27      albertel 4355:     }
1.743     raeburn  4356:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4357: 	alert('$error1');
                   4358: 	return;
1.27      albertel 4359:     }
                   4360:     if (foundsomething==0) {
1.246     albertel 4361: 	alert('$error2');
                   4362: 	return;
1.27      albertel 4363:     }
                   4364:     vf.submit();
                   4365:   }
                   4366:   function flip(vf,tf) {
                   4367:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4368:     var i;
                   4369:     //can not pick the same destination field twice
                   4370:     for (i=0;i<=vf.nfields.value;i++) {
                   4371:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4372:         eval('vf.f'+i+'.selectedIndex=0;')
                   4373:       }
                   4374:     }
                   4375:   }
                   4376: ENDPICK
                   4377: }
                   4378: 
1.26      albertel 4379: sub csvuploadmap_header {
1.324     albertel 4380:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4381:     my $javascript;
1.257     albertel 4382:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4383: 	$javascript=&csvupload_javascript_reverse_associate();
                   4384:     } else {
                   4385: 	$javascript=&csvupload_javascript_forward_associate();
                   4386:     }
1.45      ng       4387: 
1.418     albertel 4388:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4389:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4390:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4391:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4392:     my $reverse=&mt("Reverse Association");
1.41      ng       4393:     $request->print(<<ENDPICK);
1.632     www      4394: <br />
                   4395: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4396: <input type="hidden" name="associate"  value="" />
                   4397: <input type="hidden" name="phase"      value="three" />
                   4398: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4399: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4400: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4401: <input type="hidden" name="upfile_associate" 
1.257     albertel 4402:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4403: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4404: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4405: <hr />
                   4406: ENDPICK
1.597     wenzelju 4407:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4408:     return '';
1.26      albertel 4409: 
                   4410: }
                   4411: 
                   4412: sub csvupload_fields {
1.582     raeburn  4413:     my ($symb,$errorref) = @_;
1.745     raeburn  4414:     my $toolsymb;
                   4415:     if ($symb =~ /ext\.tool$/) {
                   4416:         $toolsymb = $symb;
                   4417:     }
1.582     raeburn  4418:     my (@parts) = &getpartlist($symb,$errorref);
                   4419:     if (ref($errorref)) {
                   4420:         if ($$errorref) {
                   4421:             return;
                   4422:         }
                   4423:     }
                   4424: 
1.556     weissno  4425:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4426: 		['username','Student Username'],
1.743     raeburn  4427: 		['clicker','Clicker ID'],
1.243     albertel 4428: 		['domain','Student Domain']);
1.324     albertel 4429:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4430:     foreach my $part (sort(@parts)) {
                   4431: 	my @datum;
1.745     raeburn  4432: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4433: 	my $name=$part;
1.745     raeburn  4434: 	if (!$display) { $display = $name; }
1.41      ng       4435: 	@datum=($name,$display);
1.244     albertel 4436: 	if ($name=~/^stores_(.*)_awarded/) {
                   4437: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4438: 	}
1.41      ng       4439: 	push(@fields,\@datum);
                   4440:     }
                   4441:     return (@fields);
1.26      albertel 4442: }
                   4443: 
                   4444: sub csvuploadmap_footer {
1.41      ng       4445:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4446:     my $buttontext = &mt('Assign Grades');
1.41      ng       4447:     $request->print(<<ENDPICK);
1.26      albertel 4448: </table>
                   4449: <input type="hidden" name="nfields" value="$i" />
                   4450: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4451: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4452: </form>
                   4453: ENDPICK
                   4454: }
                   4455: 
1.283     albertel 4456: sub checkforfile_js {
1.638     www      4457:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4458:     &js_escape(\$alertmsg);
1.597     wenzelju 4459:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4460:     function checkUpload(formname) {
                   4461: 	if (formname.upfile.value == "") {
1.539     riegler  4462: 	    alert("$alertmsg");
1.86      ng       4463: 	    return false;
                   4464: 	}
                   4465: 	formname.submit();
                   4466:     }
                   4467: CSVFORMJS
1.283     albertel 4468:     return $result;
                   4469: }
                   4470: 
                   4471: sub upcsvScores_form {
1.608     www      4472:     my ($request,$symb) = @_;
1.283     albertel 4473:     if (!$symb) {return '';}
                   4474:     my $result=&checkforfile_js();
1.632     www      4475:     $result.=&Apache::loncommon::start_data_table().
                   4476:              &Apache::loncommon::start_data_table_header_row().
                   4477:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4478:              &Apache::loncommon::end_data_table_header_row().
                   4479:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4480:     my $upload=&mt("Upload Scores");
1.86      ng       4481:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4482:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4483:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4484:     $result.=<<ENDUPFORM;
1.106     albertel 4485: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4486: <input type="hidden" name="symb" value="$symb" />
                   4487: <input type="hidden" name="command" value="csvuploadmap" />
                   4488: $upfile_select
1.589     bisitz   4489: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4490: </form>
                   4491: ENDUPFORM
1.370     www      4492:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4493:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4494:              '</td>'.
                   4495:             &Apache::loncommon::end_data_table_row().
                   4496:             &Apache::loncommon::end_data_table();
1.86      ng       4497:     return $result;
                   4498: }
                   4499: 
                   4500: 
1.26      albertel 4501: sub csvuploadmap {
1.608     www      4502:     my ($request,$symb)= @_;
1.41      ng       4503:     if (!$symb) {return '';}
1.72      ng       4504: 
1.41      ng       4505:     my $datatoken;
1.257     albertel 4506:     if (!$env{'form.datatoken'}) {
1.41      ng       4507: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4508:     } else {
1.742     raeburn  4509: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4510:         if ($datatoken ne '') {
                   4511: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4512:         }
1.26      albertel 4513:     }
1.41      ng       4514:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4515:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4516:     my ($i,$keyfields);
                   4517:     if (@records) {
1.582     raeburn  4518:         my $fieldserror;
                   4519: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4520:         if ($fieldserror) {
                   4521:             $request->print(&navmap_errormsg());
                   4522:             return;
                   4523:         }
1.257     albertel 4524: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4525: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4526: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4527: 							  \@fields);
                   4528: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4529: 	    chop($keyfields);
                   4530: 	} else {
                   4531: 	    unshift(@fields,['none','']);
                   4532: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4533: 							    \@fields);
1.311     banghart 4534:             foreach my $rec (@records) {
                   4535:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4536:                 if (%temp) {
                   4537:                     $keyfields=join(',',sort(keys(%temp)));
                   4538:                     last;
                   4539:                 }
                   4540:             }
1.41      ng       4541: 	}
                   4542:     }
                   4543:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4544: 
1.41      ng       4545:     return '';
1.27      albertel 4546: }
                   4547: 
1.246     albertel 4548: sub csvuploadoptions {
1.608     www      4549:     my ($request,$symb)= @_;
1.632     www      4550:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4551:     $request->print(<<ENDPICK);
                   4552: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4553: <input type="hidden" name="command"    value="csvuploadassign" />
                   4554: <p>
                   4555: <label>
                   4556:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4557:    $overwrite
1.246     albertel 4558: </label>
                   4559: </p>
                   4560: ENDPICK
                   4561:     my %fields=&get_fields();
                   4562:     if (!defined($fields{'domain'})) {
1.257     albertel 4563: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4564: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4565:     }
1.257     albertel 4566:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4567: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4568: 	my $cleankey=$1;
                   4569: 	if ($cleankey eq 'command') { next; }
                   4570: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4571: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4572:     }
                   4573:     # FIXME do a check for any duplicated user ids...
                   4574:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4575:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4576: <hr /></form>'."\n");
1.246     albertel 4577:     return '';
                   4578: }
                   4579: 
                   4580: sub get_fields {
                   4581:     my %fields;
1.257     albertel 4582:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4583:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4584: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4585: 	    if ($env{'form.f'.$i} ne 'none') {
                   4586: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4587: 	    }
                   4588: 	} else {
1.257     albertel 4589: 	    if ($env{'form.f'.$i} ne 'none') {
                   4590: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4591: 	    }
                   4592: 	}
1.27      albertel 4593:     }
1.246     albertel 4594:     return %fields;
                   4595: }
                   4596: 
                   4597: sub csvuploadassign {
1.608     www      4598:     my ($request,$symb)= @_;
1.246     albertel 4599:     if (!$symb) {return '';}
1.345     bowersj2 4600:     my $error_msg = '';
1.742     raeburn  4601:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4602:     if ($datatoken ne '') { 
                   4603:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4604:     }
1.246     albertel 4605:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4606:     my %fields=&get_fields();
1.257     albertel 4607:     my $courseid=$env{'request.course.id'};
1.97      albertel 4608:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4609:     my @notallowed;
1.41      ng       4610:     my @skipped;
1.657     raeburn  4611:     my @warnings;
1.41      ng       4612:     my $countdone=0;
                   4613:     foreach my $grade (@gradedata) {
                   4614: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4615: 	my $domain;
                   4616: 	if ($entries{$fields{'domain'}}) {
                   4617: 	    $domain=$entries{$fields{'domain'}};
                   4618: 	} else {
1.257     albertel 4619: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4620: 	}
1.243     albertel 4621: 	$domain=~s/\s//g;
1.41      ng       4622: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4623: 	$username=~s/\s//g;
1.243     albertel 4624: 	if (!$username) {
                   4625: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4626: 	    $id=~s/\s//g;
1.737     raeburn  4627:             if ($id ne '') {
                   4628: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4629: 	        $username=$ids{$id};
                   4630:             } else {
                   4631:                 if ($entries{$fields{'clicker'}}) {
                   4632:                     my $clicker = $entries{$fields{'clicker'}};
                   4633:                     $clicker=~s/\s//g;
                   4634:                     if ($clicker ne '') {
                   4635:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4636:                         if ($clickers{$clicker} ne '') {  
                   4637:                             my $match = 0;
                   4638:                             my @inclass;
                   4639:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4640:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4641:                                     $username = $poss;
                   4642:                                     push(@inclass,$poss);
                   4643:                                     $match ++;
                   4644:                                     
                   4645:                                 }
                   4646:                             }
                   4647:                             if ($match > 1) {
                   4648:                                 undef($username); 
                   4649:                                 $request->print('<p class="LC_warning">'.
                   4650:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4651:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4652:                             }
                   4653:                         }
                   4654:                     }
                   4655:                 }
                   4656:             }
1.243     albertel 4657: 	}
1.41      ng       4658: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4659: 	    my $id=$entries{$fields{'ID'}};
                   4660: 	    $id=~s/\s//g;
1.737     raeburn  4661:             my $clicker = $entries{$fields{'clicker'}};
                   4662:             $clicker=~s/\s//g;
                   4663:             if ($clicker) {
                   4664:                 push(@skipped,"$clicker:$domain");
                   4665: 	    } elsif ($id) {
1.247     albertel 4666: 		push(@skipped,"$id:$domain");
                   4667: 	    } else {
                   4668: 		push(@skipped,"$username:$domain");
                   4669: 	    }
1.41      ng       4670: 	    next;
                   4671: 	}
1.108     albertel 4672: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4673: 	if (!&canmodify($usec)) {
                   4674: 	    push(@notallowed,"$username:$domain");
                   4675: 	    next;
                   4676: 	}
1.244     albertel 4677: 	my %points;
1.41      ng       4678: 	my %grades;
                   4679: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4680: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4681: 		$dest eq 'domain') { next; }
                   4682: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4683: 	    if ($dest=~/stores_(.*)_points/) {
                   4684: 		my $part=$1;
                   4685: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4686: 					      $symb,$domain,$username);
1.345     bowersj2 4687:                 if ($wgt) {
                   4688:                     $entries{$fields{$dest}}=~s/\s//g;
                   4689:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4690:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4691:                                           : 'correct_by_override';
1.638     www      4692:                     if ($pcr>1) {
1.657     raeburn  4693:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4694:                     }
1.345     bowersj2 4695:                     $grades{"resource.$part.awarded"}=$pcr;
                   4696:                     $grades{"resource.$part.solved"}=$award;
                   4697:                     $points{$part}=1;
                   4698:                 } else {
                   4699:                     $error_msg = "<br />" .
                   4700:                         &mt("Some point values were assigned"
                   4701:                             ." for problems with a weight "
                   4702:                             ."of zero. These values were "
                   4703:                             ."ignored.");
                   4704:                 }
1.244     albertel 4705: 	    } else {
                   4706: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4707: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4708: 		my $store_key=$dest;
                   4709: 		$store_key=~s/^stores/resource/;
                   4710: 		$store_key=~s/_/\./g;
                   4711: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4712: 	    }
1.41      ng       4713: 	}
1.508     www      4714: 	if (! %grades) { 
                   4715:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4716:         } else {
                   4717: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4718: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4719: 					   $env{'request.course.id'},
                   4720: 					   $domain,$username);
1.508     www      4721: 	   if ($result eq 'ok') {
1.627     www      4722: # Successfully stored
1.508     www      4723: 	      $request->print('.');
1.627     www      4724: # Remove from grading queue
                   4725:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4726:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4727:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4728:                                              $domain,$username);
                   4729:               $countdone++;
                   4730:            } else {
1.508     www      4731: 	      $request->print("<p><span class=\"LC_error\">".
                   4732:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4733:                                   "$username:$domain",$result)."</span></p>");
                   4734: 	   }
                   4735: 	   $request->rflush();
                   4736:         }
1.41      ng       4737:     }
1.570     www      4738:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4739:     if (@warnings) {
                   4740:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4741:         $request->print(join(', ',@warnings));
                   4742:     }
1.41      ng       4743:     if (@skipped) {
1.571     www      4744: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4745:         $request->print(join(', ',@skipped));
1.106     albertel 4746:     }
                   4747:     if (@notallowed) {
1.571     www      4748: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4749: 	$request->print(join(', ',@notallowed));
1.41      ng       4750:     }
1.106     albertel 4751:     $request->print("<br />\n");
1.345     bowersj2 4752:     return $error_msg;
1.26      albertel 4753: }
1.44      ng       4754: #------------- end of section for handling csv file upload ---------
                   4755: #
                   4756: #-------------------------------------------------------------------
                   4757: #
1.122     ng       4758: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4759: #
                   4760: #--- Select a page/sequence and a student to grade
1.68      ng       4761: sub pickStudentPage {
1.608     www      4762:     my ($request,$symb) = @_;
1.68      ng       4763: 
1.539     riegler  4764:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4765:     &js_escape(\$alertmsg);
1.597     wenzelju 4766:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4767: 
                   4768: function checkPickOne(formname) {
1.76      ng       4769:     if (radioSelection(formname.student) == null) {
1.539     riegler  4770: 	alert("$alertmsg");
1.68      ng       4771: 	return;
                   4772:     }
1.125     ng       4773:     ptr = pullDownSelection(formname.selectpage);
                   4774:     formname.page.value = formname["page"+ptr].value;
                   4775:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4776:     formname.submit();
                   4777: }
                   4778: 
                   4779: LISTJAVASCRIPT
1.118     ng       4780:     &commonJSfunctions($request);
1.608     www      4781: 
1.257     albertel 4782:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4783:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4784:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4785: 
1.398     albertel 4786:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4787: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4788: 
1.80      ng       4789:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4790:     my $map_error;
                   4791:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4792:     if ($map_error) {
                   4793:         $request->print(&navmap_errormsg());
                   4794:         return; 
                   4795:     }
1.137     albertel 4796:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4797: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4798: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4799: 
                   4800:     # Collection of hidden fields
1.70      ng       4801:     my $ctr=0;
1.68      ng       4802:     foreach (@$titles) {
1.700     bisitz   4803:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4804:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4805:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4806:         $ctr++;
1.68      ng       4807:     }
1.700     bisitz   4808:     $result.='<input type="hidden" name="page" />'."\n".
                   4809:         '<input type="hidden" name="title" />'."\n";
                   4810: 
                   4811:     $result.=&build_section_inputs();
                   4812:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4813:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4814: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4815: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4816: 
1.700     bisitz   4817:     # Show grading options
                   4818:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4819:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4820:     $ctr=0;
                   4821:     foreach (@$titles) {
                   4822: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4823: 	$select.='<option value="'.$ctr.'"'.
                   4824: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4825: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4826: 	$ctr++;
                   4827:     }
1.700     bisitz   4828:     $select.= '</select>';
1.68      ng       4829: 
1.700     bisitz   4830:     $result.=
                   4831:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4832:        .$select
                   4833:        .&Apache::lonhtmlcommon::row_closure();
                   4834: 
                   4835:     $result.=
                   4836:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4837:        .'<label><input type="radio" name="vProb" value="no"'
                   4838:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4839:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4840:            .&mt('yes').'</label>'."\n"
                   4841:        .&Apache::lonhtmlcommon::row_closure();
                   4842: 
                   4843:     $result.=
                   4844:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4845:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4846:            .&mt('none').' </label>'."\n"
                   4847:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4848:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4849:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4850:            .&mt('all submissions with details').' </label>'
                   4851:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4852:     
1.700     bisitz   4853:     $result.=
                   4854:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4855:        .'<input type="text" name="CODE" value="" />'
                   4856:        .&Apache::lonhtmlcommon::row_closure(1)
                   4857:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4858: 
1.700     bisitz   4859:     # Show list of students to select for grading
                   4860:     $result.='<br /><input type="button" '.
1.589     bisitz   4861:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4862: 
1.68      ng       4863:     $request->print($result);
                   4864: 
1.485     albertel 4865:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4866: 	&Apache::loncommon::start_data_table().
                   4867: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4868: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4869: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4870: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4871: 	'<th>'.&nameUserString('header').'</th>'.
                   4872: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4873:  
1.76      ng       4874:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4875:     my $ptr = 1;
1.294     albertel 4876:     foreach my $student (sort 
                   4877: 			 {
                   4878: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4879: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4880: 			     }
                   4881: 			     return $a cmp $b;
                   4882: 			 } (keys(%$fullname))) {
1.68      ng       4883: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4884: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4885:                                   : '</td>');
1.126     ng       4886: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4887: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4888: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4889: 	$studentTable.=
                   4890: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4891:                          : '');
1.68      ng       4892: 	$ptr++;
                   4893:     }
1.484     albertel 4894:     if ($ptr%2 == 0) {
                   4895: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4896: 	    &Apache::loncommon::end_data_table_row();
                   4897:     }
                   4898:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4899:     $studentTable.='<input type="button" '.
1.589     bisitz   4900:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4901: 
                   4902:     $request->print($studentTable);
                   4903: 
                   4904:     return '';
                   4905: }
                   4906: 
                   4907: sub getSymbMap {
1.582     raeburn  4908:     my ($map_error) = @_;
1.132     bowersj2 4909:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4910:     unless (ref($navmap)) {
                   4911:         if (ref($map_error)) {
                   4912:             $$map_error = 'navmap';
                   4913:         }
                   4914:         return;
                   4915:     }
1.68      ng       4916:     my %symbx = ();
                   4917:     my @titles = ();
1.117     bowersj2 4918:     my $minder = 0;
                   4919: 
                   4920:     # Gather every sequence that has problems.
1.240     albertel 4921:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4922: 					       1,0,1);
1.117     bowersj2 4923:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  4924: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 4925: 	    my $title = $minder.'.'.
                   4926: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4927: 	    push(@titles, $title); # minder in case two titles are identical
                   4928: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4929: 	    $minder++;
1.241     albertel 4930: 	}
1.68      ng       4931:     }
                   4932:     return \@titles,\%symbx;
                   4933: }
                   4934: 
1.72      ng       4935: #
                   4936: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4937: sub displayPage {
1.608     www      4938:     my ($request,$symb) = @_;
1.257     albertel 4939:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4940:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4941:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4942:     my $pageTitle = $env{'form.page'};
1.103     albertel 4943:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4944:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4945:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4946: 
                   4947:     #need to make sure we have the correct data for later EXT calls, 
                   4948:     #thus invalidate the cache
                   4949:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4950:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4951:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4952:     &Apache::lonnet::clear_EXT_cache_status();
                   4953: 
1.103     albertel 4954:     if (!&canview($usec)) {
1.712     bisitz   4955:         $request->print(
                   4956:             '<span class="LC_warning">'.
                   4957:             &mt('Unable to view requested student. ([_1])',
                   4958:                     $env{'form.student'}).
                   4959:             '</span>');
                   4960:         return;
1.103     albertel 4961:     }
1.398     albertel 4962:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4963:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4964: 	'</h3>'."\n";
1.500     albertel 4965:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4966:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4967: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4968:     } else {
                   4969: 	delete($env{'form.CODE'});
                   4970:     }
1.71      ng       4971:     &sub_page_js($request);
                   4972:     $request->print($result);
                   4973: 
1.132     bowersj2 4974:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4975:     unless (ref($navmap)) {
                   4976:         $request->print(&navmap_errormsg());
                   4977:         return;
                   4978:     }
1.257     albertel 4979:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4980:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4981:     if (!$map) {
1.485     albertel 4982: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4983: 	return; 
                   4984:     }
1.68      ng       4985:     my $iterator = $navmap->getIterator($map->map_start(),
                   4986: 					$map->map_finish());
                   4987: 
1.71      ng       4988:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4989: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4990: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4991: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4992: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4993: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4994: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4995: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4996: 
1.382     albertel 4997:     if (defined($env{'form.CODE'})) {
                   4998: 	$studentTable.=
                   4999: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5000:     }
1.381     albertel 5001:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5002: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5003: 
1.594     bisitz   5004:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5005:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5006:         '</span>'."\n".
1.484     albertel 5007: 	&Apache::loncommon::start_data_table().
                   5008: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5009: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5010: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5011: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5012: 
1.329     albertel 5013:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5014:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5015:     $iterator->next(); # skip the first BEGIN_MAP
                   5016:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5017:     while ($depth > 0) {
1.68      ng       5018:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5019:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5020: 
1.745     raeburn  5021:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5022: 	    my $parts = $curRes->parts();
1.68      ng       5023:             my $title = $curRes->compTitle();
1.71      ng       5024: 	    my $symbx = $curRes->symb();
1.746     raeburn  5025:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5026: 	    $studentTable.=
                   5027: 		&Apache::loncommon::start_data_table_row().
                   5028: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5029: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5030: 		                        : '<br />('.&mt('[_1]parts',
                   5031: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5032: 		 ).
                   5033: 		 '</td>';
1.71      ng       5034: 	    $studentTable.='<td valign="top">';
1.382     albertel 5035: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749   ! raeburn  5036:             if ($is_tool) {
        !          5037:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
        !          5038:             } else {
1.745     raeburn  5039: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5040: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5041: 					         undef,'both',\%form);
                   5042: 	        } else {
                   5043: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5044: 		    $companswer =~ s|<form(.*?)>||g;
                   5045: 		    $companswer =~ s|</form>||g;
                   5046: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5047: #		        $companswer =~ s/$1/ /ms;
                   5048: #		        $request->print('match='.$1."<br />\n");
                   5049: #		    }
                   5050: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5051: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5052: 		}
1.71      ng       5053: 	    }
                   5054: 
1.257     albertel 5055: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5056: 
1.257     albertel 5057: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5058: 		if ($record{'version'} eq '') {
1.745     raeburn  5059:                     my $msg = &mt('No recorded submission for this problem.');
                   5060:                     if ($is_tool) {
                   5061:                         $msg = &mt('No recorded transactions for this external tool');
                   5062:                     }
                   5063: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5064: 		} else {
1.116     ng       5065: 		    my %responseType = ();
                   5066: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5067: 			my @responseIds =$curRes->responseIds($partid);
                   5068: 			my @responseType =$curRes->responseType($partid);
                   5069: 			my %responseIds;
                   5070: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5071: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5072: 			}
                   5073: 			$responseType{$partid} = \%responseIds;
1.116     ng       5074: 		    }
1.148     albertel 5075: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5076: 		}
1.257     albertel 5077: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5078: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5079:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5080: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5081: 									$env{'request.course.id'},
1.726     raeburn  5082: 									'','.submission',undef,
                   5083:                                                                         $usec,$identifier);
1.71      ng       5084:  
                   5085: 	    }
1.103     albertel 5086: 	    if (&canmodify($usec)) {
1.585     bisitz   5087:             $studentTable.=&gradeBox_start();
1.103     albertel 5088: 		foreach my $partid (@{$parts}) {
                   5089: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5090: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5091: 		    $question++;
                   5092: 		}
1.585     bisitz   5093:             $studentTable.=&gradeBox_end();
1.196     albertel 5094: 		$prob++;
1.71      ng       5095: 	    }
                   5096: 	    $studentTable.='</td></tr>';
1.68      ng       5097: 
1.103     albertel 5098: 	}
1.68      ng       5099:         $curRes = $iterator->next();
                   5100:     }
                   5101: 
1.589     bisitz   5102:     $studentTable.=
                   5103:         '</table>'."\n".
                   5104:         '<input type="button" value="'.&mt('Save').'" '.
                   5105:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5106:         '</form>'."\n";
1.71      ng       5107:     $request->print($studentTable);
                   5108: 
                   5109:     return '';
1.119     ng       5110: }
                   5111: 
                   5112: sub displaySubByDates {
1.148     albertel 5113:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5114:     my $isCODE=0;
1.335     albertel 5115:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5116:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5117:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5118:     my $studentTable=&Apache::loncommon::start_data_table().
                   5119: 	&Apache::loncommon::start_data_table_header_row().
                   5120: 	'<th>'.&mt('Date/Time').'</th>'.
                   5121: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5122:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749   ! raeburn  5123: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5124: 	'<th>'.&mt('Status').'</th>'.
                   5125: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5126:     my ($version);
                   5127:     my %mark;
1.148     albertel 5128:     my %orders;
1.119     ng       5129:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5130:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5131:         if ($is_tool) {
                   5132:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5133:         } else {
                   5134:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5135:         }
1.147     albertel 5136:     }
1.335     albertel 5137: 
                   5138:     my $interaction;
1.525     raeburn  5139:     my $no_increment = 1;
1.735     raeburn  5140:     my (%lastrndseed,%lasttype);
1.119     ng       5141:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5142: 	my $timestamp = 
                   5143: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5144: 	if (exists($$record{$version.':resource.0.version'})) {
                   5145: 	    $interaction = $$record{$version.':resource.0.version'};
                   5146: 	}
1.671     raeburn  5147:         if ($isTask && $env{'form.previousversion'}) {
                   5148:             next unless ($interaction == $env{'form.previousversion'});
                   5149:         }
1.335     albertel 5150: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5151: 		             : "$version:resource");
1.467     albertel 5152: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5153: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5154: 	if ($isCODE) {
                   5155: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5156: 	}
1.671     raeburn  5157:         if ($isTask) {
                   5158:             $studentTable.='<td>'.$interaction.'</td>';
                   5159:         }
1.119     ng       5160: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5161: 	my @displaySub = ();
                   5162: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5163:             my ($hidden,$type);
                   5164:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5165:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5166:                 $hidden = 1;
                   5167:             }
1.749   ! raeburn  5168:             my @matchKey;
        !          5169:             if ($isTask) {
        !          5170:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
        !          5171:             } elsif ($is_tool) {
        !          5172:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
        !          5173:             } else {
        !          5174:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
        !          5175:             }
1.122     ng       5176: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5177: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5178: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5179: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5180: 		    $$record{$version.':'.$matchKey} ne '') {
1.749   ! raeburn  5181:                     if ($is_tool) {
        !          5182:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5183:                     } else {
1.749   ! raeburn  5184: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
        !          5185: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
        !          5186:                         $displaySub[0].='<span class="LC_nobreak">';
        !          5187:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
        !          5188:                                        .' <span class="LC_internal_info">'
        !          5189:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
        !          5190:                                        .'</span>'
        !          5191:                                        .' <b>';
        !          5192:                         if ($hidden) {
        !          5193:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
        !          5194:                         } else {
        !          5195:                             my ($trial,$rndseed,$newvariation);
        !          5196:                             if ($type eq 'randomizetry') {
        !          5197:                                 $trial = $$record{"$where.$partid.tries"};
        !          5198:                                 $rndseed = $$record{"$where.$partid.rndseed"};
        !          5199:                             }
        !          5200: 		            if ($$record{"$where.$partid.tries"} eq '') {
        !          5201: 			        $displaySub[0].=&mt('Trial not counted');
        !          5202: 		            } else {
        !          5203: 			        $displaySub[0].=&mt('Trial: [_1]',
        !          5204: 					        $$record{"$where.$partid.tries"});
        !          5205:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
        !          5206:                                     if (($rndseed ne $lastrndseed{$partid}) &&
        !          5207:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
        !          5208:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
        !          5209:                                     }
1.640     raeburn  5210:                                 }
1.749   ! raeburn  5211:                                 $lastrndseed{$partid} = $rndseed;
        !          5212:                                 $lasttype{$partid} = $type;
        !          5213: 		            }
        !          5214: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5215:                                               : $responseType->{$partid}->{$responseId});
1.749   ! raeburn  5216: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
        !          5217: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
        !          5218: 			        $orders{$partid}->{$responseId}=
        !          5219: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
        !          5220:                                                $no_increment,$type,$trial,$rndseed);
        !          5221: 		            }
        !          5222: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
        !          5223: 		            $displaySub[0].='&nbsp; '.
        !          5224: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
        !          5225:                         }
1.596     raeburn  5226:                     }
1.147     albertel 5227: 		}
                   5228: 	    }
1.335     albertel 5229: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5230: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5231: 				    $$record{"$where.$partid.checkedin"},
                   5232: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5233: 					'<br />';
1.335     albertel 5234: 	    }
                   5235: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5236: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5237: 		    lc($$record{"$where.$partid.award"}).' '.
                   5238: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5239: 		    '<br />';
1.749   ! raeburn  5240: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
        !          5241: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
        !          5242: 		    $displaySub[1].=&mt('Grade passed back by external tool');
        !          5243: 		}
1.147     albertel 5244: 	    }
1.335     albertel 5245: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749   ! raeburn  5246: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
        !          5247: 		unless ($is_tool) {
        !          5248: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
        !          5249: 		}
1.335     albertel 5250: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5251: 		$displaySub[2].=
1.749   ! raeburn  5252: 		    $$record{"$version:resource.$partid.regrader"};
        !          5253:                 unless ($is_tool) {
        !          5254: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
        !          5255:                 }
1.147     albertel 5256: 	    }
                   5257: 	}
                   5258: 	# needed because old essay regrader has not parts info
                   5259: 	if (exists $$record{"$version:resource.regrader"}) {
                   5260: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5261: 	}
                   5262: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5263: 	if ($displaySub[2]) {
1.467     albertel 5264: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5265: 	}
1.467     albertel 5266: 	$studentTable.='&nbsp;</td>'.
                   5267: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5268:     }
1.467     albertel 5269:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5270:     return $studentTable;
1.71      ng       5271: }
                   5272: 
                   5273: sub updateGradeByPage {
1.608     www      5274:     my ($request,$symb) = @_;
1.71      ng       5275: 
1.257     albertel 5276:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5277:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5278:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5279:     my $pageTitle = $env{'form.page'};
1.103     albertel 5280:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5281:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5282:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5283:     if (!&canmodify($usec)) {
1.526     raeburn  5284: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5285: 	return;
                   5286:     }
1.398     albertel 5287:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5288:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5289: 	'</h3>'."\n";
1.70      ng       5290: 
1.68      ng       5291:     $request->print($result);
                   5292: 
1.582     raeburn  5293: 
1.132     bowersj2 5294:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5295:     unless (ref($navmap)) {
                   5296:         $request->print(&navmap_errormsg());
                   5297:         return;
                   5298:     }
1.257     albertel 5299:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5300:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5301:     if (!$map) {
1.527     raeburn  5302: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5303: 	return; 
                   5304:     }
1.71      ng       5305:     my $iterator = $navmap->getIterator($map->map_start(),
                   5306: 					$map->map_finish());
1.70      ng       5307: 
1.484     albertel 5308:     my $studentTable=
                   5309: 	&Apache::loncommon::start_data_table().
                   5310: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5311: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5312: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5313: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5314: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5315: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5316: 
                   5317:     $iterator->next(); # skip the first BEGIN_MAP
                   5318:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5319:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5320:     while ($depth > 0) {
1.71      ng       5321:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5322:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5323: 
1.385     albertel 5324:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5325: 	    my $parts = $curRes->parts();
1.71      ng       5326:             my $title = $curRes->compTitle();
                   5327: 	    my $symbx = $curRes->symb();
1.484     albertel 5328: 	    $studentTable.=
                   5329: 		&Apache::loncommon::start_data_table_row().
                   5330: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5331: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5332:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5333: 		.')').'</td>';
1.71      ng       5334: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5335: 
                   5336: 	    my %newrecord=();
                   5337: 	    my @displayPts=();
1.269     raeburn  5338:             my %aggregate = ();
                   5339:             my $aggregateflag = 0;
1.726     raeburn  5340:             if ($env{'form.HIDE'.$prob}) {
                   5341:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5342:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5343:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5344:                 $hideflag += $numchgs;
                   5345:             }
1.71      ng       5346: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5347: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5348: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5349: 
1.257     albertel 5350: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5351: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5352: 		my $partial = $newpts/$wgt;
                   5353: 		my $score;
                   5354: 		if ($partial > 0) {
                   5355: 		    $score = 'correct_by_override';
1.125     ng       5356: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5357: 		    $score = 'incorrect_by_override';
                   5358: 		}
1.257     albertel 5359: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5360: 		if ($dropMenu eq 'excused') {
1.71      ng       5361: 		    $partial = '';
                   5362: 		    $score = 'excused';
1.125     ng       5363: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5364: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5365: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5366: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5367: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5368: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5369: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5370: 		    $changeflag++;
                   5371: 		    $newpts = '';
1.269     raeburn  5372:                     
                   5373:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5374:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5375:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5376:                     if ($aggtries > 0) {
                   5377:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5378:                         $aggregateflag = 1;
                   5379:                     }
1.71      ng       5380: 		}
1.324     albertel 5381: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5382: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5383: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5384: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5385: 		    '&nbsp;<br />';
1.526     raeburn  5386: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5387: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5388: 		    '&nbsp;<br />';
1.71      ng       5389: 		$question++;
1.380     albertel 5390: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5391: 
1.71      ng       5392: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5393: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5394: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5395: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5396: 
                   5397: 		$changeflag++;
                   5398: 	    }
                   5399: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5400: 		my %record = 
                   5401: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5402: 					     $udom,$uname);
                   5403: 
                   5404: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5405: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5406: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5407: 		    $newrecord{'resource.CODE'} = '';
                   5408: 		}
1.257     albertel 5409: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5410: 					$udom,$uname);
1.382     albertel 5411: 		%record = &Apache::lonnet::restore($symbx,
                   5412: 						   $env{'request.course.id'},
                   5413: 						   $udom,$uname);
1.380     albertel 5414: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5415: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5416: 	    }
1.380     albertel 5417: 	    
1.269     raeburn  5418:             if ($aggregateflag) {
                   5419:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5420:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5421:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5422:             }
1.125     ng       5423: 
1.71      ng       5424: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5425: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5426: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5427: 
1.196     albertel 5428: 	    $prob++;
1.68      ng       5429: 	}
1.71      ng       5430:         $curRes = $iterator->next();
1.68      ng       5431:     }
1.98      albertel 5432: 
1.484     albertel 5433:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5434:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5435: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5436: 		  $changeflag).'<br />');
                   5437:     my $hidemsg=($hideflag == 0 ? '' :
                   5438:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5439:                      $hideflag).'<br />');
                   5440:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5441: 
1.70      ng       5442:     return '';
                   5443: }
                   5444: 
1.72      ng       5445: #-------- end of section for handling grading by page/sequence ---------
                   5446: #
                   5447: #-------------------------------------------------------------------
                   5448: 
1.581     www      5449: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5450: #
                   5451: #------ start of section for handling grading by page/sequence ---------
                   5452: 
1.423     albertel 5453: =pod
                   5454: 
                   5455: =head1 Bubble sheet grading routines
                   5456: 
1.424     albertel 5457:   For this documentation:
                   5458: 
                   5459:    'scanline' refers to the full line of characters
                   5460:    from the file that we are parsing that represents one entire sheet
                   5461: 
                   5462:    'bubble line' refers to the data
1.659     raeburn  5463:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5464: 
                   5465: 
1.659     raeburn  5466: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5467: into a course. When a user wants to grade, they select a
1.659     raeburn  5468: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5469: one of the predefined configurations for what each scanline looks
                   5470: like.
                   5471: 
                   5472: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5473: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5474: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5475: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5476: invalid student/employee ID
1.424     albertel 5477: 
                   5478: If the CODE option is used that determines the randomization of the
1.556     weissno  5479: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5480: username:domain.
                   5481: 
                   5482: During the validation phase the instructor can choose to skip scanlines. 
                   5483: 
1.659     raeburn  5484: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5485: 
                   5486:   scantron_original_filename (unmodified original file)
                   5487:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5488:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5489: 
                   5490: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5491: correction information that isn't representable in the bubblesheet
1.424     albertel 5492: file (see &scantron_getfile() for more information)
                   5493: 
                   5494: After all scanlines are either valid, marked as valid or skipped, then
                   5495: foreach line foreach problem in the picked sequence, an ssi request is
                   5496: made that simulates a user submitting their selected letter(s) against
                   5497: the homework problem.
1.423     albertel 5498: 
                   5499: =over 4
                   5500: 
                   5501: 
                   5502: 
                   5503: =item defaultFormData
                   5504: 
                   5505:   Returns html hidden inputs used to hold context/default values.
                   5506: 
                   5507:  Arguments:
                   5508:   $symb - $symb of the current resource 
                   5509: 
                   5510: =cut
1.422     foxr     5511: 
1.81      albertel 5512: sub defaultFormData {
1.324     albertel 5513:     my ($symb)=@_;
1.613     www      5514:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5515: }
                   5516: 
1.447     foxr     5517: 
1.423     albertel 5518: =pod 
                   5519: 
                   5520: =item getSequenceDropDown
                   5521: 
                   5522:    Return html dropdown of possible sequences to grade
                   5523:  
                   5524:  Arguments:
1.582     raeburn  5525:    $symb - $symb of the current resource
                   5526:    $map_error - ref to scalar which will container error if
                   5527:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5528: 
                   5529: =cut
1.422     foxr     5530: 
1.75      albertel 5531: sub getSequenceDropDown {
1.582     raeburn  5532:     my ($symb,$map_error)=@_;
1.75      albertel 5533:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5534:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5535:     if (ref($map_error)) {
                   5536:         return if ($$map_error);
                   5537:     }
1.137     albertel 5538:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5539:     my $ctr=0;
                   5540:     foreach (@$titles) {
                   5541: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5542: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5543: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5544: 	    '>'.$showtitle.'</option>'."\n";
                   5545: 	$ctr++;
                   5546:     }
                   5547:     $result.= '</select>';
                   5548:     return $result;
                   5549: }
                   5550: 
1.495     albertel 5551: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5552:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5553: 
                   5554: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5555: 
1.509     raeburn  5556: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5557:                                    # matchresponse or rankresponse, where 
                   5558:                                    # an individual response can have multiple 
                   5559:                                    # lines
1.503     raeburn  5560: 
                   5561: my %responsetype_per_response;     # responsetype for each response
                   5562: 
1.691     raeburn  5563: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5564:                                    # numbered response. Needed when randomorder
                   5565:                                    # or randompick are in use. Key is ID, value 
                   5566:                                    # is response number.
                   5567: 
1.495     albertel 5568: # Save and restore the bubble lines array to the form env.
                   5569: 
                   5570: 
                   5571: sub save_bubble_lines {
                   5572:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5573: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5574: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5575: 	    $first_bubble_line{$line};
1.503     raeburn  5576:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5577:             $subdivided_bubble_lines{$line};
                   5578:         $env{"form.scantron.responsetype.$line"} =
                   5579:             $responsetype_per_response{$line};
1.495     albertel 5580:     }
1.691     raeburn  5581:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5582:         my $line = $masterseq_id_responsenum{$resid};
                   5583:         $env{"form.scantron.residpart.$line"} = $resid;
                   5584:     }
1.495     albertel 5585: }
                   5586: 
                   5587: 
                   5588: sub restore_bubble_lines {
                   5589:     my $line = 0;
                   5590:     %bubble_lines_per_response = ();
1.691     raeburn  5591:     %masterseq_id_responsenum = ();
1.495     albertel 5592:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5593: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5594: 	$bubble_lines_per_response{$line} = $value;
                   5595: 	$first_bubble_line{$line}  =
                   5596: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5597:         $subdivided_bubble_lines{$line} =
                   5598:             $env{"form.scantron.sub_bubblelines.$line"};
                   5599:         $responsetype_per_response{$line} =
                   5600:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5601:         my $id = $env{"form.scantron.residpart.$line"};
                   5602:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5603: 	$line++;
                   5604:     }
                   5605: }
                   5606: 
1.423     albertel 5607: =pod 
                   5608: 
                   5609: =item scantron_filenames
                   5610: 
                   5611:    Returns a list of the scantron files in the current course 
                   5612: 
                   5613: =cut
1.422     foxr     5614: 
1.202     albertel 5615: sub scantron_filenames {
1.257     albertel 5616:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5617:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5618:     my $getpropath = 1;
1.662     raeburn  5619:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5620:                                                         $cname,$getpropath);
1.202     albertel 5621:     my @possiblenames;
1.662     raeburn  5622:     if (ref($dirlist) eq 'ARRAY') {
                   5623:         foreach my $filename (sort(@{$dirlist})) {
                   5624: 	    ($filename)=split(/&/,$filename);
                   5625: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5626: 	    $filename=~s/^scantron_orig_//;
                   5627: 	    push(@possiblenames,$filename);
                   5628:         }
1.202     albertel 5629:     }
                   5630:     return @possiblenames;
                   5631: }
                   5632: 
1.423     albertel 5633: =pod 
                   5634: 
                   5635: =item scantron_uploads
                   5636: 
                   5637:    Returns  html drop-down list of scantron files in current course.
                   5638: 
                   5639:  Arguments:
                   5640:    $file2grade - filename to set as selected in the dropdown
                   5641: 
                   5642: =cut
1.422     foxr     5643: 
1.202     albertel 5644: sub scantron_uploads {
1.209     ng       5645:     my ($file2grade) = @_;
1.202     albertel 5646:     my $result=	'<select name="scantron_selectfile">';
                   5647:     $result.="<option></option>";
                   5648:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5649: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5650:     }
                   5651:     $result.="</select>";
                   5652:     return $result;
                   5653: }
                   5654: 
1.423     albertel 5655: =pod 
                   5656: 
                   5657: =item scantron_scantab
                   5658: 
                   5659:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5660:   file.
                   5661: 
                   5662: =cut
1.422     foxr     5663: 
1.82      albertel 5664: sub scantron_scantab {
                   5665:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5666:     $result.='<option></option>'."\n";
1.518     raeburn  5667:     my @lines = &get_scantronformat_file();
                   5668:     if (@lines > 0) {
                   5669:         foreach my $line (@lines) {
                   5670:             next if (($line =~ /^\#/) || ($line eq ''));
                   5671: 	    my ($name,$descrip)=split(/:/,$line);
                   5672: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5673:         }
1.82      albertel 5674:     }
                   5675:     $result.='</select>'."\n";
1.518     raeburn  5676:     return $result;
                   5677: }
                   5678: 
                   5679: =pod
                   5680: 
                   5681: =item get_scantronformat_file
                   5682: 
                   5683:   Returns an array containing lines from the scantron format file for
                   5684:   the domain of the course.
                   5685: 
                   5686:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5687:   lines are from this file.
                   5688: 
                   5689:   Otherwise, if a default.tab has been published in RES space by the 
                   5690:   domainconfig user, lines are from this file.
                   5691: 
                   5692:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5693:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5694: 
1.518     raeburn  5695: =cut
                   5696: 
                   5697: sub get_scantronformat_file {
                   5698:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5699:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5700:     my $gottab = 0;
                   5701:     my @lines;
                   5702:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5703:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5704:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5705:             if ($formatfile ne '-1') {
                   5706:                 @lines = split("\n",$formatfile,-1);
                   5707:                 $gottab = 1;
                   5708:             }
                   5709:         }
                   5710:     }
                   5711:     if (!$gottab) {
                   5712:         my $confname = $cdom.'-domainconfig';
                   5713:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5714:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5715:         if ($formatfile ne '-1') {
                   5716:             @lines = split("\n",$formatfile,-1);
                   5717:             $gottab = 1;
                   5718:         }
                   5719:     }
                   5720:     if (!$gottab) {
1.519     raeburn  5721:         my @domains = &Apache::lonnet::current_machine_domains();
                   5722:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5723:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5724:             @lines = <$fh>;
                   5725:             close($fh);
                   5726:         } else {
                   5727:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5728:             @lines = <$fh>;
                   5729:             close($fh);
                   5730:         }
1.518     raeburn  5731:     }
                   5732:     return @lines;
1.82      albertel 5733: }
                   5734: 
1.423     albertel 5735: =pod 
                   5736: 
                   5737: =item scantron_CODElist
                   5738: 
                   5739:   Returns html drop down of the saved CODE lists from current course,
                   5740:   generated from earlier printings.
                   5741: 
                   5742: =cut
1.422     foxr     5743: 
1.186     albertel 5744: sub scantron_CODElist {
1.257     albertel 5745:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5746:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5747:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5748:     my $namechoice='<option></option>';
1.225     albertel 5749:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5750: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5751: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5752: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5753:     }
                   5754:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5755:     return $namechoice;
                   5756: }
                   5757: 
1.423     albertel 5758: =pod 
                   5759: 
                   5760: =item scantron_CODEunique
                   5761: 
                   5762:   Returns the html for "Each CODE to be used once" radio.
                   5763: 
                   5764: =cut
1.422     foxr     5765: 
1.186     albertel 5766: sub scantron_CODEunique {
1.532     bisitz   5767:     my $result='<span class="LC_nobreak">
1.272     albertel 5768:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5769:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5770:                 </span>
1.532     bisitz   5771:                 <span class="LC_nobreak">
1.272     albertel 5772:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5773:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5774:                 </span>';
1.186     albertel 5775:     return $result;
                   5776: }
1.423     albertel 5777: 
                   5778: =pod 
                   5779: 
                   5780: =item scantron_selectphase
                   5781: 
1.659     raeburn  5782:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5783:   Allows for - starting a grading run.
1.424     albertel 5784:              - downloading existing scan data (original, corrected
1.423     albertel 5785:                                                 or skipped info)
                   5786: 
                   5787:              - uploading new scan data
                   5788: 
                   5789:  Arguments:
                   5790:   $r          - The Apache request object
                   5791:   $file2grade - name of the file that contain the scanned data to score
                   5792: 
                   5793: =cut
1.186     albertel 5794: 
1.75      albertel 5795: sub scantron_selectphase {
1.608     www      5796:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5797:     if (!$symb) {return '';}
1.582     raeburn  5798:     my $map_error;
                   5799:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5800:     if ($map_error) {
                   5801:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5802:         return;
                   5803:     }
1.324     albertel 5804:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5805:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5806:     my $format_selector=&scantron_scantab();
1.186     albertel 5807:     my $CODE_selector=&scantron_CODElist();
                   5808:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5809:     my $result;
1.422     foxr     5810: 
1.513     foxr     5811:     $ssi_error = 0;
                   5812: 
1.606     wenzelju 5813:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5814:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5815: 
                   5816: 	# Chunk of form to prompt for a scantron file upload.
                   5817: 
                   5818:         $r->print('
                   5819:     <br />
                   5820:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5821:        '.&Apache::loncommon::start_data_table_header_row().'
                   5822:             <th>
                   5823:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5824:             </th>
                   5825:        '.&Apache::loncommon::end_data_table_header_row().'
                   5826:        '.&Apache::loncommon::start_data_table_row().'
                   5827:             <td>
                   5828: ');
1.608     www      5829:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5830:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5831:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5832:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5833:     &js_escape(\$alertmsg);
1.606     wenzelju 5834:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5835:     function checkUpload(formname) {
                   5836: 	if (formname.upfile.value == "") {
1.736     damieng  5837: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5838: 	    return false;
                   5839: 	}
                   5840: 	formname.submit();
                   5841:     }'));
                   5842:     $r->print('
                   5843:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5844:                 '.$default_form_data.'
                   5845:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5846:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5847:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5848:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5849:                 <br />
                   5850:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5851:               </form>
                   5852: ');
                   5853: 
                   5854:         $r->print('
                   5855:             </td>
                   5856:        '.&Apache::loncommon::end_data_table_row().'
                   5857:        '.&Apache::loncommon::end_data_table().'
                   5858: ');
                   5859:     }
                   5860: 
1.422     foxr     5861:     # Chunk of form to prompt for a file to grade and how:
                   5862: 
1.489     albertel 5863:     $result.= '
                   5864:     <br />
                   5865:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5866:     <input type="hidden" name="command" value="scantron_warning" />
                   5867:     '.$default_form_data.'
                   5868:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5869:        '.&Apache::loncommon::start_data_table_header_row().'
                   5870:             <th colspan="2">
1.492     albertel 5871:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5872:             </th>
                   5873:        '.&Apache::loncommon::end_data_table_header_row().'
                   5874:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5875:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5876:        '.&Apache::loncommon::end_data_table_row().'
                   5877:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5878:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5879:        '.&Apache::loncommon::end_data_table_row().'
                   5880:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5881:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5882:        '.&Apache::loncommon::end_data_table_row().'
                   5883:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5884:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5885:        '.&Apache::loncommon::end_data_table_row().'
                   5886:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5887:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5888:        '.&Apache::loncommon::end_data_table_row().'
                   5889:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5890: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5891:             <td>
1.492     albertel 5892: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5893:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5894:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5895: 	    </td>
1.489     albertel 5896:        '.&Apache::loncommon::end_data_table_row().'
                   5897:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5898:             <td colspan="2">
1.572     www      5899:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5900:             </td>
1.489     albertel 5901:        '.&Apache::loncommon::end_data_table_row().'
                   5902:     '.&Apache::loncommon::end_data_table().'
                   5903:     </form>
                   5904: ';
1.162     albertel 5905:    
                   5906:     $r->print($result);
                   5907: 
1.422     foxr     5908: 
                   5909: 
                   5910:     # Chunk of the form that prompts to view a scoring office file,
                   5911:     # corrected file, skipped records in a file.
                   5912: 
1.489     albertel 5913:     $r->print('
                   5914:    <br />
                   5915:    <form action="/adm/grades" name="scantron_download">
                   5916:      '.$default_form_data.'
                   5917:      <input type="hidden" name="command" value="scantron_download" />
                   5918:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5919:        '.&Apache::loncommon::start_data_table_header_row().'
                   5920:               <th>
1.492     albertel 5921:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5922:               </th>
                   5923:        '.&Apache::loncommon::end_data_table_header_row().'
                   5924:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5925:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5926:                 <br />
1.492     albertel 5927:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5928:        '.&Apache::loncommon::end_data_table_row().'
                   5929:      '.&Apache::loncommon::end_data_table().'
                   5930:    </form>
                   5931:    <br />
                   5932: ');
1.162     albertel 5933: 
1.457     banghart 5934:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5935: 
1.694     bisitz   5936:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5937:              $default_form_data."\n".
                   5938:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5939:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5940:              '<th colspan="2">
1.572     www      5941:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5942:              '</th>'."\n".
                   5943:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5944:               &Apache::loncommon::start_data_table_row()."\n".
                   5945:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5946:               '<td> '.$sequence_selector.' </td>'.
                   5947:               &Apache::loncommon::end_data_table_row()."\n".
                   5948:               &Apache::loncommon::start_data_table_row()."\n".
                   5949:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5950:               '<td> '.$file_selector.' </td>'."\n".
                   5951:               &Apache::loncommon::end_data_table_row()."\n".
                   5952:               &Apache::loncommon::start_data_table_row()."\n".
                   5953:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5954:               '<td> '.$format_selector.' </td>'."\n".
                   5955:               &Apache::loncommon::end_data_table_row()."\n".
                   5956:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5957:               '<td> '.&mt('Options').' </td>'."\n".
                   5958:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5959:               &Apache::loncommon::end_data_table_row()."\n".
                   5960:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5961:               '<td colspan="2">'."\n".
                   5962:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5963:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5964:               '</td>'."\n".
                   5965:               &Apache::loncommon::end_data_table_row()."\n".
                   5966:               &Apache::loncommon::end_data_table()."\n".
                   5967:               '</form><br />');
                   5968:     return;
1.75      albertel 5969: }
                   5970: 
1.423     albertel 5971: =pod
                   5972: 
                   5973: =item get_scantron_config
                   5974: 
1.711     bisitz   5975:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5976:    hash of configuration file fields.
                   5977: 
                   5978:  Arguments:
                   5979:     which - the name of the configuration to parse from the file.
                   5980: 
                   5981: 
                   5982:  Returns:
                   5983:             If the named configuration is not in the file, an empty
                   5984:             hash is returned.
                   5985:     a hash with the fields
                   5986:       name         - internal name for the this configuration setup
                   5987:       description  - text to display to operator that describes this config
                   5988:       CODElocation - if 0 or the string 'none'
                   5989:                           - no CODE exists for this config
                   5990:                      if -1 || the string 'letter'
                   5991:                           - a CODE exists for this config and is
                   5992:                             a string of letters
                   5993:                      Unsupported value (but planned for future support)
                   5994:                           if a positive integer
                   5995:                                - The CODE exists as the first n items from
                   5996:                                  the question section of the form
                   5997:                           if the string 'number'
                   5998:                                - The CODE exists for this config and is
                   5999:                                  a string of numbers
                   6000:       CODEstart   - (only matter if a CODE exists) column in the line where
                   6001:                      the CODE starts
                   6002:       CODElength  - length of the CODE
1.573     bisitz   6003:       IDstart     - column where the student/employee ID starts
1.556     weissno  6004:       IDlength    - length of the student/employee ID info
1.423     albertel 6005:       Qstart      - column where the information from the bubbled
                   6006:                     'questions' start
                   6007:       Qlength     - number of columns comprising a single bubble line from
                   6008:                     the sheet. (usually either 1 or 10)
1.424     albertel 6009:       Qon         - either a single character representing the character used
1.423     albertel 6010:                     to signal a bubble was chosen in the positional setup, or
                   6011:                     the string 'letter' if the letter of the chosen bubble is
                   6012:                     in the final, or 'number' if a number representing the
                   6013:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 6014:       Qoff        - the character used to represent that a bubble was
                   6015:                     left blank
1.423     albertel 6016:       PaperID     - if the scanning process generates a unique number for each
                   6017:                     sheet scanned the column that this ID number starts in
                   6018:       PaperIDlength - number of columns that comprise the unique ID number
                   6019:                       for the sheet of paper
1.424     albertel 6020:       FirstName   - column that the first name starts in
1.423     albertel 6021:       FirstNameLength - number of columns that the first name spans
                   6022:  
                   6023:       LastName    - column that the last name starts in
                   6024:       LastNameLength - number of columns that the last name spans
1.649     raeburn  6025:       BubblesPerRow - number of bubbles available in each row used to 
                   6026:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  6027: 
1.423     albertel 6028: =cut
1.422     foxr     6029: 
1.82      albertel 6030: sub get_scantron_config {
                   6031:     my ($which) = @_;
1.518     raeburn  6032:     my @lines = &get_scantronformat_file();
1.82      albertel 6033:     my %config;
1.157     albertel 6034:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  6035:     foreach my $line (@lines) {
1.82      albertel 6036: 	my ($name,$descrip)=split(/:/,$line);
                   6037: 	if ($name ne $which ) { next; }
                   6038: 	chomp($line);
                   6039: 	my @config=split(/:/,$line);
                   6040: 	$config{'name'}=$config[0];
                   6041: 	$config{'description'}=$config[1];
                   6042: 	$config{'CODElocation'}=$config[2];
                   6043: 	$config{'CODEstart'}=$config[3];
                   6044: 	$config{'CODElength'}=$config[4];
                   6045: 	$config{'IDstart'}=$config[5];
                   6046: 	$config{'IDlength'}=$config[6];
                   6047: 	$config{'Qstart'}=$config[7];
1.497     foxr     6048:  	$config{'Qlength'}=$config[8];
1.82      albertel 6049: 	$config{'Qoff'}=$config[9];
                   6050: 	$config{'Qon'}=$config[10];
1.157     albertel 6051: 	$config{'PaperID'}=$config[11];
                   6052: 	$config{'PaperIDlength'}=$config[12];
                   6053: 	$config{'FirstName'}=$config[13];
                   6054: 	$config{'FirstNamelength'}=$config[14];
                   6055: 	$config{'LastName'}=$config[15];
                   6056: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  6057:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 6058: 	last;
                   6059:     }
                   6060:     return %config;
                   6061: }
                   6062: 
1.423     albertel 6063: =pod 
                   6064: 
                   6065: =item username_to_idmap
                   6066: 
1.556     weissno  6067:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6068:     student username:domain. If a single ID occurs for more than one student,
                   6069:     the status of the student is checked, and if Active, the value in the hash
                   6070:     will be set to the Active student.
1.423     albertel 6071: 
                   6072:   Arguments:
                   6073: 
                   6074:     $classlist - reference to the class list hash. This is a hash
                   6075:                  keyed by student name:domain  whose elements are references
1.424     albertel 6076:                  to arrays containing various chunks of information
1.423     albertel 6077:                  about the student. (See loncoursedata for more info).
                   6078: 
                   6079:   Returns
                   6080:     %idmap - the constructed hash
                   6081: 
                   6082: =cut
                   6083: 
1.82      albertel 6084: sub username_to_idmap {
                   6085:     my ($classlist)= @_;
                   6086:     my %idmap;
                   6087:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6088:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6089:         unless ($id eq '') {
                   6090:             if (!exists($idmap{$id})) {
                   6091:                 $idmap{$id} = $student;
                   6092:             } else {
                   6093:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6094:                 if ($status eq 'Active') {
                   6095:                     $idmap{$id} = $student;
                   6096:                 }
                   6097:             }
                   6098:         }
1.82      albertel 6099:     }
                   6100:     return %idmap;
                   6101: }
1.423     albertel 6102: 
                   6103: =pod
                   6104: 
1.424     albertel 6105: =item scantron_fixup_scanline
1.423     albertel 6106: 
                   6107:    Process a requested correction to a scanline.
                   6108: 
                   6109:   Arguments:
                   6110:     $scantron_config   - hash from &get_scantron_config()
                   6111:     $scan_data         - hash of correction information 
                   6112:                           (see &scantron_getfile())
                   6113:     $line              - existing scanline
                   6114:     $whichline         - line number of the passed in scanline
                   6115:     $field             - type of change to process 
                   6116:                          (either 
1.573     bisitz   6117:                           'ID'     -> correct the student/employee ID
1.423     albertel 6118:                           'CODE'   -> correct the CODE
                   6119:                           'answer' -> fixup the submitted answers)
                   6120:     
                   6121:    $args               - hash of additional info,
                   6122:                           - 'ID' 
                   6123:                                'newid' -> studentID to use in replacement
1.424     albertel 6124:                                           of existing one
1.423     albertel 6125:                           - 'CODE' 
                   6126:                                'CODE_ignore_dup' - set to true if duplicates
                   6127:                                                    should be ignored.
                   6128: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6129:                                         if the existing unfound code should
1.423     albertel 6130:                                         be used as is
                   6131:                           - 'answer'
                   6132:                                'response' - new answer or 'none' if blank
                   6133:                                'question' - the bubble line to change
1.503     raeburn  6134:                                'questionnum' - the question identifier,
                   6135:                                                may include subquestion. 
1.423     albertel 6136: 
                   6137:   Returns:
                   6138:     $line - the modified scanline
                   6139: 
                   6140:   Side effects: 
                   6141:     $scan_data - may be updated
                   6142: 
                   6143: =cut
                   6144: 
1.82      albertel 6145: 
1.157     albertel 6146: sub scantron_fixup_scanline {
                   6147:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6148:     if ($field eq 'ID') {
                   6149: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6150: 	    return ($line,1,'New value too large');
1.157     albertel 6151: 	}
                   6152: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6153: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6154: 				     $args->{'newid'});
                   6155: 	}
                   6156: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6157: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6158: 	if ($args->{'newid'}=~/^\s*$/) {
                   6159: 	    &scan_data($scan_data,"$whichline.user",
                   6160: 		       $args->{'username'}.':'.$args->{'domain'});
                   6161: 	}
1.186     albertel 6162:     } elsif ($field eq 'CODE') {
1.192     albertel 6163: 	if ($args->{'CODE_ignore_dup'}) {
                   6164: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6165: 	}
                   6166: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6167: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6168: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6169: 		return ($line,1,'New CODE value too large');
                   6170: 	    }
                   6171: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6172: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6173: 	    }
                   6174: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6175: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6176: 	}
1.157     albertel 6177:     } elsif ($field eq 'answer') {
1.497     foxr     6178: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6179: 	my $off=$scantron_config->{'Qoff'};
                   6180: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6181: 	my $answer=${off}x$length;
                   6182: 	if ($args->{'response'} eq 'none') {
                   6183: 	    &scan_data($scan_data,
1.503     raeburn  6184: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6185: 	} else {
                   6186: 	    if ($on eq 'letter') {
                   6187: 		my @alphabet=('A'..'Z');
                   6188: 		$answer=$alphabet[$args->{'response'}];
                   6189: 	    } elsif ($on eq 'number') {
                   6190: 		$answer=$args->{'response'}+1;
                   6191: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6192: 	    } else {
1.497     foxr     6193: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6194: 	    }
1.497     foxr     6195: 	    &scan_data($scan_data,
1.503     raeburn  6196: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6197: 	}
1.497     foxr     6198: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6199: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6200:     }
                   6201:     return $line;
                   6202: }
1.423     albertel 6203: 
                   6204: =pod
                   6205: 
                   6206: =item scan_data
                   6207: 
                   6208:     Edit or look up  an item in the scan_data hash.
                   6209: 
                   6210:   Arguments:
                   6211:     $scan_data  - The hash (see scantron_getfile)
                   6212:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6213:                   scantronfilename_key).
1.423     albertel 6214:     $data        - New value of the hash entry.
                   6215:     $delete      - If true, the entry is removed from the hash.
                   6216: 
                   6217:   Returns:
                   6218:     The new value of the hash table field (undefined if deleted).
                   6219: 
                   6220: =cut
                   6221: 
                   6222: 
1.157     albertel 6223: sub scan_data {
                   6224:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6225:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6226:     if (defined($value)) {
                   6227: 	$scan_data->{$filename.'_'.$key} = $value;
                   6228:     }
                   6229:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6230:     return $scan_data->{$filename.'_'.$key};
                   6231: }
1.423     albertel 6232: 
1.495     albertel 6233: # ----- These first few routines are general use routines.----
                   6234: 
                   6235: # Return the number of occurences of a pattern in a string.
                   6236: 
                   6237: sub occurence_count {
                   6238:     my ($string, $pattern) = @_;
                   6239: 
                   6240:     my @matches = ($string =~ /$pattern/g);
                   6241: 
                   6242:     return scalar(@matches);
                   6243: }
                   6244: 
                   6245: 
                   6246: # Take a string known to have digits and convert all the
                   6247: # digits into letters in the range J,A..I.
                   6248: 
                   6249: sub digits_to_letters {
                   6250:     my ($input) = @_;
                   6251: 
                   6252:     my @alphabet = ('J', 'A'..'I');
                   6253: 
                   6254:     my @input    = split(//, $input);
                   6255:     my $output ='';
                   6256:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6257: 	if ($input[$i] =~ /\d/) {
                   6258: 	    $output .= $alphabet[$input[$i]];
                   6259: 	} else {
                   6260: 	    $output .= $input[$i];
                   6261: 	}
                   6262:     }
                   6263:     return $output;
                   6264: }
                   6265: 
1.423     albertel 6266: =pod 
                   6267: 
                   6268: =item scantron_parse_scanline
                   6269: 
1.711     bisitz   6270:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6271: 
                   6272:  Arguments:
1.711     bisitz   6273:     line             - The text of the bubblesheet file line to process
1.423     albertel 6274:     whichline        - Line number
1.711     bisitz   6275:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6276:     scan_data        - Hash of extra information about the scanline
                   6277:                        (see scantron_getfile for more information)
                   6278:     just_header      - True if should not process question answers but only
                   6279:                        the stuff to the left of the answers.
1.691     raeburn  6280:     randomorder      - True if randomorder in use
                   6281:     randompick       - True if randompick in use
                   6282:     sequence         - Exam folder URL
                   6283:     master_seq       - Ref to array containing symbs in exam folder
                   6284:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6285:                        (corresponding values are resource objects)
                   6286:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6287:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6288:                        are refs to an array of resource objects, ordered
                   6289:                        according to order used for CODE, when randomorder
                   6290:                        and or randompick are in use.
                   6291:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6292:                        for current line to question number used for same question
                   6293:                         in "Master Sequence" (as seen by Course Coordinator).
                   6294:     startline        - Ref to hash where key is question number (0 is first)
                   6295:                        and value is number of first bubble line for current 
                   6296:                        student or code-based randompick and/or randomorder.
                   6297:     totalref         - Ref of scalar used to score total number of bubble
                   6298:                        lines needed for responses in a scan line (used when
                   6299:                        randompick in use. 
                   6300:     
1.423     albertel 6301:  Returns:
                   6302:    Hash containing the result of parsing the scanline
                   6303: 
                   6304:    Keys are all proceeded by the string 'scantron.'
                   6305: 
                   6306:        CODE    - the CODE in use for this scanline
                   6307:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6308:                  by the operator
                   6309:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6310:                             CODEs were selected, but the usage has been
                   6311:                             forced by the operator
1.556     weissno  6312:        ID  - student/employee ID
1.423     albertel 6313:        PaperID - if used, the ID number printed on the sheet when the 
                   6314:                  paper was scanned
                   6315:        FirstName - first name from the sheet
                   6316:        LastName  - last name from the sheet
                   6317: 
                   6318:      if just_header was not true these key may also exist
                   6319: 
1.447     foxr     6320:        missingerror - a list of bubble ranges that are considered to be answers
                   6321:                       to a single question that don't have any bubbles filled in.
                   6322:                       Of the form questionnumber:firstbubblenumber:count.
                   6323:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6324:                       to a single question that have more than one bubble filled in.
                   6325:                       Of the form questionnumber::firstbubblenumber:count
                   6326:    
                   6327:                 In the above, count is the number of bubble responses in the
                   6328:                 input line needed to represent the possible answers to the question.
                   6329:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6330:                 per line would have count = 2.
                   6331: 
1.423     albertel 6332:        maxquest     - the number of the last bubble line that was parsed
                   6333: 
                   6334:        (<number> starts at 1)
                   6335:        <number>.answer - zero or more letters representing the selected
                   6336:                          letters from the scanline for the bubble line 
                   6337:                          <number>.
                   6338:                          if blank there was either no bubble or there where
                   6339:                          multiple bubbles, (consult the keys missingerror and
                   6340:                          doubleerror if this is an error condition)
                   6341: 
                   6342: =cut
                   6343: 
1.82      albertel 6344: sub scantron_parse_scanline {
1.691     raeburn  6345:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6346:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6347:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6348: 
1.82      albertel 6349:     my %record;
1.691     raeburn  6350:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6351:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6352: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6353: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6354: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6355: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6356: 	    $record{'scantron.CODE'}=substr($data,
                   6357: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6358: 					    $$scantron_config{'CODElength'});
1.191     albertel 6359: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6360: 		$record{'scantron.useCODE'}=1;
                   6361: 	    }
1.192     albertel 6362: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6363: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6364: 	    }
1.82      albertel 6365: 	} else {
                   6366: 	    #FIXME interpret first N questions
                   6367: 	}
                   6368:     }
1.83      albertel 6369:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6370: 				  $$scantron_config{'IDlength'});
1.157     albertel 6371:     $record{'scantron.PaperID'}=
                   6372: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6373: 	       $$scantron_config{'PaperIDlength'});
                   6374:     $record{'scantron.FirstName'}=
                   6375: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6376: 	       $$scantron_config{'FirstNamelength'});
                   6377:     $record{'scantron.LastName'}=
                   6378: 	substr($data,$$scantron_config{'LastName'}-1,
                   6379: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6380:     if ($just_header) { return \%record; }
1.194     albertel 6381: 
1.82      albertel 6382:     my @alphabet=('A'..'Z');
                   6383:     my $questnum=0;
1.447     foxr     6384:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6385: 
1.691     raeburn  6386:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6387:     if ($randompick || $randomorder) {
                   6388:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6389:                                          $master_seq,$symb_to_resource,
                   6390:                                          $partids_by_symb,$orderedforcode,
                   6391:                                          $respnumlookup,$startline);
                   6392:         if ($total) {
                   6393:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6394:         }
                   6395:         if (ref($totalref)) {
                   6396:             $$totalref = $total;
                   6397:         }
                   6398:     }
                   6399:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6400:     chomp($questions);		# Get rid of any trailing \n.
                   6401:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6402:     while (length($questions)) {
1.691     raeburn  6403:         my $answers_needed;
                   6404:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6405:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6406:         } else {
                   6407: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6408:         }
1.503     raeburn  6409:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6410:                              || 1;
                   6411:         $questnum++;
                   6412:         my $quest_id = $questnum;
                   6413:         my $currentquest = substr($questions,0,$answer_length);
                   6414:         $questions       = substr($questions,$answer_length);
                   6415:         if (length($currentquest) < $answer_length) { next; }
                   6416: 
1.691     raeburn  6417:         my $subdivided;
                   6418:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6419:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6420:         } else {
                   6421:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6422:         }
                   6423:         if ($subdivided =~ /,/) {
1.503     raeburn  6424:             my $subquestnum = 1;
                   6425:             my $subquestions = $currentquest;
1.691     raeburn  6426:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6427:             foreach my $subans (@subanswers_needed) {
                   6428:                 my $subans_length =
                   6429:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6430:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6431:                 $subquestions   = substr($subquestions,$subans_length);
                   6432:                 $quest_id = "$questnum.$subquestnum";
                   6433:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6434:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6435:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6436:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6437:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6438:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6439:                 } else {
                   6440:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6441:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6442:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6443:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6444:                 }
                   6445:                 $subquestnum ++;
                   6446:             }
                   6447:         } else {
                   6448:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6449:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6450:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6451:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6452:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6453:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6454:             } else {
                   6455:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6456:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6457:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6458:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6459:             }
                   6460:         }
                   6461:     }
                   6462:     $record{'scantron.maxquest'}=$questnum;
                   6463:     return \%record;
                   6464: }
1.447     foxr     6465: 
1.691     raeburn  6466: sub get_master_seq {
                   6467:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6468:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6469:                    (ref($symb_to_resource) eq 'HASH'));
                   6470:     my $resource_error;
                   6471:     foreach my $resource (@{$resources}) {
                   6472:         my $ressymb;
                   6473:         if (ref($resource)) {
                   6474:             $ressymb = $resource->symb();
                   6475:             push(@{$master_seq},$ressymb);
                   6476:             $symb_to_resource->{$ressymb} = $resource;
                   6477:         } else {
                   6478:             $resource_error = 1;
                   6479:             last;
                   6480:         }
                   6481:     }
                   6482:     return $resource_error;
                   6483: }
                   6484: 
                   6485: sub get_respnum_lookups {
                   6486:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6487:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6488:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6489:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6490:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6491:                    (ref($startline) eq 'HASH'));
                   6492:     my ($user,$scancode);
                   6493:     if ((exists($record->{'scantron.CODE'})) &&
                   6494:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6495:         $scancode = $record->{'scantron.CODE'};
                   6496:     } else {
                   6497:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6498:     }
                   6499:     my @mapresources =
                   6500:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6501:                      $orderedforcode);
                   6502:     my $total = 0;
                   6503:     my $count = 0;
                   6504:     foreach my $resource (@mapresources) {
                   6505:         my $id = $resource->id();
                   6506:         my $symb = $resource->symb();
                   6507:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6508:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6509:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6510:                 if ($respnum ne '') {
                   6511:                     $respnumlookup->{$count} = $respnum;
                   6512:                     $startline->{$count} = $total;
                   6513:                     $total += $bubble_lines_per_response{$respnum};
                   6514:                     $count ++;
                   6515:                 }
                   6516:             }
                   6517:         }
                   6518:     }
                   6519:     return $total;
                   6520: }
                   6521: 
1.503     raeburn  6522: sub scantron_validator_lettnum {
                   6523:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6524:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6525:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6526: 
                   6527:     # Qon 'letter' implies for each slot in currquest we have:
                   6528:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6529:     #    about anything else (esp. a value of Qoff) for missing
                   6530:     #    bubbles.
                   6531:     #
                   6532:     # Qon 'number' implies each slot gives a digit that indexes the
                   6533:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6534:     #    and * or ? for double bubbles on a single line.
                   6535:     #
1.447     foxr     6536: 
1.503     raeburn  6537:     my $matchon;
                   6538:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6539:         $matchon = '[A-Z]';
                   6540:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6541:         $matchon = '\d';
                   6542:     }
                   6543:     my $occurrences = 0;
1.691     raeburn  6544:     my $responsenum = $questnum-1;
                   6545:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6546:        $responsenum = $respnumlookup->{$questnum-1} 
                   6547:     }
                   6548:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6549:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6550:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6551:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6552:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6553:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6554:         my @singlelines = split('',$currquest);
                   6555:         foreach my $entry (@singlelines) {
                   6556:             $occurrences = &occurence_count($entry,$matchon);
                   6557:             if ($occurrences > 1) {
                   6558:                 last;
                   6559:             }
1.691     raeburn  6560:         }
1.503     raeburn  6561:     } else {
                   6562:         $occurrences = &occurence_count($currquest,$matchon); 
                   6563:     }
                   6564:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6565:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6566:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6567:             my $bubble = substr($currquest,$ans,1);
                   6568:             if ($bubble =~ /$matchon/ ) {
                   6569:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6570:                     if ($bubble == 0) {
                   6571:                         $bubble = 10; 
                   6572:                     }
                   6573:                     $record->{"scantron.$ansnum.answer"} = 
                   6574:                         $alphabet->[$bubble-1];
                   6575:                 } else {
                   6576:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6577:                 }
                   6578:             } else {
                   6579:                 $record->{"scantron.$ansnum.answer"}='';
                   6580:             }
                   6581:             $ansnum++;
                   6582:         }
                   6583:     } elsif (!defined($currquest)
                   6584:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6585:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6586:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6587:             $record->{"scantron.$ansnum.answer"}='';
                   6588:             $ansnum++;
                   6589:         }
                   6590:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6591:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6592:         }
                   6593:     } else {
                   6594:         if ($$scantron_config{'Qon'} eq 'number') {
                   6595:             $currquest = &digits_to_letters($currquest);            
                   6596:         }
                   6597:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6598:             my $bubble = substr($currquest,$ans,1);
                   6599:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6600:             $ansnum++;
                   6601:         }
                   6602:     }
                   6603:     return $ansnum;
                   6604: }
1.447     foxr     6605: 
1.503     raeburn  6606: sub scantron_validator_positional {
                   6607:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6608:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6609:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6610: 
1.503     raeburn  6611:     # Otherwise there's a positional notation;
                   6612:     # each bubble line requires Qlength items, and there are filled in
                   6613:     # bubbles for each case where there 'Qon' characters.
                   6614:     #
1.447     foxr     6615: 
1.503     raeburn  6616:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6617: 
1.503     raeburn  6618:     # If the split only gives us one element.. the full length of the
                   6619:     # answer string, no bubbles are filled in:
1.447     foxr     6620: 
1.507     raeburn  6621:     if ($answers_needed eq '') {
                   6622:         return;
                   6623:     }
                   6624: 
1.503     raeburn  6625:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6626:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6627:             $record->{"scantron.$ansnum.answer"}='';
                   6628:             $ansnum++;
                   6629:         }
                   6630:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6631:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6632:         }
                   6633:     } elsif (scalar(@array) == 2) {
                   6634:         my $location = length($array[0]);
                   6635:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6636:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6637:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6638:             if ($ans eq $line_num) {
                   6639:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6640:             } else {
                   6641:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6642:             }
                   6643:             $ansnum++;
                   6644:          }
                   6645:     } else {
                   6646:         #  If there's more than one instance of a bubble character
                   6647:         #  That's a double bubble; with positional notation we can
                   6648:         #  record all the bubbles filled in as well as the
                   6649:         #  fact this response consists of multiple bubbles.
                   6650:         #
1.691     raeburn  6651:         my $responsenum = $questnum-1;
                   6652:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6653:             $responsenum = $respnumlookup->{$questnum-1}
                   6654:         }
                   6655:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6656:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6657:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6658:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6659:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6660:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6661:             my $doubleerror = 0;
                   6662:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6663:                    (!$doubleerror)) {
                   6664:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6665:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6666:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6667:                if (length(@currarray) > 2) {
                   6668:                    $doubleerror = 1;
                   6669:                } 
                   6670:             }
                   6671:             if ($doubleerror) {
                   6672:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6673:             }
                   6674:         } else {
                   6675:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6676:         }
                   6677:         my $item = $ansnum;
                   6678:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6679:             $record->{"scantron.$item.answer"} = '';
                   6680:             $item ++;
                   6681:         }
1.447     foxr     6682: 
1.503     raeburn  6683:         my @ans=@array;
                   6684:         my $i=0;
                   6685:         my $increment = 0;
                   6686:         while ($#ans) {
                   6687:             $i+=length($ans[0]) + $increment;
                   6688:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6689:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6690:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6691:             shift(@ans);
                   6692:             $increment = 1;
                   6693:         }
                   6694:         $ansnum += $answers_needed;
1.82      albertel 6695:     }
1.503     raeburn  6696:     return $ansnum;
1.82      albertel 6697: }
                   6698: 
1.423     albertel 6699: =pod
                   6700: 
                   6701: =item scantron_add_delay
                   6702: 
                   6703:    Adds an error message that occurred during the grading phase to a
                   6704:    queue of messages to be shown after grading pass is complete
                   6705: 
                   6706:  Arguments:
1.424     albertel 6707:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6708:    $scanline    - the scanline that caused the error
                   6709:    $errormesage - the error message
                   6710:    $errorcode   - a numeric code for the error
                   6711: 
                   6712:  Side Effects:
1.424     albertel 6713:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6714: 
                   6715: =cut
                   6716: 
1.82      albertel 6717: sub scantron_add_delay {
1.140     albertel 6718:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6719:     push(@$delayqueue,
                   6720: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6721: 	  'ecode' => $errorcode }
                   6722: 	 );
1.82      albertel 6723: }
                   6724: 
1.423     albertel 6725: =pod
                   6726: 
                   6727: =item scantron_find_student
                   6728: 
1.424     albertel 6729:    Finds the username for the current scanline
                   6730: 
                   6731:   Arguments:
                   6732:    $scantron_record - hash result from scantron_parse_scanline
                   6733:    $scan_data       - hash of correction information 
                   6734:                       (see &scantron_getfile() form more information)
                   6735:    $idmap           - hash from &username_to_idmap()
                   6736:    $line            - number of current scanline
                   6737:  
                   6738:   Returns:
                   6739:    Either 'username:domain' or undef if unknown
                   6740: 
1.423     albertel 6741: =cut
                   6742: 
1.82      albertel 6743: sub scantron_find_student {
1.157     albertel 6744:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6745:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6746:     if ($scanID =~ /^\s*$/) {
                   6747:  	return &scan_data($scan_data,"$line.user");
                   6748:     }
1.83      albertel 6749:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6750:  	if (lc($id) eq lc($scanID)) {
                   6751:  	    return $$idmap{$id};
                   6752:  	}
1.83      albertel 6753:     }
                   6754:     return undef;
                   6755: }
                   6756: 
1.423     albertel 6757: =pod
                   6758: 
                   6759: =item scantron_filter
                   6760: 
1.424     albertel 6761:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6762:    hidden resources was selected
                   6763: 
1.423     albertel 6764: =cut
                   6765: 
1.83      albertel 6766: sub scantron_filter {
                   6767:     my ($curres)=@_;
1.331     albertel 6768: 
                   6769:     if (ref($curres) && $curres->is_problem()) {
                   6770: 	# if the user has asked to not have either hidden
                   6771: 	# or 'randomout' controlled resources to be graded
                   6772: 	# don't include them
                   6773: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6774: 	    && $curres->randomout) {
                   6775: 	    return 0;
                   6776: 	}
1.83      albertel 6777: 	return 1;
                   6778:     }
                   6779:     return 0;
1.82      albertel 6780: }
                   6781: 
1.423     albertel 6782: =pod
                   6783: 
                   6784: =item scantron_process_corrections
                   6785: 
1.424     albertel 6786:    Gets correction information out of submitted form data and corrects
                   6787:    the scanline
                   6788: 
1.423     albertel 6789: =cut
                   6790: 
1.157     albertel 6791: sub scantron_process_corrections {
                   6792:     my ($r) = @_;
1.257     albertel 6793:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6794:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6795:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6796:     my $which=$env{'form.scantron_line'};
1.200     albertel 6797:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6798:     my ($skip,$err,$errmsg);
1.257     albertel 6799:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6800: 	$skip=1;
1.257     albertel 6801:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6802: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6803: 	    $env{'form.scantron_domain'};
1.157     albertel 6804: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6805: 	($line,$err,$errmsg)=
                   6806: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6807: 				     'ID',{'newid'=>$newid,
1.257     albertel 6808: 				    'username'=>$env{'form.scantron_username'},
                   6809: 				    'domain'=>$env{'form.scantron_domain'}});
                   6810:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6811: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6812: 	my $newCODE;
1.192     albertel 6813: 	my %args;
1.190     albertel 6814: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6815: 	    $newCODE='use_unfound';
1.190     albertel 6816: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6817: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6818: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6819: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6820: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6821: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6822: 	}
1.257     albertel 6823: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6824: 	    $args{'CODE_ignore_dup'}=1;
                   6825: 	}
                   6826: 	$args{'CODE'}=$newCODE;
1.186     albertel 6827: 	($line,$err,$errmsg)=
                   6828: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6829: 				     'CODE',\%args);
1.257     albertel 6830:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6831: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6832: 	    ($line,$err,$errmsg)=
                   6833: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6834: 					 $which,'answer',
                   6835: 					 { 'question'=>$question,
1.503     raeburn  6836: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6837:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6838: 	    if ($err) { last; }
                   6839: 	}
                   6840:     }
                   6841:     if ($err) {
1.703     bisitz   6842:         $r->print(
                   6843:             '<p class="LC_error">'
                   6844:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6845:                 $errmsg)
1.704     raeburn  6846:            .'</p>');
1.157     albertel 6847:     } else {
1.200     albertel 6848: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6849: 	&scantron_putfile($scanlines,$scan_data);
                   6850:     }
                   6851: }
                   6852: 
1.423     albertel 6853: =pod
                   6854: 
                   6855: =item reset_skipping_status
                   6856: 
1.424     albertel 6857:    Forgets the current set of remember skipped scanlines (and thus
                   6858:    reverts back to considering all lines in the
                   6859:    scantron_skipped_<filename> file)
                   6860: 
1.423     albertel 6861: =cut
                   6862: 
1.200     albertel 6863: sub reset_skipping_status {
                   6864:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6865:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6866:     &scantron_putfile(undef,$scan_data);
                   6867: }
                   6868: 
1.423     albertel 6869: =pod
                   6870: 
                   6871: =item start_skipping
                   6872: 
1.424     albertel 6873:    Marks a scanline to be skipped. 
                   6874: 
1.423     albertel 6875: =cut
                   6876: 
1.376     albertel 6877: sub start_skipping {
1.200     albertel 6878:     my ($scan_data,$i)=@_;
                   6879:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6880:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6881: 	$remembered{$i}=2;
                   6882:     } else {
                   6883: 	$remembered{$i}=1;
                   6884:     }
1.200     albertel 6885:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6886: }
                   6887: 
1.423     albertel 6888: =pod
                   6889: 
                   6890: =item should_be_skipped
                   6891: 
1.424     albertel 6892:    Checks whether a scanline should be skipped.
                   6893: 
1.423     albertel 6894: =cut
                   6895: 
1.200     albertel 6896: sub should_be_skipped {
1.376     albertel 6897:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6898:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6899: 	# not redoing old skips
1.376     albertel 6900: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6901: 	return 0;
                   6902:     }
                   6903:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6904: 
                   6905:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6906: 	return 0;
                   6907:     }
1.200     albertel 6908:     return 1;
                   6909: }
                   6910: 
1.423     albertel 6911: =pod
                   6912: 
                   6913: =item remember_current_skipped
                   6914: 
1.424     albertel 6915:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6916:    file and remembers them into scan_data for later use.
                   6917: 
1.423     albertel 6918: =cut
                   6919: 
1.200     albertel 6920: sub remember_current_skipped {
                   6921:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6922:     my %to_remember;
                   6923:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6924: 	if ($scanlines->{'skipped'}[$i]) {
                   6925: 	    $to_remember{$i}=1;
                   6926: 	}
                   6927:     }
1.376     albertel 6928: 
1.200     albertel 6929:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6930:     &scantron_putfile(undef,$scan_data);
                   6931: }
                   6932: 
1.423     albertel 6933: =pod
                   6934: 
                   6935: =item check_for_error
                   6936: 
1.424     albertel 6937:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6938:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6939:     something went wrong.
                   6940: 
1.423     albertel 6941: =cut
                   6942: 
1.200     albertel 6943: sub check_for_error {
                   6944:     my ($r,$result)=@_;
                   6945:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6946: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6947:     }
                   6948: }
1.157     albertel 6949: 
1.423     albertel 6950: =pod
                   6951: 
                   6952: =item scantron_warning_screen
                   6953: 
1.424     albertel 6954:    Interstitial screen to make sure the operator has selected the
                   6955:    correct options before we start the validation phase.
                   6956: 
1.423     albertel 6957: =cut
                   6958: 
1.203     albertel 6959: sub scantron_warning_screen {
1.650     raeburn  6960:     my ($button_text,$symb)=@_;
1.257     albertel 6961:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6962:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6963:     my $CODElist;
1.284     albertel 6964:     if ($scantron_config{'CODElocation'} &&
                   6965: 	$scantron_config{'CODEstart'} &&
                   6966: 	$scantron_config{'CODElength'}) {
                   6967: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6968: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6969: 	$CODElist=
1.492     albertel 6970: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6971: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6972:     }
1.663     raeburn  6973:     my $lastbubblepoints;
                   6974:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6975:         $lastbubblepoints =
                   6976:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6977:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6978:     }
1.492     albertel 6979:     return ('
1.203     albertel 6980: <p>
1.492     albertel 6981: <span class="LC_warning">
1.705     raeburn  6982: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6983: </p>
                   6984: <table>
1.492     albertel 6985: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6986: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6987: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6988: </table>
1.680     raeburn  6989: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6990: '.&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 6991: 
                   6992: <br />
1.492     albertel 6993: ');
1.203     albertel 6994: }
                   6995: 
1.423     albertel 6996: =pod
                   6997: 
                   6998: =item scantron_do_warning
                   6999: 
1.424     albertel 7000:    Check if the operator has picked something for all required
                   7001:    fields. Error out if something is missing.
                   7002: 
1.423     albertel 7003: =cut
                   7004: 
1.203     albertel 7005: sub scantron_do_warning {
1.608     www      7006:     my ($r,$symb)=@_;
1.203     albertel 7007:     if (!$symb) {return '';}
1.324     albertel 7008:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7009:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7010:     if ( $env{'form.selectpage'} eq '' ||
                   7011: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7012: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7013: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7014: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7015: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7016: 	} 
1.257     albertel 7017: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7018: 	    $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 7019: 	} 
1.257     albertel 7020: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7021: 	    $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 7022: 	} 
                   7023:     } else {
1.650     raeburn  7024: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  7025:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7026: 	$r->print('
1.663     raeburn  7027: '.$warning.$bubbledbyhand.'
1.492     albertel 7028: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7029: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7030: ');
1.237     albertel 7031:     }
1.614     www      7032:     $r->print("</form><br />");
1.203     albertel 7033:     return '';
                   7034: }
                   7035: 
1.423     albertel 7036: =pod
                   7037: 
                   7038: =item scantron_form_start
                   7039: 
1.424     albertel 7040:     html hidden input for remembering all selected grading options
                   7041: 
1.423     albertel 7042: =cut
                   7043: 
1.203     albertel 7044: sub scantron_form_start {
                   7045:     my ($max_bubble)=@_;
                   7046:     my $result= <<SCANTRONFORM;
                   7047: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7048:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7049:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7050:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7051:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7052:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7053:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7054:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7055:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7056:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7057: SCANTRONFORM
1.447     foxr     7058: 
                   7059:   my $line = 0;
                   7060:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7061:        my $chunk =
                   7062: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7063:        $chunk .=
                   7064: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7065:        $chunk .= 
                   7066:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7067:        $chunk .=
                   7068:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7069:        $chunk .=
                   7070:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7071:        $result .= $chunk;
                   7072:        $line++;
1.691     raeburn  7073:     }
1.203     albertel 7074:     return $result;
                   7075: }
                   7076: 
1.423     albertel 7077: =pod
                   7078: 
                   7079: =item scantron_validate_file
                   7080: 
1.659     raeburn  7081:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7082: 
                   7083:     Also processes any necessary information resets that need to
                   7084:     occur before validation begins (ignore previous corrections,
                   7085:     restarting the skipped records processing)
                   7086: 
1.423     albertel 7087: =cut
                   7088: 
1.157     albertel 7089: sub scantron_validate_file {
1.608     www      7090:     my ($r,$symb) = @_;
1.157     albertel 7091:     if (!$symb) {return '';}
1.324     albertel 7092:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7093:     
1.703     bisitz   7094:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7095:     # them when doing the corrections reset
1.257     albertel 7096:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7097: 	&reset_skipping_status();
                   7098:     }
1.257     albertel 7099:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7100: 	&remember_current_skipped();
1.257     albertel 7101: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7102:     }
                   7103: 
1.257     albertel 7104:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7105: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7106: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7107: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7108: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7109:     }
1.200     albertel 7110: 
1.257     albertel 7111:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7112: 	&scantron_process_corrections($r);
                   7113:     }
1.503     raeburn  7114:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7115:     #get the student pick code ready
                   7116:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7117:     my $nav_error;
1.649     raeburn  7118:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   7119:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7120:     if ($nav_error) {
                   7121:         $r->print(&navmap_errormsg());
                   7122:         return '';
                   7123:     }
1.203     albertel 7124:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7125:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7126:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7127:     }
1.157     albertel 7128:     $r->print($result);
                   7129:     
1.334     albertel 7130:     my @validate_phases=( 'sequence',
                   7131: 			  'ID',
1.157     albertel 7132: 			  'CODE',
                   7133: 			  'doublebubble',
                   7134: 			  'missingbubbles');
1.257     albertel 7135:     if (!$env{'form.validatepass'}) {
                   7136: 	$env{'form.validatepass'} = 0;
1.157     albertel 7137:     }
1.257     albertel 7138:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7139: 
1.448     foxr     7140: 
1.157     albertel 7141:     my $stop=0;
                   7142:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7143: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7144: 	$r->rflush();
1.691     raeburn  7145:      
1.157     albertel 7146: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7147: 	{
                   7148: 	    no strict 'refs';
                   7149: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7150: 	}
                   7151:     }
                   7152:     if (!$stop) {
1.650     raeburn  7153: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7154: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7155:                   $warning.
                   7156:                   &mt('Perform verification for each student after storage of submissions?').
                   7157:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7158:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7159:                   ('&nbsp;'x3).'<label>'.
                   7160:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7161:                   '</label></span><br />'.
                   7162:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7163:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7164:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7165:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7166:     } else {
                   7167: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7168: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7169:     }
                   7170:     if ($stop) {
1.334     albertel 7171: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7172: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7173: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7174: 
1.650     raeburn  7175: 	    $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 7176: 	} else {
1.503     raeburn  7177:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7178: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7179:             } else {
1.539     riegler  7180:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7181:             }
1.492     albertel 7182: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7183: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7184: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7185: 	}
1.157     albertel 7186:     }
1.614     www      7187:     $r->print(" </form><br />");
1.157     albertel 7188:     return '';
                   7189: }
                   7190: 
1.423     albertel 7191: 
                   7192: =pod
                   7193: 
                   7194: =item scantron_remove_file
                   7195: 
1.659     raeburn  7196:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7197:    scantron_original_<filename> is never removed
                   7198: 
                   7199: 
1.423     albertel 7200: =cut
                   7201: 
1.200     albertel 7202: sub scantron_remove_file {
1.192     albertel 7203:     my ($which)=@_;
1.257     albertel 7204:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7205:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7206:     my $file='scantron_';
1.200     albertel 7207:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7208: 	$file.=$which.'_';
1.192     albertel 7209:     } else {
                   7210: 	return 'refused';
                   7211:     }
1.257     albertel 7212:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7213:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7214: }
                   7215: 
1.423     albertel 7216: 
                   7217: =pod
                   7218: 
                   7219: =item scantron_remove_scan_data
                   7220: 
1.659     raeburn  7221:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7222:    data file.  (In the case that both the are doing skipped records we need
                   7223:    to remember the old skipped lines for the time being so that element
                   7224:    persists for a while.)
                   7225: 
1.423     albertel 7226: =cut
                   7227: 
1.200     albertel 7228: sub scantron_remove_scan_data {
1.257     albertel 7229:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7230:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7231:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7232:     my @todelete;
1.257     albertel 7233:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7234:     foreach my $key (@keys) {
                   7235: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7236: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7237: 		$key=~/remember_skipping/) {
                   7238: 		next;
                   7239: 	    }
1.192     albertel 7240: 	    push(@todelete,$key);
                   7241: 	}
                   7242:     }
1.200     albertel 7243:     my $result;
1.192     albertel 7244:     if (@todelete) {
1.491     albertel 7245: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7246: 				       \@todelete,$cdom,$cname);
                   7247:     } else {
                   7248: 	$result = 'ok';
1.192     albertel 7249:     }
                   7250:     return $result;
                   7251: }
                   7252: 
1.423     albertel 7253: 
                   7254: =pod
                   7255: 
                   7256: =item scantron_getfile
                   7257: 
1.659     raeburn  7258:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7259:     the scan_data hash
                   7260:   
                   7261:   Arguments:
                   7262:     None
                   7263: 
                   7264:   Returns:
                   7265:     2 hash references
                   7266: 
                   7267:      - first one has 
                   7268:          orig      -
                   7269:          corrected -
                   7270:          skipped   -  each of which points to an array ref of the specified
                   7271:                       file broken up into individual lines
                   7272:          count     - number of scanlines
                   7273:  
                   7274:      - second is the scan_data hash possible keys are
1.425     albertel 7275:        ($number refers to scanline numbered $number and thus the key affects
                   7276:         only that scanline
                   7277:         $bubline refers to the specific bubble line element and the aspects
                   7278:         refers to that specific bubble line element)
                   7279: 
                   7280:        $number.user - username:domain to use
                   7281:        $number.CODE_ignore_dup 
                   7282:                     - ignore the duplicate CODE error 
                   7283:        $number.useCODE
                   7284:                     - use the CODE in the scanline as is
                   7285:        $number.no_bubble.$bubline
                   7286:                     - it is valid that there is no bubbled in bubble
                   7287:                       at $number $bubline
                   7288:        remember_skipping
                   7289:                     - a frozen hash containing keys of $number and values
                   7290:                       of either 
                   7291:                         1 - we are on a 'do skipped records pass' and plan
                   7292:                             on processing this line
                   7293:                         2 - we are on a 'do skipped records pass' and this
                   7294:                             scanline has been marked to skip yet again
1.424     albertel 7295: 
1.423     albertel 7296: =cut
                   7297: 
1.157     albertel 7298: sub scantron_getfile {
1.200     albertel 7299:     #FIXME really would prefer a scantron directory
1.257     albertel 7300:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7301:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7302:     my $lines;
                   7303:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7304: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7305:     my %scanlines;
                   7306:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7307:     my $temp=$scanlines{'orig'};
                   7308:     $scanlines{'count'}=$#$temp;
                   7309: 
                   7310:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7311: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7312:     if ($lines eq '-1') {
                   7313: 	$scanlines{'corrected'}=[];
                   7314:     } else {
                   7315: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7316:     }
                   7317:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7318: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7319:     if ($lines eq '-1') {
                   7320: 	$scanlines{'skipped'}=[];
                   7321:     } else {
                   7322: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7323:     }
1.175     albertel 7324:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7325:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7326:     my %scan_data = @tmp;
                   7327:     return (\%scanlines,\%scan_data);
                   7328: }
                   7329: 
1.423     albertel 7330: =pod
                   7331: 
                   7332: =item lonnet_putfile
                   7333: 
1.424     albertel 7334:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7335: 
                   7336:  Arguments:
                   7337:    $contents - data to store
                   7338:    $filename - filename to store $contents into
                   7339: 
                   7340:  Returns:
                   7341:    result value from &Apache::lonnet::finishuserfileupload
                   7342: 
1.423     albertel 7343: =cut
                   7344: 
1.157     albertel 7345: sub lonnet_putfile {
                   7346:     my ($contents,$filename)=@_;
1.257     albertel 7347:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7348:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7349:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7350:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7351: 
                   7352: }
                   7353: 
1.423     albertel 7354: =pod
                   7355: 
                   7356: =item scantron_putfile
                   7357: 
1.659     raeburn  7358:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7359:     scan_data hash. (Does not modify the original version only the
                   7360:     corrected and skipped versions.
                   7361: 
                   7362:  Arguments:
                   7363:     $scanlines - hash ref that looks like the first return value from
                   7364:                  &scantron_getfile()
                   7365:     $scan_data - hash ref that looks like the second return value from
                   7366:                  &scantron_getfile()
                   7367: 
1.423     albertel 7368: =cut
                   7369: 
1.157     albertel 7370: sub scantron_putfile {
                   7371:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7372:     #FIXME really would prefer a scantron directory
1.257     albertel 7373:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7375:     if ($scanlines) {
                   7376: 	my $prefix='scantron_';
1.157     albertel 7377: # no need to update orig, shouldn't change
                   7378: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7379: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7380: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7381: 			$prefix.'corrected_'.
1.257     albertel 7382: 			$env{'form.scantron_selectfile'});
1.200     albertel 7383: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7384: 			$prefix.'skipped_'.
1.257     albertel 7385: 			$env{'form.scantron_selectfile'});
1.200     albertel 7386:     }
1.175     albertel 7387:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7388: }
                   7389: 
1.423     albertel 7390: =pod
                   7391: 
                   7392: =item scantron_get_line
                   7393: 
1.424     albertel 7394:    Returns the correct version of the scanline
                   7395: 
                   7396:  Arguments:
                   7397:     $scanlines - hash ref that looks like the first return value from
                   7398:                  &scantron_getfile()
                   7399:     $scan_data - hash ref that looks like the second return value from
                   7400:                  &scantron_getfile()
                   7401:     $i         - number of the requested line (starts at 0)
                   7402: 
                   7403:  Returns:
                   7404:    A scanline, (either the original or the corrected one if it
                   7405:    exists), or undef if the requested scanline should be
                   7406:    skipped. (Either because it's an skipped scanline, or it's an
                   7407:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7408:    pass.
                   7409: 
1.423     albertel 7410: =cut
                   7411: 
1.157     albertel 7412: sub scantron_get_line {
1.200     albertel 7413:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7414:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7415:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7416:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7417:     return $scanlines->{'orig'}[$i]; 
                   7418: }
                   7419: 
1.423     albertel 7420: =pod
                   7421: 
                   7422: =item scantron_todo_count
                   7423: 
1.424     albertel 7424:     Counts the number of scanlines that need processing.
                   7425: 
                   7426:  Arguments:
                   7427:     $scanlines - hash ref that looks like the first return value from
                   7428:                  &scantron_getfile()
                   7429:     $scan_data - hash ref that looks like the second return value from
                   7430:                  &scantron_getfile()
                   7431: 
                   7432:  Returns:
                   7433:     $count - number of scanlines to process
                   7434: 
1.423     albertel 7435: =cut
                   7436: 
1.200     albertel 7437: sub get_todo_count {
                   7438:     my ($scanlines,$scan_data)=@_;
                   7439:     my $count=0;
                   7440:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7441: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7442: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7443: 	$count++;
                   7444:     }
                   7445:     return $count;
                   7446: }
                   7447: 
1.423     albertel 7448: =pod
                   7449: 
                   7450: =item scantron_put_line
                   7451: 
1.659     raeburn  7452:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7453:     data file.
                   7454: 
                   7455:  Arguments:
                   7456:     $scanlines - hash ref that looks like the first return value from
                   7457:                  &scantron_getfile()
                   7458:     $scan_data - hash ref that looks like the second return value from
                   7459:                  &scantron_getfile()
                   7460:     $i         - line number to update
                   7461:     $newline   - contents of the updated scanline
                   7462:     $skip      - if true make the line for skipping and update the
                   7463:                  'skipped' file
                   7464: 
1.423     albertel 7465: =cut
                   7466: 
1.157     albertel 7467: sub scantron_put_line {
1.200     albertel 7468:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7469:     if ($skip) {
                   7470: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7471: 	&start_skipping($scan_data,$i);
1.157     albertel 7472: 	return;
                   7473:     }
                   7474:     $scanlines->{'corrected'}[$i]=$newline;
                   7475: }
                   7476: 
1.423     albertel 7477: =pod
                   7478: 
                   7479: =item scantron_clear_skip
                   7480: 
1.424     albertel 7481:    Remove a line from the 'skipped' file
                   7482: 
                   7483:  Arguments:
                   7484:     $scanlines - hash ref that looks like the first return value from
                   7485:                  &scantron_getfile()
                   7486:     $scan_data - hash ref that looks like the second return value from
                   7487:                  &scantron_getfile()
                   7488:     $i         - line number to update
                   7489: 
1.423     albertel 7490: =cut
                   7491: 
1.376     albertel 7492: sub scantron_clear_skip {
                   7493:     my ($scanlines,$scan_data,$i)=@_;
                   7494:     if (exists($scanlines->{'skipped'}[$i])) {
                   7495: 	undef($scanlines->{'skipped'}[$i]);
                   7496: 	return 1;
                   7497:     }
                   7498:     return 0;
                   7499: }
                   7500: 
1.423     albertel 7501: =pod
                   7502: 
                   7503: =item scantron_filter_not_exam
                   7504: 
1.424     albertel 7505:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7506:    filter out resources that are not marked as 'exam' mode
                   7507: 
1.423     albertel 7508: =cut
                   7509: 
1.334     albertel 7510: sub scantron_filter_not_exam {
                   7511:     my ($curres)=@_;
                   7512:     
                   7513:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7514: 	# if the user has asked to not have either hidden
                   7515: 	# or 'randomout' controlled resources to be graded
                   7516: 	# don't include them
                   7517: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7518: 	    && $curres->randomout) {
                   7519: 	    return 0;
                   7520: 	}
                   7521: 	return 1;
                   7522:     }
                   7523:     return 0;
                   7524: }
                   7525: 
1.423     albertel 7526: =pod
                   7527: 
                   7528: =item scantron_validate_sequence
                   7529: 
1.424     albertel 7530:     Validates the selected sequence, checking for resource that are
                   7531:     not set to exam mode.
                   7532: 
1.423     albertel 7533: =cut
                   7534: 
1.334     albertel 7535: sub scantron_validate_sequence {
                   7536:     my ($r,$currentphase) = @_;
                   7537: 
                   7538:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7539:     unless (ref($navmap)) {
                   7540:         $r->print(&navmap_errormsg());
                   7541:         return (1,$currentphase);
                   7542:     }
1.334     albertel 7543:     my (undef,undef,$sequence)=
                   7544: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7545: 
                   7546:     my $map=$navmap->getResourceByUrl($sequence);
                   7547: 
                   7548:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7549:                                     value="ignore" />');
                   7550:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7551: 	my @resources=
                   7552: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7553: 	if (@resources) {
1.675     bisitz   7554: 	    $r->print(
                   7555:                 '<p class="LC_warning">'
                   7556:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7557:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7558:                    .' work correctly.')
                   7559:                .'</p>'
                   7560:             );
1.334     albertel 7561: 	    return (1,$currentphase);
                   7562: 	}
                   7563:     }
                   7564: 
                   7565:     return (0,$currentphase+1);
                   7566: }
                   7567: 
1.423     albertel 7568: 
                   7569: 
1.157     albertel 7570: sub scantron_validate_ID {
                   7571:     my ($r,$currentphase) = @_;
                   7572:     
                   7573:     #get student info
                   7574:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7575:     my %idmap=&username_to_idmap($classlist);
                   7576: 
                   7577:     #get scantron line setup
1.257     albertel 7578:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7579:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7580: 
                   7581:     my $nav_error;
1.649     raeburn  7582:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7583:     if ($nav_error) {
                   7584:         $r->print(&navmap_errormsg());
                   7585:         return(1,$currentphase);
                   7586:     }
1.157     albertel 7587: 
                   7588:     my %found=('ids'=>{},'usernames'=>{});
                   7589:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7590: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7591: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7592: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7593: 						 $scan_data);
                   7594: 	my $id=$$scan_record{'scantron.ID'};
                   7595: 	my $found;
                   7596: 	foreach my $checkid (keys(%idmap)) {
                   7597: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7598: 	}
                   7599: 	if ($found) {
                   7600: 	    my $username=$idmap{$found};
                   7601: 	    if ($found{'ids'}{$found}) {
                   7602: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7603: 					 $line,'duplicateID',$found);
1.194     albertel 7604: 		return(1,$currentphase);
1.157     albertel 7605: 	    } elsif ($found{'usernames'}{$username}) {
                   7606: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7607: 					 $line,'duplicateID',$username);
1.194     albertel 7608: 		return(1,$currentphase);
1.157     albertel 7609: 	    }
1.186     albertel 7610: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7611: 	    $found{'ids'}{$found}++;
                   7612: 	    $found{'usernames'}{$username}++;
                   7613: 	} else {
                   7614: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7615: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7616: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7617: 		    &scantron_get_correction($r,$i,$scan_record,
                   7618: 					     \%scantron_config,
                   7619: 					     $line,'duplicateID',$username);
1.194     albertel 7620: 		    return(1,$currentphase);
1.157     albertel 7621: 		} elsif (!defined($username)) {
                   7622: 		    &scantron_get_correction($r,$i,$scan_record,
                   7623: 					     \%scantron_config,
                   7624: 					     $line,'incorrectID');
1.194     albertel 7625: 		    return(1,$currentphase);
1.157     albertel 7626: 		}
                   7627: 		$found{'usernames'}{$username}++;
                   7628: 	    } else {
                   7629: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7630: 					 $line,'incorrectID');
1.194     albertel 7631: 		return(1,$currentphase);
1.157     albertel 7632: 	    }
                   7633: 	}
                   7634:     }
                   7635: 
                   7636:     return (0,$currentphase+1);
                   7637: }
                   7638: 
1.423     albertel 7639: 
1.157     albertel 7640: sub scantron_get_correction {
1.691     raeburn  7641:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7642:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7643: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7644: #to show both the current line and the previous one and allow skipping
                   7645: #the previous one or the current one
                   7646: 
1.333     albertel 7647:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7648:         $r->print(
                   7649:             '<p class="LC_warning">'
                   7650:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7651:                 "<b>$error</b>",
                   7652:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7653:            ."</p> \n");
1.157     albertel 7654:     } else {
1.658     bisitz   7655:         $r->print(
                   7656:             '<p class="LC_warning">'
                   7657:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7658:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7659:            ."</p> \n");
                   7660:     }
                   7661:     my $message =
                   7662:         '<p>'
                   7663:        .&mt('The ID on the form is [_1]',
                   7664:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7665:        .'<br />'
1.665     raeburn  7666:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7667:             $$scan_record{'scantron.LastName'},
                   7668:             $$scan_record{'scantron.FirstName'})
                   7669:        .'</p>';
1.242     albertel 7670: 
1.157     albertel 7671:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7672:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7673:                            # Array populated for doublebubble or
                   7674:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7675:                            # to validate radio button checking   
                   7676: 
1.157     albertel 7677:     if ($error =~ /ID$/) {
1.186     albertel 7678: 	if ($error eq 'incorrectID') {
1.658     bisitz   7679:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7680: 		      "</p>\n");
1.157     albertel 7681: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7682:             $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 7683: 	}
1.242     albertel 7684: 	$r->print($message);
1.492     albertel 7685: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7686: 	$r->print("\n<ul><li> ");
                   7687: 	#FIXME it would be nice if this sent back the user ID and
                   7688: 	#could do partial userID matches
                   7689: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7690: 				       'scantron_username','scantron_domain'));
                   7691: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7692: 	$r->print("\n:\n".
1.257     albertel 7693: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7694: 
                   7695: 	$r->print('</li>');
1.186     albertel 7696:     } elsif ($error =~ /CODE$/) {
                   7697: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7698: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7699: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7700: 	    $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 7701: 	}
1.658     bisitz   7702: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7703: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7704:                  ."</p>\n");
1.242     albertel 7705: 	$r->print($message);
1.658     bisitz   7706: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7707: 	$r->print("\n<br /> ");
1.194     albertel 7708: 	my $i=0;
1.273     albertel 7709: 	if ($error eq 'incorrectCODE' 
                   7710: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7711: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7712: 	    if ($closest > 0) {
                   7713: 		foreach my $testcode (@{$closest}) {
                   7714: 		    my $checked='';
1.569     bisitz   7715: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7716: 		    $r->print("
                   7717:    <label>
1.569     bisitz   7718:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7719:        ".&mt("Use the similar CODE [_1] instead.",
                   7720: 	    "<b><tt>".$testcode."</tt></b>")."
                   7721:     </label>
                   7722:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7723: 		    $r->print("\n<br />");
                   7724: 		    $i++;
                   7725: 		}
1.194     albertel 7726: 	    }
                   7727: 	}
1.273     albertel 7728: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7729: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7730: 	    $r->print("
                   7731:     <label>
1.569     bisitz   7732:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7733:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7734: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7735:     </label>");
1.273     albertel 7736: 	    $r->print("\n<br />");
                   7737: 	}
1.194     albertel 7738: 
1.597     wenzelju 7739: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7740: function change_radio(field) {
1.190     albertel 7741:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7742:     var i;
                   7743:     for (i=0;i<slct.length;i++) {
                   7744:         if (slct[i].value==field) { slct[i].checked=true; }
                   7745:     }
                   7746: }
                   7747: ENDSCRIPT
1.187     albertel 7748: 	my $href="/adm/pickcode?".
1.359     www      7749: 	   "form=".&escape("scantronupload").
                   7750: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7751: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7752: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7753: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7754: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7755: 	    $r->print("
                   7756:     <label>
                   7757:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7758:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7759: 	     "<a target='_blank' href='$href'>","</a>")."
                   7760:     </label> 
1.558     bisitz   7761:     ".&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 7762: 	    $r->print("\n<br />");
                   7763: 	}
1.492     albertel 7764: 	$r->print("
                   7765:     <label>
                   7766:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7767:        ".&mt("Use [_1] as the CODE.",
                   7768: 	     "</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 7769: 	$r->print("\n<br /><br />");
1.157     albertel 7770:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7771: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7772: 
                   7773: 	# The form field scantron_questions is acutally a list of line numbers.
                   7774: 	# represented by this form so:
                   7775: 
1.691     raeburn  7776: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7777:                                                 $respnumlookup,$startline);
1.497     foxr     7778: 
1.157     albertel 7779: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7780: 		  $line_list.'" />');
1.242     albertel 7781: 	$r->print($message);
1.492     albertel 7782: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7783: 	foreach my $question (@{$arg}) {
1.503     raeburn  7784: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7785:                                                    $scan_record, $error,
                   7786:                                                    $randomorder,$randompick,
                   7787:                                                    $respnumlookup,$startline);
1.524     raeburn  7788:             push(@lines_to_correct,@linenums);
1.157     albertel 7789: 	}
1.503     raeburn  7790:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7791:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7792: 	$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 7793: 	$r->print($message);
1.492     albertel 7794: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7795: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7796: 
1.503     raeburn  7797: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7798: 	# a list of question numbers. Therefore:
                   7799: 	#
1.691     raeburn  7800: 
                   7801: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7802:                                                 $respnumlookup,$startline);
1.497     foxr     7803: 
1.157     albertel 7804: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7805: 		  $line_list.'" />');
1.157     albertel 7806: 	foreach my $question (@{$arg}) {
1.503     raeburn  7807: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7808:                                                    $scan_record, $error,
                   7809:                                                    $randomorder,$randompick,
                   7810:                                                    $respnumlookup,$startline);
1.524     raeburn  7811:             push(@lines_to_correct,@linenums);
1.157     albertel 7812: 	}
1.503     raeburn  7813:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7814:     } else {
                   7815: 	$r->print("\n<ul>");
                   7816:     }
                   7817:     $r->print("\n</li></ul>");
1.497     foxr     7818: }
                   7819: 
1.503     raeburn  7820: sub verify_bubbles_checked {
                   7821:     my (@ansnums) = @_;
                   7822:     my $ansnumstr = join('","',@ansnums);
                   7823:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7824:     &js_escape(\$warning);
1.597     wenzelju 7825:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7826: function verify_bubble_radio(form) {
                   7827:     var ansnumArray = new Array ("$ansnumstr");
                   7828:     var need_bubble_count = 0;
                   7829:     for (var i=0; i<ansnumArray.length; i++) {
                   7830:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7831:             var bubble_picked = 0; 
                   7832:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7833:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7834:                     bubble_picked = 1;
                   7835:                 }
                   7836:             }
                   7837:             if (bubble_picked == 0) {
                   7838:                 need_bubble_count ++;
                   7839:             }
                   7840:         }
                   7841:     }
                   7842:     if (need_bubble_count) {
                   7843:         alert("$warning");
                   7844:         return;
                   7845:     }
                   7846:     form.submit(); 
                   7847: }
                   7848: ENDSCRIPT
                   7849:     return $output;
                   7850: }
                   7851: 
1.497     foxr     7852: =pod
                   7853: 
                   7854: =item  questions_to_line_list
1.157     albertel 7855: 
1.497     foxr     7856: Converts a list of questions into a string of comma separated
                   7857: line numbers in the answer sheet used by the questions.  This is
                   7858: used to fill in the scantron_questions form field.
                   7859: 
                   7860:   Arguments:
                   7861:      questions    - Reference to an array of questions.
1.691     raeburn  7862:      randomorder  - True if randomorder in use.
                   7863:      randompick   - True if randompick in use.
                   7864:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7865:                      for current line to question number used for same question
                   7866:                      in "Master Seqence" (as seen by Course Coordinator).
                   7867:      startline    - Reference to hash where key is question number (0 is first)
                   7868:                     and key is number of first bubble line for current student
                   7869:                     or code-based randompick and/or randomorder.
1.693     raeburn  7870: 
1.497     foxr     7871: =cut
                   7872: 
                   7873: 
                   7874: sub questions_to_line_list {
1.691     raeburn  7875:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7876:     my @lines;
                   7877: 
1.503     raeburn  7878:     foreach my $item (@{$questions}) {
                   7879:         my $question = $item;
                   7880:         my ($first,$count,$last);
                   7881:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7882:             $question = $1;
                   7883:             my $subquestion = $2;
1.691     raeburn  7884:             my $responsenum = $question-1;
                   7885:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7886:                 $responsenum = $respnumlookup->{$question-1};
                   7887:                 if (ref($startline) eq 'HASH') {
                   7888:                     $first = $startline->{$question-1} + 1;
                   7889:                 }
                   7890:             } else {
                   7891:                 $first = $first_bubble_line{$responsenum} + 1;
                   7892:             }
                   7893:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7894:             my $subcount = 1;
                   7895:             while ($subcount<$subquestion) {
                   7896:                 $first += $subans[$subcount-1];
                   7897:                 $subcount ++;
                   7898:             }
                   7899:             $count = $subans[$subquestion-1];
                   7900:         } else {
1.691     raeburn  7901:             my $responsenum = $question-1;
                   7902:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7903:                 $responsenum = $respnumlookup->{$question-1};
                   7904:                 if (ref($startline) eq 'HASH') {
                   7905:                     $first = $startline->{$question-1} + 1;
                   7906:                 }
                   7907:             } else {
                   7908:                 $first = $first_bubble_line{$responsenum} + 1;
                   7909:             }
                   7910: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7911:         }
1.506     raeburn  7912:         $last = $first+$count-1;
1.503     raeburn  7913:         push(@lines, ($first..$last));
1.497     foxr     7914:     }
                   7915:     return join(',', @lines);
                   7916: }
                   7917: 
                   7918: =pod 
                   7919: 
                   7920: =item prompt_for_corrections
                   7921: 
                   7922: Prompts for a potentially multiline correction to the
                   7923: user's bubbling (factors out common code from scantron_get_correction
                   7924: for multi and missing bubble cases).
                   7925: 
                   7926:  Arguments:
                   7927:    $r           - Apache request object.
                   7928:    $question    - The question number to prompt for.
                   7929:    $scan_config - The scantron file configuration hash.
                   7930:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7931:    $error       - Type of error
1.691     raeburn  7932:    $randomorder - True if randomorder in use.
                   7933:    $randompick  - True if randompick in use.
                   7934:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7935:                     for current line to question number used for same question
                   7936:                     in "Master Seqence" (as seen by Course Coordinator).
                   7937:    $startline   - Reference to hash where key is question number (0 is first)
                   7938:                   and value is number of first bubble line for current student
                   7939:                   or code-based randompick and/or randomorder.
                   7940: 
1.497     foxr     7941: 
                   7942:  Implicit inputs:
                   7943:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7944:                                   Numbered from 0 (but question numbers are from
                   7945:                                   1.
                   7946:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7947:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7948:                                   type problems render as separate sub-questions, 
1.503     raeburn  7949:                                   in exam mode. This hash contains a 
                   7950:                                   comma-separated list of the lines per 
                   7951:                                   sub-question.
1.510     raeburn  7952:    %responsetype_per_response   - essayresponse, formularesponse,
                   7953:                                   stringresponse, imageresponse, reactionresponse,
                   7954:                                   and organicresponse type problem parts can have
1.503     raeburn  7955:                                   multiple lines per response if the weight
                   7956:                                   assigned exceeds 10.  In this case, only
                   7957:                                   one bubble per line is permitted, but more 
                   7958:                                   than one line might contain bubbles, e.g.
                   7959:                                   bubbling of: line 1 - J, line 2 - J, 
                   7960:                                   line 3 - B would assign 22 points.  
1.497     foxr     7961: 
                   7962: =cut
                   7963: 
                   7964: sub prompt_for_corrections {
1.691     raeburn  7965:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7966:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7967:     my ($current_line,$lines);
                   7968:     my @linenums;
                   7969:     my $questionnum = $question;
1.691     raeburn  7970:     my ($first,$responsenum);
1.503     raeburn  7971:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7972:         $question = $1;
                   7973:         my $subquestion = $2;
1.691     raeburn  7974:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7975:             $responsenum = $respnumlookup->{$question-1};
                   7976:             if (ref($startline) eq 'HASH') {
                   7977:                 $first = $startline->{$question-1};
                   7978:             }
                   7979:         } else {
                   7980:             $responsenum = $question-1;
1.714     raeburn  7981:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7982:         }
                   7983:         $current_line = $first + 1 ;
                   7984:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7985:         my $subcount = 1;
                   7986:         while ($subcount<$subquestion) {
                   7987:             $current_line += $subans[$subcount-1];
                   7988:             $subcount ++;
                   7989:         }
                   7990:         $lines = $subans[$subquestion-1];
                   7991:     } else {
1.691     raeburn  7992:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7993:             $responsenum = $respnumlookup->{$question-1};
                   7994:             if (ref($startline) eq 'HASH') { 
                   7995:                 $first = $startline->{$question-1};
                   7996:             }
                   7997:         } else {
                   7998:             $responsenum = $question-1;
                   7999:             $first = $first_bubble_line{$responsenum};
                   8000:         }
                   8001:         $current_line = $first + 1;
                   8002:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8003:     }
1.497     foxr     8004:     if ($lines > 1) {
1.503     raeburn  8005:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8006:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8007:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8008:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8009:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8010:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8011:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8012:             $r->print(
                   8013:                 &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)
                   8014:                .'<br /><br />'
                   8015:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8016:                .'<br />'
                   8017:                .&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.')
                   8018:                .'<br />'
                   8019:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8020:                .'<br /><br />'
                   8021:             );
1.503     raeburn  8022:         } else {
                   8023:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8024:         }
1.497     foxr     8025:     }
                   8026:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8027:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8028: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8029: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8030:         push(@linenums,$current_line);
1.497     foxr     8031: 	$current_line++;
                   8032:     }
                   8033:     if ($lines > 1) {
                   8034: 	$r->print("<hr /><br />");
                   8035:     }
1.503     raeburn  8036:     return @linenums;
1.157     albertel 8037: }
1.423     albertel 8038: 
                   8039: =pod
                   8040: 
                   8041: =item scantron_bubble_selector
                   8042:   
                   8043:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8044:    possibly showing the existing the selected bubbles if known
1.423     albertel 8045: 
                   8046:  Arguments:
                   8047:     $r           - Apache request object
                   8048:     $scan_config - hash from &get_scantron_config()
1.497     foxr     8049:     $line        - Number of the line being displayed.
1.503     raeburn  8050:     $questionnum - Question number (may include subquestion)
                   8051:     $error       - Type of error.
1.497     foxr     8052:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8053: 
                   8054: =cut
                   8055: 
1.157     albertel 8056: sub scantron_bubble_selector {
1.503     raeburn  8057:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8058:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8059: 
                   8060:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8061:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8062:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8063:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8064:             $max=$$scan_config{'BubblesPerRow'};
                   8065:             if (($scmode eq 'number') && ($max > 10)) {
                   8066:                 $max = 10;
                   8067:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8068:                 $max = 26;
                   8069:             }
                   8070:         } else {
                   8071:             $max = 10;
                   8072:         }
                   8073:     }
1.274     albertel 8074: 
1.157     albertel 8075:     my @alphabet=('A'..'Z');
1.503     raeburn  8076:     $r->print(&Apache::loncommon::start_data_table().
                   8077:               &Apache::loncommon::start_data_table_row());
                   8078:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8079:     for (my $i=0;$i<$max+1;$i++) {
                   8080: 	$r->print("\n".'<td align="center">');
                   8081: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8082: 	else { $r->print('&nbsp;'); }
                   8083: 	$r->print('</td>');
                   8084:     }
1.503     raeburn  8085:     $r->print(&Apache::loncommon::end_data_table_row().
                   8086:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8087:     for (my $i=0;$i<$max;$i++) {
                   8088: 	$r->print("\n".
                   8089: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8090: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8091:     }
1.503     raeburn  8092:     my $nobub_checked = ' ';
                   8093:     if ($error eq 'missingbubble') {
                   8094:         $nobub_checked = ' checked = "checked" ';
                   8095:     }
                   8096:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8097: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8098:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8099:               $line.'" value="'.$questionnum.'" /></td>');
                   8100:     $r->print(&Apache::loncommon::end_data_table_row().
                   8101:               &Apache::loncommon::end_data_table());
1.157     albertel 8102: }
                   8103: 
1.423     albertel 8104: =pod
                   8105: 
                   8106: =item num_matches
                   8107: 
1.424     albertel 8108:    Counts the number of characters that are the same between the two arguments.
                   8109: 
                   8110:  Arguments:
                   8111:    $orig - CODE from the scanline
                   8112:    $code - CODE to match against
                   8113: 
                   8114:  Returns:
                   8115:    $count - integer count of the number of same characters between the
                   8116:             two arguments
                   8117: 
1.423     albertel 8118: =cut
                   8119: 
1.194     albertel 8120: sub num_matches {
                   8121:     my ($orig,$code) = @_;
                   8122:     my @code=split(//,$code);
                   8123:     my @orig=split(//,$orig);
                   8124:     my $same=0;
                   8125:     for (my $i=0;$i<scalar(@code);$i++) {
                   8126: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8127:     }
                   8128:     return $same;
                   8129: }
                   8130: 
1.423     albertel 8131: =pod
                   8132: 
                   8133: =item scantron_get_closely_matching_CODEs
                   8134: 
1.424     albertel 8135:    Cycles through all CODEs and finds the set that has the greatest
                   8136:    number of same characters as the provided CODE
                   8137: 
                   8138:  Arguments:
                   8139:    $allcodes - hash ref returned by &get_codes()
                   8140:    $CODE     - CODE from the current scanline
                   8141: 
                   8142:  Returns:
                   8143:    2 element list
                   8144:     - first elements is number of how closely matching the best fit is 
                   8145:       (5 means best set has 5 matching characters)
                   8146:     - second element is an arrary ref containing the set of valid CODEs
                   8147:       that best fit the passed in CODE
                   8148: 
1.423     albertel 8149: =cut
                   8150: 
1.194     albertel 8151: sub scantron_get_closely_matching_CODEs {
                   8152:     my ($allcodes,$CODE)=@_;
                   8153:     my @CODEs;
                   8154:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8155: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8156:     }
                   8157: 
                   8158:     return ($#CODEs,$CODEs[-1]);
                   8159: }
                   8160: 
1.423     albertel 8161: =pod
                   8162: 
                   8163: =item get_codes
                   8164: 
1.424     albertel 8165:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8166:    set of remembered CODEs.
                   8167: 
                   8168:  Arguments:
                   8169:   $old_name - name of the set of remembered CODEs
                   8170:   $cdom     - domain of the course
                   8171:   $cnum     - internal course name
                   8172: 
                   8173:  Returns:
                   8174:   %allcodes - keys are the valid CODEs, values are all 1
                   8175: 
1.423     albertel 8176: =cut
                   8177: 
1.194     albertel 8178: sub get_codes {
1.280     foxr     8179:     my ($old_name, $cdom, $cnum) = @_;
                   8180:     if (!$old_name) {
                   8181: 	$old_name=$env{'form.scantron_CODElist'};
                   8182:     }
                   8183:     if (!$cdom) {
                   8184: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8185:     }
                   8186:     if (!$cnum) {
                   8187: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8188:     }
1.278     albertel 8189:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8190: 				    $cdom,$cnum);
                   8191:     my %allcodes;
                   8192:     if ($result{"type\0$old_name"} eq 'number') {
                   8193: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8194:     } else {
                   8195: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8196:     }
1.194     albertel 8197:     return %allcodes;
                   8198: }
                   8199: 
1.423     albertel 8200: =pod
                   8201: 
                   8202: =item scantron_validate_CODE
                   8203: 
1.424     albertel 8204:    Validates all scanlines in the selected file to not have any
                   8205:    invalid or underspecified CODEs and that none of the codes are
                   8206:    duplicated if this was requested.
                   8207: 
1.423     albertel 8208: =cut
                   8209: 
1.157     albertel 8210: sub scantron_validate_CODE {
                   8211:     my ($r,$currentphase) = @_;
1.257     albertel 8212:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8213:     if ($scantron_config{'CODElocation'} &&
                   8214: 	$scantron_config{'CODEstart'} &&
                   8215: 	$scantron_config{'CODElength'}) {
1.257     albertel 8216: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8217: 	    &FIXME_blow_up()
                   8218: 	}
                   8219:     } else {
                   8220: 	return (0,$currentphase+1);
                   8221:     }
                   8222:     
                   8223:     my %usedCODEs;
                   8224: 
1.194     albertel 8225:     my %allcodes=&get_codes();
1.186     albertel 8226: 
1.582     raeburn  8227:     my $nav_error;
1.649     raeburn  8228:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8229:     if ($nav_error) {
                   8230:         $r->print(&navmap_errormsg());
                   8231:         return(1,$currentphase);
                   8232:     }
1.447     foxr     8233: 
1.186     albertel 8234:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8235:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8236: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8237: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8238: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8239: 						 $scan_data);
                   8240: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8241: 	my $error=0;
1.224     albertel 8242: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8243: 	    &scantron_get_correction($r,$i,$scan_record,
                   8244: 				     \%scantron_config,
                   8245: 				     $line,'incorrectCODE',\%allcodes);
                   8246: 	    return(1,$currentphase);
                   8247: 	}
1.221     albertel 8248: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8249: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8250: 	    &scantron_get_correction($r,$i,$scan_record,
                   8251: 				     \%scantron_config,
1.194     albertel 8252: 				     $line,'incorrectCODE',\%allcodes);
                   8253: 	    return(1,$currentphase);
1.186     albertel 8254: 	}
1.214     albertel 8255: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8256: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8257: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8258: 	    &scantron_get_correction($r,$i,$scan_record,
                   8259: 				     \%scantron_config,
1.194     albertel 8260: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8261: 	    return(1,$currentphase);
1.186     albertel 8262: 	}
1.524     raeburn  8263: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8264:     }
1.157     albertel 8265:     return (0,$currentphase+1);
                   8266: }
                   8267: 
1.423     albertel 8268: =pod
                   8269: 
                   8270: =item scantron_validate_doublebubble
                   8271: 
1.424     albertel 8272:    Validates all scanlines in the selected file to not have any
                   8273:    bubble lines with multiple bubbles marked.
                   8274: 
1.423     albertel 8275: =cut
                   8276: 
1.157     albertel 8277: sub scantron_validate_doublebubble {
                   8278:     my ($r,$currentphase) = @_;
                   8279:     #get student info
                   8280:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8281:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8282:     my (undef,undef,$sequence)=
                   8283:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8284: 
                   8285:     #get scantron line setup
1.257     albertel 8286:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8287:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8288: 
                   8289:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8290:     unless (ref($navmap)) {
                   8291:         $r->print(&navmap_errormsg());
                   8292:         return(1,$currentphase);
                   8293:     }
                   8294:     my $map=$navmap->getResourceByUrl($sequence);
                   8295:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8296:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8297:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8298:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8299: 
1.583     raeburn  8300:     my $nav_error;
1.691     raeburn  8301:     if (ref($map)) {
                   8302:         $randomorder = $map->randomorder();
                   8303:         $randompick = $map->randompick();
                   8304:         if ($randomorder || $randompick) {
                   8305:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8306:             if ($nav_error) {
                   8307:                 $r->print(&navmap_errormsg());
                   8308:                 return(1,$currentphase);
                   8309:             }
                   8310:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8311:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8312:         }
                   8313:     } else {
                   8314:         $r->print(&navmap_errormsg());
                   8315:         return(1,$currentphase);
                   8316:     }
                   8317: 
1.649     raeburn  8318:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8319:     if ($nav_error) {
                   8320:         $r->print(&navmap_errormsg());
                   8321:         return(1,$currentphase);
                   8322:     }
1.447     foxr     8323: 
1.157     albertel 8324:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8325: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8326: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8327: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8328: 						 $scan_data,undef,\%idmap,$randomorder,
                   8329:                                                  $randompick,$sequence,\@master_seq,
                   8330:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8331:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8332: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8333: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8334: 				 'doublebubble',
1.691     raeburn  8335: 				 $$scan_record{'scantron.doubleerror'},
                   8336:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8337:     	return (1,$currentphase);
                   8338:     }
                   8339:     return (0,$currentphase+1);
                   8340: }
                   8341: 
1.423     albertel 8342: 
1.503     raeburn  8343: sub scantron_get_maxbubble {
1.649     raeburn  8344:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8345:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8346: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8347: 	&restore_bubble_lines();
1.257     albertel 8348: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8349:     }
1.330     albertel 8350: 
1.447     foxr     8351:     my (undef, undef, $sequence) =
1.257     albertel 8352: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8353: 
1.447     foxr     8354:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8355:     unless (ref($navmap)) {
                   8356:         if (ref($nav_error)) {
                   8357:             $$nav_error = 1;
                   8358:         }
1.591     raeburn  8359:         return;
1.582     raeburn  8360:     }
1.191     albertel 8361:     my $map=$navmap->getResourceByUrl($sequence);
                   8362:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8363:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8364: 
                   8365:     &Apache::lonxml::clear_problem_counter();
                   8366: 
1.557     raeburn  8367:     my $uname       = $env{'user.name'};
                   8368:     my $udom        = $env{'user.domain'};
1.435     foxr     8369:     my $cid         = $env{'request.course.id'};
                   8370:     my $total_lines = 0;
                   8371:     %bubble_lines_per_response = ();
1.447     foxr     8372:     %first_bubble_line         = ();
1.503     raeburn  8373:     %subdivided_bubble_lines   = ();
                   8374:     %responsetype_per_response = ();
1.691     raeburn  8375:     %masterseq_id_responsenum  = ();
1.554     raeburn  8376: 
1.447     foxr     8377:     my $response_number = 0;
                   8378:     my $bubble_line     = 0;
1.191     albertel 8379:     foreach my $resource (@resources) {
1.691     raeburn  8380:         my $resid = $resource->id(); 
1.672     raeburn  8381:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8382:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8383:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8384: 	    foreach my $part_id (@{$parts}) {
                   8385:                 my $lines;
                   8386: 
                   8387: 	        # TODO - make this a persistent hash not an array.
                   8388: 
                   8389:                 # optionresponse, matchresponse and rankresponse type items 
                   8390:                 # render as separate sub-questions in exam mode.
                   8391:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8392:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8393:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8394:                     my ($numbub,$numshown);
                   8395:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8396:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8397:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8398:                         }
                   8399:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8400:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8401:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8402:                         }
                   8403:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8404:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8405:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8406:                         }
                   8407:                     }
                   8408:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8409:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8410:                     }
1.649     raeburn  8411:                     my $bubbles_per_row =
                   8412:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8413:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8414:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8415:                         $inner_bubble_lines++;
                   8416:                     }
                   8417:                     for (my $i=0; $i<$numshown; $i++) {
                   8418:                         $subdivided_bubble_lines{$response_number} .= 
                   8419:                             $inner_bubble_lines.',';
                   8420:                     }
                   8421:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8422:                     $lines = $numshown * $inner_bubble_lines;
                   8423:                 } else {
                   8424:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8425:                 }
1.542     raeburn  8426: 
                   8427:                 $first_bubble_line{$response_number} = $bubble_line;
                   8428: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8429:                 $responsetype_per_response{$response_number} = 
                   8430:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8431:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8432: 	        $response_number++;
                   8433: 
                   8434: 	        $bubble_line +=  $lines;
                   8435: 	        $total_lines +=  $lines;
                   8436: 	    }
                   8437:         }
                   8438:     }
1.552     raeburn  8439:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8440: 
                   8441:     &save_bubble_lines();
                   8442:     $env{'form.scantron_maxbubble'} =
                   8443: 	$total_lines;
                   8444:     return $env{'form.scantron_maxbubble'};
                   8445: }
1.523     raeburn  8446: 
1.649     raeburn  8447: sub bubblesheet_bubbles_per_row {
                   8448:     my ($scantron_config) = @_;
                   8449:     my $bubbles_per_row;
                   8450:     if (ref($scantron_config) eq 'HASH') {
                   8451:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8452:     }
                   8453:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8454:         $bubbles_per_row = 10;
                   8455:     }
                   8456:     return $bubbles_per_row;
                   8457: }
                   8458: 
1.157     albertel 8459: sub scantron_validate_missingbubbles {
                   8460:     my ($r,$currentphase) = @_;
                   8461:     #get student info
                   8462:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8463:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8464:     my (undef,undef,$sequence)=
                   8465:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8466: 
                   8467:     #get scantron line setup
1.257     albertel 8468:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8469:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8470: 
                   8471:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8472:     unless (ref($navmap)) {
                   8473:         $r->print(&navmap_errormsg());
                   8474:         return(1,$currentphase);
                   8475:     }
                   8476: 
                   8477:     my $map=$navmap->getResourceByUrl($sequence);
                   8478:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8479:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8480:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8481:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8482: 
1.582     raeburn  8483:     my $nav_error;
1.691     raeburn  8484:     if (ref($map)) {
                   8485:         $randomorder = $map->randomorder();
                   8486:         $randompick = $map->randompick();
                   8487:         if ($randomorder || $randompick) {
                   8488:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8489:             if ($nav_error) {
                   8490:                 $r->print(&navmap_errormsg());
                   8491:                 return(1,$currentphase);
                   8492:             }
                   8493:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8494:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8495:         }
                   8496:     } else {
                   8497:         $r->print(&navmap_errormsg());
                   8498:         return(1,$currentphase);
                   8499:     }
                   8500: 
                   8501: 
1.649     raeburn  8502:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8503:     if ($nav_error) {
1.691     raeburn  8504:         $r->print(&navmap_errormsg());
1.693     raeburn  8505:         return(1,$currentphase);
1.582     raeburn  8506:     }
1.691     raeburn  8507: 
1.157     albertel 8508:     if (!$max_bubble) { $max_bubble=2**31; }
                   8509:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8510: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8511: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8512: 	my $scan_record =
                   8513:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8514: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8515:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8516:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8517: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8518: 	my @to_correct;
1.470     foxr     8519: 	
                   8520: 	# Probably here's where the error is...
                   8521: 
1.157     albertel 8522: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8523:             my $lastbubble;
                   8524:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8525:                my $question = $1;
                   8526:                my $subquestion = $2;
1.691     raeburn  8527:                my ($first,$responsenum);
                   8528:                if ($randomorder || $randompick) {
                   8529:                    $responsenum = $respnumlookup{$question-1};
                   8530:                    $first = $startline{$question-1};
                   8531:                } else {
                   8532:                    $responsenum = $question-1; 
                   8533:                    $first = $first_bubble_line{$responsenum};
                   8534:                }
                   8535:                if (!defined($first)) { next; }
                   8536:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8537:                my $subcount = 1;
                   8538:                while ($subcount<$subquestion) {
                   8539:                    $first += $subans[$subcount-1];
                   8540:                    $subcount ++;
                   8541:                }
                   8542:                my $count = $subans[$subquestion-1];
                   8543:                $lastbubble = $first + $count;
                   8544:             } else {
1.691     raeburn  8545:                my ($first,$responsenum);
                   8546:                if ($randomorder || $randompick) {
                   8547:                    $responsenum = $respnumlookup{$missing-1};
                   8548:                    $first = $startline{$missing-1};
                   8549:                } else {
                   8550:                    $responsenum = $missing-1;
                   8551:                    $first = $first_bubble_line{$responsenum};
                   8552:                }
                   8553:                if (!defined($first)) { next; }
                   8554:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8555:             }
                   8556:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8557: 	    push(@to_correct,$missing);
                   8558: 	}
                   8559: 	if (@to_correct) {
                   8560: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8561: 				     $line,'missingbubble',\@to_correct,
                   8562:                                      $randomorder,$randompick,\%respnumlookup,
                   8563:                                      \%startline);
1.157     albertel 8564: 	    return (1,$currentphase);
                   8565: 	}
                   8566: 
                   8567:     }
                   8568:     return (0,$currentphase+1);
                   8569: }
                   8570: 
1.663     raeburn  8571: sub hand_bubble_option {
                   8572:     my (undef, undef, $sequence) =
                   8573:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8574:     return if ($sequence eq '');
                   8575:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8576:     unless (ref($navmap)) {
                   8577:         return;
                   8578:     }
                   8579:     my $needs_hand_bubbles;
                   8580:     my $map=$navmap->getResourceByUrl($sequence);
                   8581:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8582:     foreach my $res (@resources) {
                   8583:         if (ref($res)) {
                   8584:             if ($res->is_problem()) {
                   8585:                 my $partlist = $res->parts();
                   8586:                 foreach my $part (@{ $partlist }) {
                   8587:                     my @types = $res->responseType($part);
                   8588:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8589:                         $needs_hand_bubbles = 1;
                   8590:                         last;
                   8591:                     }
                   8592:                 }
                   8593:             }
                   8594:         }
                   8595:     }
                   8596:     if ($needs_hand_bubbles) {
                   8597:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8598:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8599:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8600:                &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 />').
                   8601:                '<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  8602:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8603:     }
                   8604:     return;
                   8605: }
1.423     albertel 8606: 
1.82      albertel 8607: sub scantron_process_students {
1.608     www      8608:     my ($r,$symb) = @_;
1.513     foxr     8609: 
1.257     albertel 8610:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8611:     if (!$symb) {
                   8612: 	return '';
                   8613:     }
1.324     albertel 8614:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8615: 
1.257     albertel 8616:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8617:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8618:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8619:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8620:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8621:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8622:     unless (ref($navmap)) {
                   8623:         $r->print(&navmap_errormsg());
                   8624:         return '';
1.691     raeburn  8625:     }
1.83      albertel 8626:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8627:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8628:         %grader_randomlists_by_symb);
1.677     raeburn  8629:     if (ref($map)) {
                   8630:         $randomorder = $map->randomorder();
1.689     raeburn  8631:         $randompick = $map->randompick();
1.691     raeburn  8632:     } else {
                   8633:         $r->print(&navmap_errormsg());
                   8634:         return '';
1.677     raeburn  8635:     }
1.691     raeburn  8636:     my $nav_error;
1.83      albertel 8637:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8638:     if ($randomorder || $randompick) {
                   8639:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8640:         if ($nav_error) {
                   8641:             $r->print(&navmap_errormsg());
                   8642:             return '';
                   8643:         }
                   8644:     }
1.557     raeburn  8645:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8646:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8647: 
1.554     raeburn  8648:     my ($uname,$udom);
1.82      albertel 8649:     my $result= <<SCANTRONFORM;
1.81      albertel 8650: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8651:   <input type="hidden" name="command" value="scantron_configphase" />
                   8652:   $default_form_data
                   8653: SCANTRONFORM
1.82      albertel 8654:     $r->print($result);
                   8655: 
                   8656:     my @delayqueue;
1.542     raeburn  8657:     my (%completedstudents,%scandata);
1.140     albertel 8658:     
1.520     www      8659:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8660:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8661:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8662:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8663:     $r->print('<br />');
1.140     albertel 8664:     my $start=&Time::HiRes::time();
1.158     albertel 8665:     my $i=-1;
1.542     raeburn  8666:     my $started;
1.447     foxr     8667: 
1.649     raeburn  8668:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8669:     if ($nav_error) {
                   8670:         $r->print(&navmap_errormsg());
                   8671:         return '';
                   8672:     }
                   8673: 
1.513     foxr     8674:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8675:     # the user and return.
                   8676: 
                   8677:     if ($ssi_error) {
                   8678: 	$r->print("</form>");
                   8679: 	&ssi_print_error($r);
1.520     www      8680:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8681: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8682:     }
1.447     foxr     8683: 
1.542     raeburn  8684:     my %lettdig = &letter_to_digits();
                   8685:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8686:     my %orderedforcode;
1.542     raeburn  8687: 
1.157     albertel 8688:     while ($i<$scanlines->{'count'}) {
                   8689:  	($uname,$udom)=('','');
                   8690:  	$i++;
1.200     albertel 8691:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8692:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8693: 	if ($started) {
1.667     www      8694: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8695: 	}
                   8696: 	$started=1;
1.691     raeburn  8697:         my %respnumlookup = ();
                   8698:         my %startline = ();
                   8699:         my $total;
1.157     albertel 8700:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8701:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8702:                                                  $randompick,$sequence,\@master_seq,
                   8703:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8704:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8705:                                                  \$total);
1.157     albertel 8706:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8707:  					      \%idmap,$i)) {
                   8708:   	    &scantron_add_delay(\@delayqueue,$line,
                   8709:  				'Unable to find a student that matches',1);
                   8710:  	    next;
                   8711:   	}
                   8712:  	if (exists $completedstudents{$uname}) {
                   8713:  	    &scantron_add_delay(\@delayqueue,$line,
                   8714:  				'Student '.$uname.' has multiple sheets',2);
                   8715:  	    next;
                   8716:  	}
1.677     raeburn  8717:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8718:         my $user = $uname.':'.$usec;
1.157     albertel 8719:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8720: 
1.677     raeburn  8721:         my $scancode;
                   8722:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8723:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8724:             $scancode = $scan_record->{'scantron.CODE'};
                   8725:         } else {
                   8726:             $scancode = '';
                   8727:         }
                   8728: 
                   8729:         my @mapresources = @resources;
1.689     raeburn  8730:         if ($randomorder || $randompick) {
1.678     raeburn  8731:             @mapresources = 
1.691     raeburn  8732:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8733:                              \%orderedforcode);
1.677     raeburn  8734:         }
1.586     raeburn  8735:         my (%partids_by_symb,$res_error);
1.677     raeburn  8736:         foreach my $resource (@mapresources) {
1.586     raeburn  8737:             my $ressymb;
                   8738:             if (ref($resource)) {
                   8739:                 $ressymb = $resource->symb();
                   8740:             } else {
                   8741:                 $res_error = 1;
                   8742:                 last;
                   8743:             }
1.557     raeburn  8744:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8745:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8746:                 my $currcode;
                   8747:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8748:                     $currcode = $scancode;
                   8749:                 }
1.557     raeburn  8750:                 my ($analysis,$parts) =
1.672     raeburn  8751:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8752:                                               $uname,$udom,undef,$bubbles_per_row,
                   8753:                                               $currcode);
1.557     raeburn  8754:                 $partids_by_symb{$ressymb} = $parts;
                   8755:             } else {
                   8756:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8757:             }
1.554     raeburn  8758:         }
                   8759: 
1.586     raeburn  8760:         if ($res_error) {
                   8761:             &scantron_add_delay(\@delayqueue,$line,
                   8762:                                 'An error occurred while grading student '.$uname,2);
                   8763:             next;
                   8764:         }
                   8765: 
1.330     albertel 8766: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8767:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8768: 
                   8769: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8770: 	    &scantron_putfile($scanlines,$scan_data);
                   8771: 	}
1.161     albertel 8772: 	
1.542     raeburn  8773:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8774:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8775:                                    $bubbles_per_row,$randomorder,$randompick,
                   8776:                                    \%respnumlookup,\%startline) 
                   8777:             eq 'ssi_error') {
1.542     raeburn  8778:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8779:             $r->print("</form>");
                   8780:             &ssi_print_error($r);
                   8781:             &Apache::lonnet::remove_lock($lock);
                   8782:             return '';      # Why return ''?  Beats me.
                   8783:         }
1.513     foxr     8784: 
1.692     raeburn  8785:         if (($scancode) && ($randomorder || $randompick)) {
                   8786:             my $parmresult =
                   8787:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8788:                                                        '0_examcode',2,$scancode,
                   8789:                                                        'string_examcode',$uname,
                   8790:                                                        $udom);
                   8791:         }
1.140     albertel 8792: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8793:         if ($env{'form.verifyrecord'}) {
                   8794:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8795:             if ($randompick) {
                   8796:                 if ($total) {
                   8797:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8798:                 }
                   8799:             }
                   8800: 
1.542     raeburn  8801:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8802:             chomp($studentdata);
                   8803:             $studentdata =~ s/\r$//;
                   8804:             my $studentrecord = '';
                   8805:             my $counter = -1;
1.677     raeburn  8806:             foreach my $resource (@mapresources) {
1.554     raeburn  8807:                 my $ressymb = $resource->symb();
1.542     raeburn  8808:                 ($counter,my $recording) =
                   8809:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8810:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8811:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8812:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8813:                 $studentrecord .= $recording;
                   8814:             }
                   8815:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8816:                 &Apache::lonxml::clear_problem_counter();
                   8817:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8818:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8819:                                            $bubbles_per_row,$randomorder,$randompick,
                   8820:                                            \%respnumlookup,\%startline) 
                   8821:                     eq 'ssi_error') {
1.554     raeburn  8822:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8823:                     $r->print("</form>");
                   8824:                     &ssi_print_error($r);
                   8825:                     &Apache::lonnet::remove_lock($lock);
                   8826:                     delete($completedstudents{$uname});
                   8827:                     return '';
                   8828:                 }
1.542     raeburn  8829:                 $counter = -1;
                   8830:                 $studentrecord = '';
1.677     raeburn  8831:                 foreach my $resource (@mapresources) {
1.554     raeburn  8832:                     my $ressymb = $resource->symb();
1.542     raeburn  8833:                     ($counter,my $recording) =
                   8834:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8835:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8836:                                                  \%scantron_config,\%lettdig,$numletts,
                   8837:                                                  $randomorder,$randompick,\%respnumlookup,
                   8838:                                                  \%startline);
1.542     raeburn  8839:                     $studentrecord .= $recording;
                   8840:                 }
                   8841:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8842:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8843:                     if ($scancode eq '') {
1.658     bisitz   8844:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8845:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8846:                     } else {
1.658     bisitz   8847:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8848:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8849:                     }
                   8850:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8851:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8852:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8853:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8854:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8855:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8856:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8857:                               &Apache::loncommon::end_data_table_row().
                   8858:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8859:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8860:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8861:                               &Apache::loncommon::end_data_table_row().
                   8862:                               &Apache::loncommon::end_data_table().'</p>');
                   8863:                 } else {
                   8864:                     $r->print('<br /><span class="LC_warning">'.
                   8865:                              &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 />'.
                   8866:                              &mt("As a consequence, this user's submission history records two tries.").
                   8867:                                  '</span><br />');
                   8868:                 }
                   8869:             }
                   8870:         }
1.543     raeburn  8871:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8872:     } continue {
1.330     albertel 8873: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8874: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8875:     }
1.140     albertel 8876:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8877:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8878: #    my $lasttime = &Time::HiRes::time()-$start;
                   8879: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8880: 
1.200     albertel 8881:     $r->print("</form>");
1.157     albertel 8882:     return '';
1.75      albertel 8883: }
1.157     albertel 8884: 
1.557     raeburn  8885: sub graders_resources_pass {
1.649     raeburn  8886:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8887:         $bubbles_per_row) = @_;
1.557     raeburn  8888:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8889:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8890:         foreach my $resource (@{$resources}) {
                   8891:             my $ressymb = $resource->symb();
                   8892:             my ($analysis,$parts) =
                   8893:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8894:                                           $env{'user.name'},$env{'user.domain'},
                   8895:                                           1,$bubbles_per_row);
1.557     raeburn  8896:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8897:             if (ref($analysis) eq 'HASH') {
                   8898:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8899:                     $grader_randomlists_by_symb->{$ressymb} =
                   8900:                         $analysis->{'parts_withrandomlist'};
                   8901:                 }
                   8902:             }
                   8903:         }
                   8904:     }
                   8905:     return;
                   8906: }
                   8907: 
1.678     raeburn  8908: =pod
                   8909: 
                   8910: =item users_order
                   8911: 
                   8912:   Returns array of resources in current map, ordered based on either CODE,
                   8913:   if this is a CODEd exam, or based on student's identity if this is a 
                   8914:   "NAMEd" exam.
                   8915: 
1.691     raeburn  8916:   Should be used when randomorder and/or randompick applied when the 
                   8917:   corresponding exam was printed, prior to students completing bubblesheets 
                   8918:   for the version of the exam the student received.
1.678     raeburn  8919: 
                   8920: =cut
                   8921: 
                   8922: sub users_order  {
1.691     raeburn  8923:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8924:     my @mapresources;
1.691     raeburn  8925:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8926:         return @mapresources;
1.691     raeburn  8927:     }
                   8928:     if ($scancode) {
                   8929:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8930:             @mapresources = @{$orderedforcode->{$scancode}};
                   8931:         } else {
                   8932:             $env{'form.CODE'} = $scancode;
                   8933:             my $actual_seq =
                   8934:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8935:                                                                $master_seq,
                   8936:                                                                $user,$scancode,1);
                   8937:             if (ref($actual_seq) eq 'ARRAY') {
                   8938:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8939:                 if (ref($orderedforcode) eq 'HASH') {
                   8940:                     if (@mapresources > 0) { 
                   8941:                         $orderedforcode->{$scancode} = \@mapresources;
                   8942:                     }
                   8943:                 }
                   8944:             }
                   8945:             delete($env{'form.CODE'});
1.678     raeburn  8946:         }
                   8947:     } else {
                   8948:         my $actual_seq =
                   8949:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8950:                                                            $master_seq,
1.688     raeburn  8951:                                                            $user,undef,1);
1.678     raeburn  8952:         if (ref($actual_seq) eq 'ARRAY') {
                   8953:             @mapresources = 
                   8954:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8955:         }
1.691     raeburn  8956:     }
                   8957:     return @mapresources;
1.678     raeburn  8958: }
                   8959: 
1.542     raeburn  8960: sub grade_student_bubbles {
1.691     raeburn  8961:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8962:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8963:     my $uselookup = 0;
                   8964:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8965:         (ref($startline) eq 'HASH')) {
                   8966:         $uselookup = 1;
                   8967:     }
                   8968: 
1.554     raeburn  8969:     if (ref($resources) eq 'ARRAY') {
                   8970:         my $count = 0;
                   8971:         foreach my $resource (@{$resources}) {
                   8972:             my $ressymb = $resource->symb();
                   8973:             my %form = ('submitted'      => 'scantron',
                   8974:                         'grade_target'   => 'grade',
                   8975:                         'grade_username' => $uname,
                   8976:                         'grade_domain'   => $udom,
                   8977:                         'grade_courseid' => $env{'request.course.id'},
                   8978:                         'grade_symb'     => $ressymb,
                   8979:                         'CODE'           => $scancode
                   8980:                        );
1.649     raeburn  8981:             if ($bubbles_per_row ne '') {
                   8982:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8983:             }
1.663     raeburn  8984:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8985:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8986:             }
1.554     raeburn  8987:             if (ref($parts) eq 'HASH') {
                   8988:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8989:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8990:                         if ($uselookup) {
                   8991:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8992:                         } else {
                   8993:                             $form{'scantron_questnum_start.'.$part} =
                   8994:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8995:                         }
1.554     raeburn  8996:                         $count++;
                   8997:                     }
                   8998:                 }
                   8999:             }
                   9000:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9001:             return 'ssi_error' if ($ssi_error);
                   9002:             last if (&Apache::loncommon::connection_aborted($r));
                   9003:         }
1.542     raeburn  9004:     }
                   9005:     return;
                   9006: }
                   9007: 
1.157     albertel 9008: sub scantron_upload_scantron_data {
1.608     www      9009:     my ($r,$symb)=@_;
1.565     raeburn  9010:     my $dom = $env{'request.role.domain'};
                   9011:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9012:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9013:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9014: 							  'domainid',
1.565     raeburn  9015: 							  'coursename',$dom);
                   9016:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9017:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9018:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9019:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9020:     &js_escape(\$nofile_alert);
1.579     raeburn  9021:     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  9022:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9023:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9024:     function checkUpload(formname) {
                   9025: 	if (formname.upfile.value == "") {
1.579     raeburn  9026: 	    alert("'.$nofile_alert.'");
1.157     albertel 9027: 	    return false;
                   9028: 	}
1.565     raeburn  9029:         if (formname.courseid.value == "") {
1.579     raeburn  9030:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9031:             return false;
                   9032:         }
1.157     albertel 9033: 	formname.submit();
                   9034:     }
1.565     raeburn  9035: 
                   9036:     function ToSyllabus() {
                   9037:         var cdom = '."'$dom'".';
                   9038:         var cnum = document.rules.courseid.value;
                   9039:         if (cdom == "" || cdom == null) {
                   9040:             return;
                   9041:         }
                   9042:         if (cnum == "" || cnum == null) {
                   9043:            return;
                   9044:         }
                   9045:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9046:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9047:         return;
                   9048:     }
                   9049: 
1.597     wenzelju 9050: '));
                   9051:     $r->print('
1.648     bisitz   9052: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9053: 
1.492     albertel 9054: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9055: '.$default_form_data.
                   9056:   &Apache::lonhtmlcommon::start_pick_box().
                   9057:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9058:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9059:   &Apache::lonhtmlcommon::row_closure().
                   9060:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9061:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9062:   &Apache::lonhtmlcommon::row_closure().
                   9063:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9064:   '<input name="domainid" type="hidden" />'.$domdesc.
                   9065:   &Apache::lonhtmlcommon::row_closure().
                   9066:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9067:   '<input type="file" name="upfile" size="50" />'.
                   9068:   &Apache::lonhtmlcommon::row_closure(1).
                   9069:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9070: 
1.492     albertel 9071: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9072: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9073: </form>
1.492     albertel 9074: ');
1.157     albertel 9075:     return '';
                   9076: }
                   9077: 
1.423     albertel 9078: 
1.157     albertel 9079: sub scantron_upload_scantron_data_save {
1.608     www      9080:     my($r,$symb)=@_;
1.182     albertel 9081:     my $doanotherupload=
                   9082: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9083: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9084: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9085: 	'</form>'."\n";
1.257     albertel 9086:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9087: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9088: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9089: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9090: 	unless ($symb) {
1.182     albertel 9091: 	    $r->print($doanotherupload);
                   9092: 	}
1.162     albertel 9093: 	return '';
                   9094:     }
1.257     albertel 9095:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9096:     my $uploadedfile;
1.710     bisitz   9097:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9098:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9099:         $r->print(
                   9100:             &Apache::lonhtmlcommon::confirm_success(
                   9101:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9102:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9103:     } else {
1.568     raeburn  9104:         my $result = 
                   9105:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   9106:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9107:         if ($result =~ m{^/uploaded/}) {
                   9108:             $r->print(
                   9109:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9110:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9111:                         (length($env{'form.upfile'})-1),
                   9112:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9113:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9114:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9115:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   9116:         } else {
                   9117:             $r->print(
                   9118:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9119:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9120:                           $result,
1.568     raeburn  9121: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9122: 	}
                   9123:     }
1.174     albertel 9124:     if ($symb) {
1.612     www      9125: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9126:     } else {
1.182     albertel 9127: 	$r->print($doanotherupload);
1.174     albertel 9128:     }
1.157     albertel 9129:     return '';
                   9130: }
                   9131: 
1.567     raeburn  9132: sub validate_uploaded_scantron_file {
                   9133:     my ($cdom,$cname,$fname) = @_;
                   9134:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9135:     my @lines;
                   9136:     if ($scanlines ne '-1') {
                   9137:         @lines=split("\n",$scanlines,-1);
                   9138:     }
                   9139:     my $output;
                   9140:     if (@lines) {
                   9141:         my (%counts,$max_match_format);
1.710     bisitz   9142:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9143:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9144:         my %idmap = &username_to_idmap($classlist);
                   9145:         foreach my $key (keys(%idmap)) {
                   9146:             my $lckey = lc($key);
                   9147:             $idmap{$lckey} = $idmap{$key};
                   9148:         }
                   9149:         my %unique_formats;
                   9150:         my @formatlines = &get_scantronformat_file();
                   9151:         foreach my $line (@formatlines) {
                   9152:             chomp($line);
                   9153:             my @config = split(/:/,$line);
                   9154:             my $idstart = $config[5];
                   9155:             my $idlength = $config[6];
                   9156:             if (($idstart ne '') && ($idlength > 0)) {
                   9157:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9158:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9159:                 } else {
                   9160:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9161:                 }
                   9162:             }
                   9163:         }
                   9164:         foreach my $key (keys(%unique_formats)) {
                   9165:             my ($idstart,$idlength) = split(':',$key);
                   9166:             %{$counts{$key}} = (
                   9167:                                'found'   => 0,
                   9168:                                'total'   => 0,
                   9169:                               );
                   9170:             foreach my $line (@lines) {
                   9171:                 next if ($line =~ /^#/);
                   9172:                 next if ($line =~ /^[\s\cz]*$/);
                   9173:                 my $id = substr($line,$idstart-1,$idlength);
                   9174:                 $id = lc($id);
                   9175:                 if (exists($idmap{$id})) {
                   9176:                     $counts{$key}{'found'} ++;
                   9177:                 }
                   9178:                 $counts{$key}{'total'} ++;
                   9179:             }
                   9180:             if ($counts{$key}{'total'}) {
                   9181:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9182:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9183:                     $max_match_pct = $percent_match;
                   9184:                     $max_match_format = $key;
1.710     bisitz   9185:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9186:                     $max_match_count = $counts{$key}{'total'};
                   9187:                 }
                   9188:             }
                   9189:         }
                   9190:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9191:             my $format_descs;
                   9192:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9193:             for (my $i=0; $i<$numwithformat; $i++) {
                   9194:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9195:                 if ($i<$numwithformat-2) {
                   9196:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9197:                 } elsif ($i==$numwithformat-2) {
                   9198:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9199:                 } elsif ($i==$numwithformat-1) {
                   9200:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9201:                 }
                   9202:             }
                   9203:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9204:             $output .= '<br />';
                   9205:             if ($found_match_count == $max_match_count) {
                   9206:                 # 100% matching entries
                   9207:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9208:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9209:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9210:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9211:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9212:                     ' in the file (for the format defined for [_3]).',
                   9213:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9214:             } else {
                   9215:                 # Not all entries matching? -> Show warning and additional info
                   9216:                 $output .=
                   9217:                     &Apache::lonhtmlcommon::confirm_success(
                   9218:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9219:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9220:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9221:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9222:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9223:                         ' in the file (for the format defined for [_3]).',
                   9224:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9225:                     '<p class="LC_info">'.
                   9226:                     &mt('A low percentage of matches results from one of the following:').
                   9227:                     '</p><ul>'.
                   9228:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9229:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9230:                                '<i>'.$cdom.'</i>').'</li>'.
                   9231:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9232:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9233:                     '</ul>';
                   9234:             }
1.567     raeburn  9235:         }
                   9236:     } else {
1.710     bisitz   9237:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9238:     }
                   9239:     return $output;
                   9240: }
                   9241: 
1.202     albertel 9242: sub valid_file {
                   9243:     my ($requested_file)=@_;
                   9244:     foreach my $filename (sort(&scantron_filenames())) {
                   9245: 	if ($requested_file eq $filename) { return 1; }
                   9246:     }
                   9247:     return 0;
                   9248: }
                   9249: 
                   9250: sub scantron_download_scantron_data {
1.608     www      9251:     my ($r,$symb)=@_;
                   9252:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9253:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9254:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9255:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9256:     if (! &valid_file($file)) {
1.492     albertel 9257: 	$r->print('
1.202     albertel 9258: 	<p>
1.686     bisitz   9259: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9260:         </p>
1.492     albertel 9261: ');
1.202     albertel 9262: 	return;
                   9263:     }
                   9264:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9265:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9266:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9267:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9268:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9269:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9270:     $r->print('
1.202     albertel 9271:     <p>
1.723     raeburn  9272: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9273: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9274:     </p>
                   9275:     <p>
1.492     albertel 9276: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9277: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9278:     </p>
                   9279:     <p>
1.492     albertel 9280: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9281: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9282:     </p>
1.492     albertel 9283: ');
1.202     albertel 9284:     return '';
                   9285: }
1.157     albertel 9286: 
1.523     raeburn  9287: sub checkscantron_results {
1.608     www      9288:     my ($r,$symb) = @_;
1.523     raeburn  9289:     if (!$symb) {return '';}
                   9290:     my $cid = $env{'request.course.id'};
1.542     raeburn  9291:     my %lettdig = &letter_to_digits();
1.523     raeburn  9292:     my $numletts = scalar(keys(%lettdig));
                   9293:     my $cnum = $env{'course.'.$cid.'.num'};
                   9294:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9295:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9296:     my %record;
                   9297:     my %scantron_config =
                   9298:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9299:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9300:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9301:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9302:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9303:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9304:     unless (ref($navmap)) {
                   9305:         $r->print(&navmap_errormsg());
                   9306:         return '';
                   9307:     }
1.523     raeburn  9308:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9309:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9310:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9311:     if (ref($map)) { 
                   9312:         $randomorder=$map->randomorder();
1.689     raeburn  9313:         $randompick=$map->randompick();
1.677     raeburn  9314:     }
1.557     raeburn  9315:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9316:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9317:     if ($nav_error) {
                   9318:         $r->print(&navmap_errormsg());
                   9319:         return '';
1.678     raeburn  9320:     }
1.673     raeburn  9321:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9322:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9323:     my ($uname,$udom);
1.523     raeburn  9324:     my (%scandata,%lastname,%bylast);
                   9325:     $r->print('
                   9326: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9327: 
                   9328:     my @delayqueue;
                   9329:     my %completedstudents;
                   9330: 
1.691     raeburn  9331:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9332:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9333:     my ($username,$domain,$started);
1.649     raeburn  9334:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9335:     if ($nav_error) {
                   9336:         $r->print(&navmap_errormsg());
                   9337:         return '';
                   9338:     }
1.523     raeburn  9339: 
1.667     www      9340:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9341:     my $start=&Time::HiRes::time();
                   9342:     my $i=-1;
                   9343: 
                   9344:     while ($i<$scanlines->{'count'}) {
                   9345:         ($username,$domain,$uname)=('','','');
                   9346:         $i++;
                   9347:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9348:         if ($line=~/^[\s\cz]*$/) { next; }
                   9349:         if ($started) {
1.667     www      9350:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9351:         }
                   9352:         $started=1;
                   9353:         my $scan_record=
                   9354:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9355:                                                      $scan_data);
1.693     raeburn  9356:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9357:                                               \%idmap,$i)) {
1.523     raeburn  9358:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9359:                                 'Unable to find a student that matches',1);
                   9360:             next;
                   9361:         }
                   9362:         if (exists $completedstudents{$uname}) {
                   9363:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9364:                                 'Student '.$uname.' has multiple sheets',2);
                   9365:             next;
                   9366:         }
                   9367:         my $pid = $scan_record->{'scantron.ID'};
                   9368:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9369:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9370:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9371:         my $user = $uname.':'.$usec;
1.523     raeburn  9372:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9373: 
1.678     raeburn  9374:         my $scancode;
1.677     raeburn  9375:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9376:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9377:             $scancode = $scan_record->{'scantron.CODE'};
                   9378:         } else {
                   9379:             $scancode = '';
                   9380:         }
                   9381: 
                   9382:         my @mapresources = @resources;
1.691     raeburn  9383:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9384:         my %respnumlookup=();
                   9385:         my %startline=();
1.689     raeburn  9386:         if ($randomorder || $randompick) {
1.678     raeburn  9387:             @mapresources =
1.691     raeburn  9388:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9389:                              \%orderedforcode);
                   9390:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9391:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9392:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9393:                                              \%respnumlookup,\%startline);
                   9394:             if ($randompick && $total) {
                   9395:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9396:             }
1.677     raeburn  9397:         }
1.691     raeburn  9398:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9399:         chomp($scandata{$pid});
                   9400:         $scandata{$pid} =~ s/\r$//;
                   9401: 
1.523     raeburn  9402:         my $counter = -1;
1.677     raeburn  9403:         foreach my $resource (@mapresources) {
1.557     raeburn  9404:             my $parts;
1.554     raeburn  9405:             my $ressymb = $resource->symb();
1.557     raeburn  9406:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9407:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9408:                 my $currcode;
                   9409:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9410:                     $currcode = $scancode;
                   9411:                 }
1.557     raeburn  9412:                 (my $analysis,$parts) =
1.672     raeburn  9413:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9414:                                               $username,$domain,undef,
1.741     raeburn  9415:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9416:             } else {
                   9417:                 $parts = $grader_partids_by_symb{$ressymb};
                   9418:             }
1.542     raeburn  9419:             ($counter,my $recording) =
                   9420:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9421:                                          $scandata{$pid},$parts,
1.691     raeburn  9422:                                          \%scantron_config,\%lettdig,$numletts,
                   9423:                                          $randomorder,$randompick,
                   9424:                                          \%respnumlookup,\%startline);
1.542     raeburn  9425:             $record{$pid} .= $recording;
1.523     raeburn  9426:         }
                   9427:     }
                   9428:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9429:     $r->print('<br />');
                   9430:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9431:     $passed = 0;
                   9432:     $failed = 0;
                   9433:     $numstudents = 0;
                   9434:     foreach my $last (sort(keys(%bylast))) {
                   9435:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9436:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9437:                 my $showscandata = $scandata{$pid};
                   9438:                 my $showrecord = $record{$pid};
                   9439:                 $showscandata =~ s/\s/&nbsp;/g;
                   9440:                 $showrecord =~ s/\s/&nbsp;/g;
                   9441:                 if ($scandata{$pid} eq $record{$pid}) {
                   9442:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9443:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9444: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9445: '</tr>'."\n".
                   9446: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9447: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9448:                     $passed ++;
                   9449:                 } else {
                   9450:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9451:                     $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  9452: '</tr>'."\n".
                   9453: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9454: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9455: '</tr>'."\n";
                   9456:                     $failed ++;
                   9457:                 }
                   9458:                 $numstudents ++;
                   9459:             }
                   9460:         }
                   9461:     }
1.648     bisitz   9462:     $r->print(
                   9463:         '<p>'
                   9464:        .&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).',
                   9465:             '<b>',
                   9466:             $numstudents,
                   9467:             '</b>',
                   9468:             $env{'form.scantron_maxbubble'})
                   9469:        .'</p>'
                   9470:     );
1.682     raeburn  9471:     $r->print('<p>'
1.683     raeburn  9472:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9473:              .'<br />'
                   9474:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9475:              .'</p>'
                   9476:     );
1.523     raeburn  9477:     if ($passed) {
1.572     www      9478:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9479:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9480:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9481:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9482:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9483:                  $okstudents."\n".
                   9484:                  &Apache::loncommon::end_data_table().'<br />');
                   9485:     }
                   9486:     if ($failed) {
1.572     www      9487:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9488:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9489:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9490:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9491:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9492:                  $badstudents."\n".
                   9493:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9494:                  &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  9495:     }
1.614     www      9496:     $r->print('</form><br />');
1.523     raeburn  9497:     return;
                   9498: }
                   9499: 
1.542     raeburn  9500: sub verify_scantron_grading {
1.554     raeburn  9501:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9502:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9503:         $respnumlookup,$startline) = @_;
1.542     raeburn  9504:     my ($record,%expected,%startpos);
                   9505:     return ($counter,$record) if (!ref($resource));
                   9506:     return ($counter,$record) if (!$resource->is_problem());
                   9507:     my $symb = $resource->symb();
1.554     raeburn  9508:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9509:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9510:         $counter ++;
                   9511:         $expected{$part_id} = 0;
1.691     raeburn  9512:         my $respnum = $counter;
                   9513:         if ($randomorder || $randompick) {
                   9514:             $respnum = $respnumlookup->{$counter};
                   9515:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9516:         } else {
                   9517:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9518:         }
                   9519:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9520:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9521:             foreach my $item (@sub_lines) {
                   9522:                 $expected{$part_id} += $item;
                   9523:             }
                   9524:         } else {
1.691     raeburn  9525:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9526:         }
                   9527:     }
                   9528:     if ($symb) {
                   9529:         my %recorded;
                   9530:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9531:         if ($returnhash{'version'}) {
                   9532:             my %lasthash=();
                   9533:             my $version;
                   9534:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9535:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9536:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9537:                 }
                   9538:             }
                   9539:             foreach my $key (keys(%lasthash)) {
                   9540:                 if ($key =~ /\.scantron$/) {
                   9541:                     my $value = &unescape($lasthash{$key});
                   9542:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9543:                     if ($value eq '') {
                   9544:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9545:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9546:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9547:                             }
                   9548:                         }
                   9549:                     } else {
                   9550:                         my @tocheck;
                   9551:                         my @items = split(//,$value);
                   9552:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9553:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9554:                             if (@items < $expected{$part_id}) {
                   9555:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9556:                                 my @singles = split(//,$fragment);
                   9557:                                 foreach my $pos (@singles) {
                   9558:                                     if ($pos eq ' ') {
                   9559:                                         push(@tocheck,$pos);
                   9560:                                     } else {
                   9561:                                         my $next = shift(@items);
                   9562:                                         push(@tocheck,$next);
                   9563:                                     }
                   9564:                                 }
                   9565:                             } else {
                   9566:                                 @tocheck = @items;
                   9567:                             }
                   9568:                             foreach my $letter (@tocheck) {
                   9569:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9570:                                     if ($letter !~ /^[A-J]$/) {
                   9571:                                         $letter = $scantron_config->{'Qoff'};
                   9572:                                     }
                   9573:                                     $recorded{$part_id} .= $letter;
                   9574:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9575:                                     my $digit;
                   9576:                                     if ($letter !~ /^[A-J]$/) {
                   9577:                                         $digit = $scantron_config->{'Qoff'};
                   9578:                                     } else {
                   9579:                                         $digit = $lettdig->{$letter};
                   9580:                                     }
                   9581:                                     $recorded{$part_id} .= $digit;
                   9582:                                 }
                   9583:                             }
                   9584:                         } else {
                   9585:                             @tocheck = @items;
                   9586:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9587:                                 my $curr_sub = shift(@tocheck);
                   9588:                                 my $digit;
                   9589:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9590:                                     $digit = $lettdig->{$curr_sub}-1;
                   9591:                                 }
                   9592:                                 if ($curr_sub eq 'J') {
                   9593:                                     $digit += scalar($numletts);
                   9594:                                 }
                   9595:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9596:                                     if ($j == $digit) {
                   9597:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9598:                                     } else {
                   9599:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9600:                                     }
                   9601:                                 }
                   9602:                             }
                   9603:                         }
                   9604:                     }
                   9605:                 }
                   9606:             }
                   9607:         }
1.554     raeburn  9608:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9609:             if ($recorded{$part_id} eq '') {
                   9610:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9611:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9612:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9613:                     }
                   9614:                 }
                   9615:             }
                   9616:             $record .= $recorded{$part_id};
                   9617:         }
                   9618:     }
                   9619:     return ($counter,$record);
                   9620: }
                   9621: 
1.691     raeburn  9622: sub letter_to_digits {
1.542     raeburn  9623:     my %lettdig = (
                   9624:                     A => 1,
                   9625:                     B => 2,
                   9626:                     C => 3,
                   9627:                     D => 4,
                   9628:                     E => 5,
                   9629:                     F => 6,
                   9630:                     G => 7,
                   9631:                     H => 8,
                   9632:                     I => 9,
                   9633:                     J => 0,
                   9634:                   );
                   9635:     return %lettdig;
                   9636: }
                   9637: 
1.423     albertel 9638: 
1.75      albertel 9639: #-------- end of section for handling grading scantron forms -------
                   9640: #
                   9641: #-------------------------------------------------------------------
                   9642: 
1.72      ng       9643: #-------------------------- Menu interface -------------------------
                   9644: #
1.614     www      9645: #--- Href with symb and command ---
                   9646: 
                   9647: sub href_symb_cmd {
                   9648:     my ($symb,$cmd)=@_;
1.669     raeburn  9649:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9650: }
                   9651: 
1.443     banghart 9652: sub grading_menu {
1.608     www      9653:     my ($request,$symb) = @_;
1.443     banghart 9654:     if (!$symb) {return '';}
                   9655: 
                   9656:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9657:                   'command'=>'individual');
1.538     schulted 9658:     
1.598     www      9659:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9660: 
                   9661:     $fields{'command'}='ungraded';
                   9662:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9663: 
                   9664:     $fields{'command'}='table';
                   9665:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9666: 
                   9667:     $fields{'command'}='all_for_one';
                   9668:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9669: 
1.621     www      9670:     $fields{'command'}='downloadfilesselect';
                   9671:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9672: 
1.443     banghart 9673:     $fields{'command'} = 'csvform';
1.538     schulted 9674:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9675:     
1.443     banghart 9676:     $fields{'command'} = 'processclicker';
1.538     schulted 9677:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9678:     
1.443     banghart 9679:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9680:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9681: 
                   9682:     $fields{'command'} = 'initialverifyreceipt';
                   9683:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9684:     
1.598     www      9685:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9686:             items =>[
1.598     www      9687:                         {	linktext => 'Select individual students to grade',
                   9688:                     		url => $url1a,
1.538     schulted 9689:                     		permission => 'F',
1.636     wenzelju 9690:                     		icon => 'grade_students.png',
1.598     www      9691:                     		linktitle => 'Grade current resource for a selection of students.'
                   9692:                         }, 
                   9693:                         {       linktext => 'Grade ungraded submissions.',
                   9694:                                 url => $url1b,
                   9695:                                 permission => 'F',
1.636     wenzelju 9696:                                 icon => 'ungrade_sub.png',
1.598     www      9697:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9698:                         },
1.598     www      9699: 
                   9700:                         {       linktext => 'Grading table',
                   9701:                                 url => $url1c,
                   9702:                                 permission => 'F',
1.636     wenzelju 9703:                                 icon => 'grading_table.png',
1.598     www      9704:                                 linktitle => 'Grade current resource for all students.'
                   9705:                         },
1.615     www      9706:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9707:                                 url => $url1d,
                   9708:                                 permission => 'F',
1.636     wenzelju 9709:                                 icon => 'grade_PageFolder.png',
1.598     www      9710:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9711:                         },
                   9712:                         {       linktext => 'Download submissions',
                   9713:                                 url => $url1e,
                   9714:                                 permission => 'F',
1.636     wenzelju 9715:                                 icon => 'download_sub.png',
1.621     www      9716:                                 linktitle => 'Download all students submissions.'
1.598     www      9717:                         }]},
                   9718:                          { categorytitle=>'Automated Grading',
                   9719:                items =>[
                   9720: 
1.538     schulted 9721:                 	    {	linktext => 'Upload Scores',
                   9722:                     		url => $url2,
                   9723:                     		permission => 'F',
                   9724:                     		icon => 'uploadscores.png',
                   9725:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9726:                 	    },
                   9727:                 	    {	linktext => 'Process Clicker',
                   9728:                     		url => $url3,
                   9729:                     		permission => 'F',
                   9730:                     		icon => 'addClickerInfoFile.png',
                   9731:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9732:                 	    },
1.587     raeburn  9733:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9734:                     		url => $url4,
                   9735:                     		permission => 'F',
1.636     wenzelju 9736:                     		icon => 'bubblesheet.png',
1.648     bisitz   9737:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9738:                 	    },
1.616     www      9739:                             {   linktext => 'Verify Receipt Number',
1.602     www      9740:                                 url => $url5,
                   9741:                                 permission => 'F',
1.636     wenzelju 9742:                                 icon => 'receipt_number.png',
1.602     www      9743:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9744:                             }
                   9745: 
1.538     schulted 9746:                     ]
                   9747:             });
                   9748: 
1.443     banghart 9749:     # Create the menu
                   9750:     my $Str;
1.445     banghart 9751:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9752:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9753:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9754: 
1.602     www      9755:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9756:     return $Str;    
                   9757: }
                   9758: 
1.598     www      9759: 
                   9760: sub ungraded {
                   9761:     my ($request)=@_;
                   9762:     &submit_options($request);
                   9763: }
                   9764: 
1.599     www      9765: sub submit_options_sequence {
1.608     www      9766:     my ($request,$symb) = @_;
1.599     www      9767:     if (!$symb) {return '';}
1.600     www      9768:     &commonJSfunctions($request);
                   9769:     my $result;
1.599     www      9770: 
1.600     www      9771:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9772:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9773:     $result.=&selectfield(0).
1.601     www      9774:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9775:             <div>
                   9776:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9777:             </div>
                   9778:         </div>
                   9779:   </form>';
                   9780:     return $result;
                   9781: }
                   9782: 
                   9783: sub submit_options_table {
1.608     www      9784:     my ($request,$symb) = @_;
1.600     www      9785:     if (!$symb) {return '';}
1.599     www      9786:     &commonJSfunctions($request);
1.746     raeburn  9787:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      9788:     my $result;
                   9789: 
                   9790:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9791:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9792: 
1.745     raeburn  9793:     $result.=&selectfield(1,$is_tool).
1.601     www      9794:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9795:             <div>
                   9796:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9797:             </div>
                   9798:         </div>
                   9799:   </form>';
                   9800:     return $result;
                   9801: }
1.443     banghart 9802: 
1.621     www      9803: sub submit_options_download {
                   9804:     my ($request,$symb) = @_;
                   9805:     if (!$symb) {return '';}
                   9806: 
1.746     raeburn  9807:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      9808:     &commonJSfunctions($request);
                   9809: 
                   9810:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9811:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9812:     $result.='
                   9813: <h2>
                   9814:   '.&mt('Select Students for Which to Download Submissions').'
1.745     raeburn  9815: </h2>'.&selectfield(1,$is_tool).'
1.621     www      9816:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9817:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9818:             </div>
                   9819:           </div>
1.600     www      9820: 
                   9821: 
1.621     www      9822:   </form>';
                   9823:     return $result;
                   9824: }
                   9825: 
1.443     banghart 9826: #--- Displays the submissions first page -------
                   9827: sub submit_options {
1.608     www      9828:     my ($request,$symb) = @_;
1.72      ng       9829:     if (!$symb) {return '';}
                   9830: 
1.746     raeburn  9831:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       9832:     &commonJSfunctions($request);
1.473     albertel 9833:     my $result;
1.533     bisitz   9834: 
1.72      ng       9835:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9836: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  9837:     $result.=&selectfield(1,$is_tool).'
1.601     www      9838:                 <input type="hidden" name="command" value="submission" /> 
                   9839: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9840:             </div>
                   9841:           </div>
                   9842: 
                   9843: 
                   9844:   </form>';
                   9845:     return $result;
                   9846: }
1.533     bisitz   9847: 
1.601     www      9848: sub selectfield {
1.745     raeburn  9849:    my ($full,$is_tool)=@_;
                   9850:    my %options;
                   9851:    if ($is_tool) {
                   9852:        %options =
                   9853:            (&transtatus_options,
                   9854:             'select_form_order' => ['yes','incorrect','all']);
                   9855:    } else {
                   9856:        %options = 
                   9857:            (&substatus_options,
                   9858:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   9859:    }
1.601     www      9860:    my $result='<div class="LC_columnSection">
1.537     harmsja  9861:   
1.533     bisitz   9862:     <fieldset>
                   9863:       <legend>
                   9864:        '.&mt('Sections').'
                   9865:       </legend>
1.601     www      9866:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9867:     </fieldset>
1.537     harmsja  9868:   
1.533     bisitz   9869:     <fieldset>
                   9870:       <legend>
                   9871:         '.&mt('Groups').'
                   9872:       </legend>
                   9873:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9874:     </fieldset>
1.537     harmsja  9875:   
1.533     bisitz   9876:     <fieldset>
                   9877:       <legend>
                   9878:         '.&mt('Access Status').'
                   9879:       </legend>
1.601     www      9880:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9881:     </fieldset>';
                   9882:     if ($full) {
1.745     raeburn  9883:         my $heading = &mt('Submission Status');
                   9884:         if ($is_tool) {
                   9885:             $heading = &mt('Transaction Status');
                   9886:         }
                   9887:         $result.='
1.533     bisitz   9888:     <fieldset>
                   9889:       <legend>
1.745     raeburn  9890:         '.$heading.'
1.601     www      9891:       </legend>'.
1.635     raeburn  9892:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9893:    '</fieldset>';
                   9894:     }
                   9895:     $result.='</div><br />';
1.44      ng       9896:     return $result;
1.2       albertel 9897: }
                   9898: 
1.738     raeburn  9899: sub substatus_options {
                   9900:     return &Apache::lonlocal::texthash(
                   9901:                                       'yes'       => 'with submissions',
                   9902:                                       'queued'    => 'in grading queue',
                   9903:                                       'graded'    => 'with ungraded submissions',
                   9904:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  9905:                                       'all'       => 'with any status',
                   9906:                                       );
1.738     raeburn  9907: }
                   9908: 
1.745     raeburn  9909: sub transtatus_options {
                   9910:     return &Apache::lonlocal::texthash(
                   9911:                                        'yes'       => 'with score transactions',
                   9912:                                        'incorrect' => 'with less than full credit',
                   9913:                                        'all'       => 'with any status',
                   9914:                                       );
                   9915: }
                   9916: 
1.285     albertel 9917: sub reset_perm {
                   9918:     undef(%perm);
                   9919: }
                   9920: 
                   9921: sub init_perm {
                   9922:     &reset_perm();
1.300     albertel 9923:     foreach my $test_perm ('vgr','mgr','opa') {
                   9924: 
                   9925: 	my $scope = $env{'request.course.id'};
                   9926: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9927: 
                   9928: 	    $scope .= '/'.$env{'request.course.sec'};
                   9929: 	    if ( $perm{$test_perm}=
                   9930: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9931: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9932: 	    } else {
                   9933: 		delete($perm{$test_perm});
                   9934: 	    }
1.285     albertel 9935: 	}
                   9936:     }
                   9937: }
                   9938: 
1.674     raeburn  9939: sub init_old_essays {
                   9940:     my ($symb,$apath,$adom,$aname) = @_;
                   9941:     if ($symb ne '') {
                   9942:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9943:         if (keys(%essays) > 0) {
                   9944:             $old_essays{$symb} = \%essays;
                   9945:         }
                   9946:     }
                   9947:     return;
                   9948: }
                   9949: 
                   9950: sub reset_old_essays {
                   9951:     undef(%old_essays);
                   9952: }
                   9953: 
1.400     www      9954: sub gather_clicker_ids {
1.408     albertel 9955:     my %clicker_ids;
1.400     www      9956: 
                   9957:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9958: 
                   9959:     # Set up a couple variables.
1.407     albertel 9960:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9961:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9962:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9963: 
1.407     albertel 9964:     foreach my $student (keys(%$classlist)) {
1.438     www      9965:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9966:         my $username = $classlist->{$student}->[$username_idx];
                   9967:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9968:         my $clickers =
1.408     albertel 9969: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9970:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9971:             $id=~s/^[\#0]+//;
1.421     www      9972:             $id=~s/[\-\:]//g;
1.407     albertel 9973:             if (exists($clicker_ids{$id})) {
1.408     albertel 9974: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9975:             } else {
1.408     albertel 9976: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9977:             }
                   9978:         }
                   9979:     }
1.407     albertel 9980:     return %clicker_ids;
1.400     www      9981: }
                   9982: 
1.402     www      9983: sub gather_adv_clicker_ids {
1.408     albertel 9984:     my %clicker_ids;
1.402     www      9985:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9986:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9987:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9988:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9989:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9990:             my ($puname,$pudom)=split(/\:/,$person);
                   9991:             my $clickers =
1.408     albertel 9992: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9993:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9994: 		$id=~s/^[\#0]+//;
1.421     www      9995:                 $id=~s/[\-\:]//g;
1.408     albertel 9996: 		if (exists($clicker_ids{$id})) {
                   9997: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9998: 		} else {
                   9999: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10000: 		}
1.405     www      10001:             }
1.402     www      10002:         }
                   10003:     }
1.407     albertel 10004:     return %clicker_ids;
1.402     www      10005: }
                   10006: 
1.413     www      10007: sub clicker_grading_parameters {
                   10008:     return ('gradingmechanism' => 'scalar',
                   10009:             'upfiletype' => 'scalar',
                   10010:             'specificid' => 'scalar',
                   10011:             'pcorrect' => 'scalar',
                   10012:             'pincorrect' => 'scalar');
                   10013: }
                   10014: 
1.400     www      10015: sub process_clicker {
1.608     www      10016:     my ($r,$symb)=@_;
1.400     www      10017:     if (!$symb) {return '';}
                   10018:     my $result=&checkforfile_js();
1.632     www      10019:     $result.=&Apache::loncommon::start_data_table().
                   10020:              &Apache::loncommon::start_data_table_header_row().
                   10021:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10022:              &Apache::loncommon::end_data_table_header_row().
                   10023:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10024: # Attempt to restore parameters from last session, set defaults if not present
                   10025:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10026:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10027:                                                  \%Saveable_Parameters);
                   10028:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10029:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10030:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10031:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10032: 
                   10033:     my %checked;
1.521     www      10034:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10035:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10036:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10037:        }
                   10038:     }
                   10039: 
1.632     www      10040:     my $upload=&mt("Evaluate File");
1.400     www      10041:     my $type=&mt("Type");
1.402     www      10042:     my $attendance=&mt("Award points just for participation");
                   10043:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10044:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10045:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10046:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10047:     my $pcorrect=&mt("Percentage points for correct solution");
                   10048:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10049:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10050: 						   {'iclicker' => 'i>clicker',
1.666     www      10051:                                                     'interwrite' => 'interwrite PRS',
                   10052:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10053:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10054:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10055: function sanitycheck() {
                   10056: // Accept only integer percentages
                   10057:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10058:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10059: // Find out grading choice
                   10060:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10061:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10062:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10063:       }
                   10064:    }
                   10065: // By default, new choice equals user selection
                   10066:    newgradingchoice=gradingchoice;
                   10067: // Not good to give more points for false answers than correct ones
                   10068:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10069:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10070:    }
                   10071: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10072:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10073:       document.forms.gradesupload.pcorrect.value=100;
                   10074:       document.forms.gradesupload.pincorrect.value=100;
                   10075:    }
                   10076: // If the values are different, cannot be attendance only
                   10077:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10078:        (gradingchoice=='attendance')) {
                   10079:        newgradingchoice='personnel';
                   10080:    }
                   10081: // Change grading choice to new one
                   10082:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10083:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10084:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10085:       } else {
                   10086:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10087:       }
                   10088:    }
                   10089: // Remember the old state
                   10090:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10091: }
1.597     wenzelju 10092: ENDUPFORM
                   10093:     $result.= <<ENDUPFORM;
1.400     www      10094: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10095: <input type="hidden" name="symb" value="$symb" />
                   10096: <input type="hidden" name="command" value="processclickerfile" />
                   10097: <input type="file" name="upfile" size="50" />
                   10098: <br /><label>$type: $selectform</label>
1.632     www      10099: ENDUPFORM
                   10100:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10101:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10102:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10103: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10104: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10105: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10106: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10107: <br />&nbsp;&nbsp;&nbsp;
                   10108: <input type="text" name="givenanswer" size="50" />
1.413     www      10109: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10110: ENDGRADINGFORM
                   10111:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10112:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10113:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10114: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10115: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 10116: </form>'
1.632     www      10117: ENDPERCFORM
                   10118:     $result.='</td>'.
                   10119:              &Apache::loncommon::end_data_table_row().
                   10120:              &Apache::loncommon::end_data_table();
1.400     www      10121:     return $result;
                   10122: }
                   10123: 
                   10124: sub process_clicker_file {
1.608     www      10125:     my ($r,$symb)=@_;
1.400     www      10126:     if (!$symb) {return '';}
1.413     www      10127: 
                   10128:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10129:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10130:                                               \%Saveable_Parameters);
1.598     www      10131:     my $result='';
1.404     www      10132:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10133: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10134: 	return $result;
1.404     www      10135:     }
1.522     www      10136:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10137:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10138:         return $result;
1.521     www      10139:     }
1.522     www      10140:     my $foundgiven=0;
1.521     www      10141:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10142:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10143:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10144:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10145:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10146:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10147:         $foundgiven=$#answers+1;
1.521     www      10148:     }
1.407     albertel 10149:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10150:     my %correct_ids;
1.404     www      10151:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10152: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10153:     }
                   10154:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10155: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10156: 	   $correct_id=~tr/a-z/A-Z/;
                   10157: 	   $correct_id=~s/\s//gs;
                   10158: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10159:            $correct_id=~s/[\-\:]//g;
1.414     www      10160:            if ($correct_id) {
                   10161: 	      $correct_ids{$correct_id}='specified';
                   10162:            }
                   10163:         }
1.400     www      10164:     }
1.404     www      10165:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10166: 	$result.=&mt('Score based on attendance only');
1.521     www      10167:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10168:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10169:     } else {
1.408     albertel 10170: 	my $number=0;
1.411     www      10171: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10172: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10173: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10174: 	    if ($correct_ids{$id} eq 'specified') {
                   10175: 		$result.=&mt('specified');
                   10176: 	    } else {
                   10177: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10178: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10179: 	    }
                   10180: 	    $number++;
                   10181: 	}
1.411     www      10182:         $result.="</p>\n";
1.710     bisitz   10183:         if ($number==0) {
                   10184:             $result .=
                   10185:                  &Apache::lonhtmlcommon::confirm_success(
                   10186:                      &mt('No IDs found to determine correct answer'),1);
                   10187:             return $result;
                   10188:         }
1.404     www      10189:     }
1.405     www      10190:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10191:         $result .=
                   10192:             &Apache::lonhtmlcommon::confirm_success(
                   10193:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10194:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10195:         return $result;
1.405     www      10196:     }
1.410     www      10197: 
                   10198: # Were able to get all the info needed, now analyze the file
                   10199: 
1.411     www      10200:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10201:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10202:     $result.=&Apache::loncommon::start_data_table().
                   10203:              &Apache::loncommon::start_data_table_header_row().
                   10204:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10205:              &Apache::loncommon::end_data_table_header_row().
                   10206:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10207: <td>
1.410     www      10208: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10209: <input type="hidden" name="symb" value="$symb" />
                   10210: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10211: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10212: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10213: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10214: ENDHEADER
1.522     www      10215:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10216:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10217:     } 
1.408     albertel 10218:     my %responses;
                   10219:     my @questiontitles;
1.405     www      10220:     my $errormsg='';
                   10221:     my $number=0;
                   10222:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10223: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10224:     }
1.419     www      10225:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10226:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10227:     }
1.666     www      10228:     if ($env{'form.upfiletype'} eq 'turning') {
                   10229:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10230:     }
1.411     www      10231:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10232:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10233:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10234:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10235:              '<br />';
1.522     www      10236:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10237:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10238:        return $result;
1.522     www      10239:     } 
1.414     www      10240: # Remember Question Titles
                   10241: # FIXME: Possibly need delimiter other than ":"
                   10242:     for (my $i=0;$i<$number;$i++) {
                   10243:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10244:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10245:     }
1.411     www      10246:     my $correct_count=0;
                   10247:     my $student_count=0;
                   10248:     my $unknown_count=0;
1.414     www      10249: # Match answers with usernames
                   10250: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10251:     foreach my $id (keys(%responses)) {
1.410     www      10252:        if ($correct_ids{$id}) {
1.414     www      10253:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10254:           $correct_count++;
1.410     www      10255:        } elsif ($clicker_ids{$id}) {
1.437     www      10256:           if ($clicker_ids{$id}=~/\,/) {
                   10257: # More than one user with the same clicker!
1.632     www      10258:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10259:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10260:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10261:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10262:                            "<select name='multi".$id."'>";
                   10263:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10264:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10265:              }
                   10266:              $result.='</select>';
                   10267:              $unknown_count++;
                   10268:           } else {
                   10269: # Good: found one and only one user with the right clicker
                   10270:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10271:              $student_count++;
                   10272:           }
1.410     www      10273:        } else {
1.632     www      10274:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10275:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10276:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10277:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10278:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10279:                    "\n".&mt("Domain").": ".
                   10280:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      10281:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10282:           $unknown_count++;
1.410     www      10283:        }
1.405     www      10284:     }
1.412     www      10285:     $result.='<hr />'.
                   10286:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10287:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10288:        if ($correct_count==0) {
1.696     bisitz   10289:           $errormsg.="Found no correct answers for grading!";
1.412     www      10290:        } elsif ($correct_count>1) {
1.414     www      10291:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10292:        }
                   10293:     }
1.428     www      10294:     if ($number<1) {
                   10295:        $errormsg.="Found no questions.";
                   10296:     }
1.412     www      10297:     if ($errormsg) {
                   10298:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10299:     } else {
                   10300:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10301:     }
1.632     www      10302:     $result.='</form></td>'.
                   10303:              &Apache::loncommon::end_data_table_row().
                   10304:              &Apache::loncommon::end_data_table();
1.614     www      10305:     return $result;
1.400     www      10306: }
                   10307: 
1.405     www      10308: sub iclicker_eval {
1.406     www      10309:     my ($questiontitles,$responses)=@_;
1.405     www      10310:     my $number=0;
                   10311:     my $errormsg='';
                   10312:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10313:         my %components=&Apache::loncommon::record_sep($line);
                   10314:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10315: 	if ($entries[0] eq 'Question') {
                   10316: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10317: 		$$questiontitles[$number]=$entries[$i];
                   10318: 		$number++;
                   10319: 	    }
                   10320: 	}
                   10321: 	if ($entries[0]=~/^\#/) {
                   10322: 	    my $id=$entries[0];
                   10323: 	    my @idresponses;
                   10324: 	    $id=~s/^[\#0]+//;
                   10325: 	    for (my $i=0;$i<$number;$i++) {
                   10326: 		my $idx=3+$i*6;
1.644     www      10327:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10328: 		push(@idresponses,$entries[$idx]);
                   10329: 	    }
                   10330: 	    $$responses{$id}=join(',',@idresponses);
                   10331: 	}
1.405     www      10332:     }
                   10333:     return ($errormsg,$number);
                   10334: }
                   10335: 
1.419     www      10336: sub interwrite_eval {
                   10337:     my ($questiontitles,$responses)=@_;
                   10338:     my $number=0;
                   10339:     my $errormsg='';
1.420     www      10340:     my $skipline=1;
                   10341:     my $questionnumber=0;
                   10342:     my %idresponses=();
1.419     www      10343:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10344:         my %components=&Apache::loncommon::record_sep($line);
                   10345:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10346:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10347:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10348:         next if $skipline;
                   10349:         if ($entries[0]!=$questionnumber) {
                   10350:            $questionnumber=$entries[0];
                   10351:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10352:            $number++;
1.419     www      10353:         }
1.420     www      10354:         my $id=$entries[4];
                   10355:         $id=~s/^[\#0]+//;
1.421     www      10356:         $id=~s/^v\d*\://i;
                   10357:         $id=~s/[\-\:]//g;
1.420     www      10358:         $idresponses{$id}[$number]=$entries[6];
                   10359:     }
1.524     raeburn  10360:     foreach my $id (keys(%idresponses)) {
1.420     www      10361:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10362:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10363:     }
                   10364:     return ($errormsg,$number);
                   10365: }
                   10366: 
1.666     www      10367: sub turning_eval {
                   10368:     my ($questiontitles,$responses)=@_;
                   10369:     my $number=0;
                   10370:     my $errormsg='';
                   10371:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10372:         my %components=&Apache::loncommon::record_sep($line);
                   10373:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10374:         if ($#entries>$number) { $number=$#entries; }
                   10375:         my $id=$entries[0];
                   10376:         my @idresponses;
                   10377:         $id=~s/^[\#0]+//;
                   10378:         unless ($id) { next; }
                   10379:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10380:             $entries[$idx]=~s/\,/\;/g;
                   10381:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10382:             push(@idresponses,$entries[$idx]);
                   10383:         }
                   10384:         $$responses{$id}=join(',',@idresponses);
                   10385:     }
                   10386:     for (my $i=1; $i<=$number; $i++) {
                   10387:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10388:     }
                   10389:     return ($errormsg,$number);
                   10390: }
                   10391: 
                   10392: 
1.414     www      10393: sub assign_clicker_grades {
1.608     www      10394:     my ($r,$symb)=@_;
1.414     www      10395:     if (!$symb) {return '';}
1.416     www      10396: # See which part we are saving to
1.582     raeburn  10397:     my $res_error;
                   10398:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10399:     if ($res_error) {
                   10400:         return &navmap_errormsg();
                   10401:     }
1.416     www      10402: # FIXME: This should probably look for the first handgradeable part
                   10403:     my $part=$$partlist[0];
                   10404: # Start screen output
1.632     www      10405:     my $result=&Apache::loncommon::start_data_table().
                   10406:              &Apache::loncommon::start_data_table_header_row().
                   10407:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10408:              &Apache::loncommon::end_data_table_header_row().
                   10409:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10410: # Get correct result
                   10411: # FIXME: Possibly need delimiter other than ":"
                   10412:     my @correct=();
1.415     www      10413:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10414:     my $number=$env{'form.number'};
                   10415:     if ($gradingmechanism ne 'attendance') {
1.414     www      10416:        foreach my $key (keys(%env)) {
                   10417:           if ($key=~/^form\.correct\:/) {
                   10418:              my @input=split(/\,/,$env{$key});
                   10419:              for (my $i=0;$i<=$#input;$i++) {
                   10420:                  if (($correct[$i]) && ($input[$i]) &&
                   10421:                      ($correct[$i] ne $input[$i])) {
                   10422:                     $result.='<br /><span class="LC_warning">'.
                   10423:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10424:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10425:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10426:                     $correct[$i]=$input[$i];
                   10427:                  }
                   10428:              }
                   10429:           }
                   10430:        }
1.415     www      10431:        for (my $i=0;$i<$number;$i++) {
1.644     www      10432:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10433:              $result.='<br /><span class="LC_error">'.
                   10434:                       &mt('No correct result given for question "[_1]"!',
                   10435:                           $env{'form.question:'.$i}).'</span>';
                   10436:           }
                   10437:        }
1.644     www      10438:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10439:     }
                   10440: # Start grading
1.415     www      10441:     my $pcorrect=$env{'form.pcorrect'};
                   10442:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10443:     my $storecount=0;
1.632     www      10444:     my %users=();
1.415     www      10445:     foreach my $key (keys(%env)) {
1.420     www      10446:        my $user='';
1.415     www      10447:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10448:           $user=$1;
                   10449:        }
                   10450:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10451:           my $id=$1;
                   10452:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10453:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10454:           } elsif ($env{'form.multi'.$id}) {
                   10455:              $user=$env{'form.multi'.$id};
1.420     www      10456:           }
                   10457:        }
1.632     www      10458:        if ($user) {
                   10459:           if ($users{$user}) {
                   10460:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10461:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10462:                       '</span><br />';
                   10463:           }
                   10464:           $users{$user}=1; 
1.415     www      10465:           my @answer=split(/\,/,$env{$key});
                   10466:           my $sum=0;
1.522     www      10467:           my $realnumber=$number;
1.415     www      10468:           for (my $i=0;$i<$number;$i++) {
1.576     www      10469:              if  ($correct[$i] eq '-') {
                   10470:                 $realnumber--;
1.644     www      10471:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10472:                 if ($gradingmechanism eq 'attendance') {
                   10473:                    $sum+=$pcorrect;
1.576     www      10474:                 } elsif ($correct[$i] eq '*') {
1.522     www      10475:                    $sum+=$pcorrect;
1.415     www      10476:                 } else {
1.644     www      10477: # We actually grade if correct or not
                   10478:                    my $increment=$pincorrect;
                   10479: # Special case: numerical answer "0"
                   10480:                    if ($correct[$i] eq '0') {
                   10481:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10482:                          $increment=$pcorrect;
                   10483:                       }
                   10484: # General numerical answer, both evaluate to something non-zero
                   10485:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10486:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10487:                          $increment=$pcorrect;
                   10488:                       }
                   10489: # Must be just alphanumeric
                   10490:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10491:                       $increment=$pcorrect;
1.415     www      10492:                    }
1.644     www      10493:                    $sum+=$increment;
1.415     www      10494:                 }
                   10495:              }
                   10496:           }
1.522     www      10497:           my $ave=$sum/(100*$realnumber);
1.416     www      10498: # Store
                   10499:           my ($username,$domain)=split(/\:/,$user);
                   10500:           my %grades=();
                   10501:           $grades{"resource.$part.solved"}='correct_by_override';
                   10502:           $grades{"resource.$part.awarded"}=$ave;
                   10503:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10504:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10505:                                                  $env{'request.course.id'},
                   10506:                                                  $domain,$username);
                   10507:           if ($returncode ne 'ok') {
                   10508:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10509:           } else {
                   10510:              $storecount++;
                   10511:           }
1.415     www      10512:        }
                   10513:     }
                   10514: # We are done
1.549     hauer    10515:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10516:              '</td>'.
                   10517:              &Apache::loncommon::end_data_table_row().
                   10518:              &Apache::loncommon::end_data_table();
1.614     www      10519:     return $result;
1.414     www      10520: }
                   10521: 
1.582     raeburn  10522: sub navmap_errormsg {
                   10523:     return '<div class="LC_error">'.
                   10524:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10525:            &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  10526:            '</div>';
                   10527: }
1.607     droeschl 10528: 
1.609     www      10529: sub startpage {
1.671     raeburn  10530:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10531:     if ($nomenu) {
                   10532:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10533:     } else {
                   10534:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10535:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10536:                                                  {'bread_crumbs' => $crumbs}));
                   10537:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10538:     }
1.613     www      10539:     unless ($nodisplayflag) {
1.671     raeburn  10540:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10541:     }
1.607     droeschl 10542: }
1.582     raeburn  10543: 
1.622     www      10544: sub select_problem {
                   10545:     my ($r)=@_;
1.632     www      10546:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.745     raeburn  10547:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
1.622     www      10548:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10549:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10550: }
                   10551: 
1.1       albertel 10552: sub handler {
1.41      ng       10553:     my $request=$_[0];
1.434     albertel 10554:     &reset_caches();
1.646     raeburn  10555:     if ($request->header_only) {
                   10556:         &Apache::loncommon::content_type($request,'text/html');
                   10557:         $request->send_http_header;
                   10558:         return OK;
                   10559:     }
                   10560:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10561: 
1.664     raeburn  10562: # see what command we need to execute
                   10563: 
                   10564:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10565:     my $command=$commands[0];
                   10566: 
1.646     raeburn  10567:     &init_perm();
                   10568:     if (!$env{'request.course.id'}) {
1.664     raeburn  10569:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10570:                 ($command =~ /^scantronupload/)) {
                   10571:             # Not in a course.
                   10572:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10573:             return HTTP_NOT_ACCEPTABLE;
                   10574:         }
1.646     raeburn  10575:     } elsif (!%perm) {
                   10576:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10577:         return OK;
1.41      ng       10578:     }
1.646     raeburn  10579:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10580:     $request->send_http_header;
1.646     raeburn  10581: 
1.160     albertel 10582:     if ($#commands > 0) {
                   10583: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10584:     }
1.608     www      10585: 
                   10586: # see what the symb is
                   10587: 
                   10588:     my $symb=$env{'form.symb'};
                   10589:     unless ($symb) {
                   10590:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10591:        $symb=&Apache::lonnet::symbread($url);
                   10592:     }
1.646     raeburn  10593:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10594: 
1.513     foxr     10595:     $ssi_error = 0;
1.637     www      10596:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10597: #
1.637     www      10598: # Not called from a resource, but inside a course
1.601     www      10599: #    
1.622     www      10600:         &startpage($request,undef,[],1,1);
                   10601:         &select_problem($request);
1.41      ng       10602:     } else {
1.104     albertel 10603: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10604:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10605:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10606:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10607:                     &choose_task_version_form($symb,$env{'form.student'},
                   10608:                                               $env{'form.userdom'});
                   10609:             }
                   10610:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10611:             if ($versionform) {
                   10612:                 $request->print($versionform);
                   10613:             }
                   10614:             $request->print('<br clear="all" />');
1.611     www      10615: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10616:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10617:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10618:                 &choose_task_version_form($symb,$env{'form.student'},
                   10619:                                           $env{'form.userdom'},
                   10620:                                           $env{'form.inhibitmenu'});
                   10621:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10622:             if ($versionform) {
                   10623:                 $request->print($versionform);
                   10624:             }
                   10625:             $request->print('<br clear="all" />');
                   10626:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10627: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10628:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10629:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10630: 	    &pickStudentPage($request,$symb);
1.103     albertel 10631: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10632:             &startpage($request,$symb,
                   10633:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10634:                                        {href=>'',text=>'Select student'},
                   10635:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10636: 	    &displayPage($request,$symb);
1.104     albertel 10637: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10638:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10639:                                        {href=>'',text=>'Select student'},
                   10640:                                        {href=>'',text=>'Grade student'},
                   10641:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10642: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10643: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10644:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10645:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10646: 	    &processGroup($request,$symb);
1.104     albertel 10647: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10648:             &startpage($request,$symb);
                   10649: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10650: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10651:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10652: 	    $request->print(&submit_options($request,$symb));
1.598     www      10653:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10654:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10655:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10656:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10657:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10658:             $request->print(&submit_options_table($request,$symb));
1.598     www      10659:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10660:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10661:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10662: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10663:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10664: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10665: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10666:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10667:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10668: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10669: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10670:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10671:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10672:                                                                              text=>"Modify grades"},
                   10673:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10674: 	    $request->print(&editgrades($request,$symb));
1.602     www      10675:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10676:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10677:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10678: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10679:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10680:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10681: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10682:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10683:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10684:             $request->print(&process_clicker($request,$symb));
1.400     www      10685:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10686:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10687:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10688:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10689:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10690:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10691:                                        {href=>'', text=>'Process clicker file'},
                   10692:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10693:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10694: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10695:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10696: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10697: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10698:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10699: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10700: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10701:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10702: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10703: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10704: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10705:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10706: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10707: 	    } else {
1.257     albertel 10708: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10709: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10710: 		} else {
1.257     albertel 10711: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10712: 		}
1.627     www      10713:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10714: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10715: 	    }
1.246     albertel 10716: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10717:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10718: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10719: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10720:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10721: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10722:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10723:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10724:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10725: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10726:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10727: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10728: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10729:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10730: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10731:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10732:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10733: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10734:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10735:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10736:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10737:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10738: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10739:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10740:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10741:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10742: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10743:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10744:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10745:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10746:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10747:             $request->print(&checkscantron_results($request,$symb));
                   10748:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10749:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10750:             $request->print(&submit_options_download($request,$symb));
                   10751:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10752:             &startpage($request,$symb,
                   10753:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10754:     {href=>'', text=>'Download submissions'}]);
                   10755:             &submit_download_link($request,$symb);
1.106     albertel 10756: 	} elsif ($command) {
1.620     www      10757:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10758: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10759: 	}
1.2       albertel 10760:     }
1.513     foxr     10761:     if ($ssi_error) {
                   10762: 	&ssi_print_error($request);
                   10763:     }
1.671     raeburn  10764:     if ($env{'form.inhibitmenu'}) {
                   10765:         $request->print(&Apache::loncommon::end_page());
                   10766:     } else {
                   10767:         &Apache::lonquickgrades::endGradeScreen($request);
                   10768:     }
1.434     albertel 10769:     &reset_caches();
1.646     raeburn  10770:     return OK;
1.44      ng       10771: }
                   10772: 
1.1       albertel 10773: 1;
                   10774: 
1.13      albertel 10775: __END__;
1.531     jms      10776: 
                   10777: 
                   10778: =head1 NAME
                   10779: 
                   10780: Apache::grades
                   10781: 
                   10782: =head1 SYNOPSIS
                   10783: 
                   10784: Handles the viewing of grades.
                   10785: 
                   10786: This is part of the LearningOnline Network with CAPA project
                   10787: described at http://www.lon-capa.org.
                   10788: 
                   10789: =head1 OVERVIEW
                   10790: 
                   10791: Do an ssi with retries:
1.715     bisitz   10792: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10793: 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
                   10794: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10795: 
                   10796: At least the logic that drives this has been pulled out into loncommon.
                   10797: 
                   10798: 
                   10799: 
                   10800: ssi_with_retries - Does the server side include of a resource.
                   10801:                      if the ssi call returns an error we'll retry it up to
                   10802:                      the number of times requested by the caller.
1.715     bisitz   10803:                      If we still have a problem, no text is appended to the
1.531     jms      10804:                      output and we set some global variables.
                   10805:                      to indicate to the caller an SSI error occurred.  
                   10806:                      All of this is supposed to deal with the issues described
1.715     bisitz   10807:                      in LON-CAPA BZ 5631 see:
1.531     jms      10808:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10809:                      by informing the user that this happened.
                   10810: 
                   10811: Parameters:
                   10812:   resource   - The resource to include.  This is passed directly, without
                   10813:                interpretation to lonnet::ssi.
                   10814:   form       - The form hash parameters that guide the interpretation of the resource
                   10815:                
                   10816:   retries    - Number of retries allowed before giving up completely.
                   10817: Returns:
                   10818:   On success, returns the rendered resource identified by the resource parameter.
                   10819: Side Effects:
                   10820:   The following global variables can be set:
                   10821:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10822:                               It is up to the caller to initialize this to false
                   10823:                               if desired.
                   10824:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10825:                               of the resource that could not be rendered by the ssi
                   10826:                               call.
                   10827:    ssi_error_message   - The error string fetched from the ssi response
                   10828:                               in the event of an error.
                   10829: 
                   10830: 
                   10831: =head1 HANDLER SUBROUTINE
                   10832: 
                   10833: ssi_with_retries()
                   10834: 
                   10835: =head1 SUBROUTINES
                   10836: 
                   10837: =over
                   10838: 
1.671     raeburn  10839: =head1 Routines to display previous version of a Task for a specific student
                   10840: 
                   10841: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10842: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10843: requires a proctor to check-in the student, a new version of the Task will
                   10844: be created when the student is checked in to the new opportunity.
                   10845: 
                   10846: If a particular student has tried two or more versions of a particular task,
                   10847: the submission screen provides a user with vgr privileges (e.g., a Course
                   10848: Coordinator) the ability to display a previous version worked on by the
                   10849: student.  By default, the current version is displayed. If a previous version
                   10850: has been selected for display, submission data are only shown that pertain
                   10851: to that particular version, and the interface to submit grades is not shown.
                   10852: 
                   10853: =over 4
                   10854: 
                   10855: =item show_previous_task_version()
                   10856: 
                   10857: Displays a specified version of a student's Task, as the student sees it.
                   10858: 
                   10859: Inputs: 2
                   10860:         request - request object
                   10861:         symb    - unique symb for current instance of resource
                   10862: 
                   10863: Output: None.
                   10864: 
                   10865: Side Effects: calls &show_problem() to print version of Task, with
                   10866:               version contained in form item: $env{'form.previousversion'}
                   10867: 
                   10868: =item choose_task_version_form()
                   10869: 
                   10870: Displays a web form used to select which version of a student's view of a
                   10871: Task should be displayed.  Either launches a pop-up window, or replaces
                   10872: content in existing pop-up, or replaces page in main window.
                   10873: 
                   10874: Inputs: 4
                   10875:         symb    - unique symb for current instance of resource
                   10876:         uname   - username of student
                   10877:         udom    - domain of student
                   10878:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10879:                   breadcrumbs etc., are displayed
                   10880: 
                   10881: Output: 4
                   10882:         current   - student's current version
                   10883:         displayed - student's version being displayed
                   10884:         result    - scalar containing HTML for web form used to switch to
                   10885:                     a different version (or a link to close window, if pop-up).
                   10886:         js        - javascript for processing selection in versions web form
                   10887: 
                   10888: Side Effects: None.
                   10889: 
                   10890: =item previous_display_javascript()
                   10891: 
                   10892: Inputs: 2
                   10893:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10894:                   breadcrumbs etc., are displayed.
                   10895:         current - student's current version number.
                   10896: 
                   10897: Output: 1
                   10898:         js      - javascript for processing selection in versions web form.
                   10899: 
                   10900: Side Effects: None.
                   10901: 
                   10902: =back
                   10903: 
                   10904: =head1 Routines to process bubblesheet data.
                   10905: 
                   10906: =over 4
                   10907: 
1.531     jms      10908: =item scantron_get_correction() : 
                   10909: 
                   10910:    Builds the interface screen to interact with the operator to fix a
                   10911:    specific error condition in a specific scanline
                   10912: 
                   10913:  Arguments:
                   10914:     $r           - Apache request object
                   10915:     $i           - number of the current scanline
                   10916:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10917:     $scan_config - hash ref as returned from &get_scantron_config()
                   10918:     $line        - full contents of the current scanline
                   10919:     $error       - error condition, valid values are
                   10920:                    'incorrectCODE', 'duplicateCODE',
                   10921:                    'doublebubble', 'missingbubble',
                   10922:                    'duplicateID', 'incorrectID'
                   10923:     $arg         - extra information needed
                   10924:        For errors:
                   10925:          - duplicateID   - paper number that this studentID was seen before on
                   10926:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10927:                            seen on before
                   10928:          - incorrectCODE - current incorrect CODE 
                   10929:          - doublebubble  - array ref of the bubble lines that have double
                   10930:                            bubble errors
                   10931:          - missingbubble - array ref of the bubble lines that have missing
                   10932:                            bubble errors
                   10933: 
1.691     raeburn  10934:    $randomorder - True if exam folder has randomorder set
                   10935:    $randompick  - True if exam folder has randompick set
                   10936:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10937:                      for current line to question number used for same question
                   10938:                      in "Master Seqence" (as seen by Course Coordinator).
                   10939:    $startline   - Reference to hash where key is question number (0 is first)
                   10940:                   and value is number of first bubble line for current student
                   10941:                   or code-based randompick and/or randomorder.
                   10942: 
                   10943: 
                   10944: 
1.531     jms      10945: =item  scantron_get_maxbubble() : 
                   10946: 
1.582     raeburn  10947:    Arguments:
                   10948:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10949:                       failure to retrieve a navmap object.
                   10950:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10951:        calling routine should trap the error condition and display the warning
                   10952:        found in &navmap_errormsg().
                   10953: 
1.649     raeburn  10954:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10955: 
1.531     jms      10956:    Returns the maximum number of bubble lines that are expected to
                   10957:    occur. Does this by walking the selected sequence rendering the
                   10958:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10959:    for what the current value of the problem counter is.
                   10960: 
                   10961:    Caches the results to $env{'form.scantron_maxbubble'},
                   10962:    $env{'form.scantron.bubble_lines.n'}, 
                   10963:    $env{'form.scantron.first_bubble_line.n'} and
                   10964:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10965:    which are the total number of bubble lines, the number of bubble
1.531     jms      10966:    lines for response n and number of the first bubble line for response n,
                   10967:    and a comma separated list of numbers of bubble lines for sub-questions
                   10968:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10969: 
                   10970: 
                   10971: =item  scantron_validate_missingbubbles() : 
                   10972: 
                   10973:    Validates all scanlines in the selected file to not have any
                   10974:     answers that don't have bubbles that have not been verified
                   10975:     to be bubble free.
                   10976: 
                   10977: =item  scantron_process_students() : 
                   10978: 
1.659     raeburn  10979:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10980: 
                   10981:    The parsed scanline hash is added to %env 
                   10982: 
                   10983:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10984:    foreach resource , with the form data of
                   10985: 
                   10986: 	'submitted'     =>'scantron' 
                   10987: 	'grade_target'  =>'grade',
                   10988: 	'grade_username'=> username of student
                   10989: 	'grade_domain'  => domain of student
                   10990: 	'grade_courseid'=> of course
                   10991: 	'grade_symb'    => symb of resource to grade
                   10992: 
                   10993:     This triggers a grading pass. The problem grading code takes care
                   10994:     of converting the bubbled letter information (now in %env) into a
                   10995:     valid submission.
                   10996: 
                   10997: =item  scantron_upload_scantron_data() :
                   10998: 
1.659     raeburn  10999:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11000: 
                   11001: =item  scantron_upload_scantron_data_save() : 
                   11002: 
                   11003:    Adds a provided bubble information data file to the course if user
                   11004:    has the correct privileges to do so. 
                   11005: 
                   11006: =item  valid_file() :
                   11007: 
                   11008:    Validates that the requested bubble data file exists in the course.
                   11009: 
                   11010: =item  scantron_download_scantron_data() : 
                   11011: 
                   11012:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11013:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11014:    course.
                   11015: 
                   11016: =item  scantron_validate_ID() : 
                   11017: 
                   11018:    Validates all scanlines in the selected file to not have any
1.556     weissno  11019:    invalid or underspecified student/employee IDs
1.531     jms      11020: 
1.582     raeburn  11021: =item navmap_errormsg() :
                   11022: 
                   11023:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11024:    Should be called whenever the request to instantiate a navmap object fails.
                   11025: 
                   11026: =back
1.582     raeburn  11027: 
1.531     jms      11028: =back
                   11029: 
                   11030: =cut

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