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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.741   ! raeburn     4: # $Id: grades.pm,v 1.740 2017/05/19 19:25:05 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.741   ! raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.741   ! raeburn   304:             if ($scancode) {
        !           305:                 if (ref($add_to_form) eq 'HASH') {
        !           306:                     $add_to_form->{'code_for_randomlist'} = $scancode;
        !           307:                 } else {
        !           308:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
        !           309:                 }
        !           310:             }
1.649     raeburn   311:             my $analyze = 
                    312:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    313:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   314:             if (ref($analyze) eq 'HASH') {
                    315:                 %analysis = %{$analyze};
                    316:             }
                    317:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    318:                 foreach my $part (@{$analysis{'parts'}}) {
                    319:                     my ($id,$respid) = split(/\./,$part);
                    320:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    321:                         push(@parts,$part);
                    322:                     }
                    323:                 }
                    324:             }
                    325:         }
                    326:         return (\%analysis,\@parts);
                    327:     }
                    328: 
1.148     albertel  329: }
1.434     albertel  330: 
1.118     ng        331: #--- Clean response type for display
1.335     albertel  332: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    333: #        response types only.
1.118     ng        334: sub cleanRecord {
1.336     albertel  335:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   336: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  337:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  338:     if ($response =~ /^(option|rank)$/) {
                    339: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     340:         my @answer = %answer;
                    341:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  342: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    343: 	my ($toprow,$bottomrow);
                    344: 	foreach my $foil (@$order) {
                    345: 	    if ($grading{$foil} == 1) {
                    346: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    347: 	    } else {
                    348: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    349: 	    }
1.398     albertel  350: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  351: 	}
                    352: 	return '<blockquote><table border="1">'.
1.466     albertel  353: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    354: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   355: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  356:     } elsif ($response eq 'match') {
                    357: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     358:         my @answer = %answer;
                    359:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  360: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    361: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    362: 	my ($toprow,$middlerow,$bottomrow);
                    363: 	foreach my $foil (@$order) {
                    364: 	    my $item=shift(@items);
                    365: 	    if ($grading{$foil} == 1) {
                    366: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  367: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  368: 	    } else {
                    369: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  370: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  371: 	    }
1.398     albertel  372: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        373: 	}
1.126     ng        374: 	return '<blockquote><table border="1">'.
1.466     albertel  375: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    376: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  377: 	    $middlerow.'</tr>'.
1.466     albertel  378: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   379: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  380:     } elsif ($response eq 'radiobutton') {
                    381: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     382:         my @answer = %answer;
                    383:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  384: 	my ($toprow,$bottomrow);
1.434     albertel  385: 	my $correct = 
1.640     raeburn   386: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  387: 	foreach my $foil (@$order) {
1.148     albertel  388: 	    if (exists($answer{$foil})) {
1.434     albertel  389: 		if ($foil eq $correct) {
1.466     albertel  390: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  391: 		} else {
1.466     albertel  392: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  393: 		}
                    394: 	    } else {
1.466     albertel  395: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  396: 	    }
1.398     albertel  397: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  398: 	}
                    399: 	return '<blockquote><table border="1">'.
1.466     albertel  400: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    401: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   402: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  403:     } elsif ($response eq 'essay') {
1.257     albertel  404: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        405: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  406: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    407: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        408: 
1.257     albertel  409: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    410: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    411: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    412: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    413: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    414: 	    $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        415: 	}
1.730     kruse     416: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     417: 
1.268     albertel  418:     } elsif ( $response eq 'organic') {
1.721     bisitz    419:         my $result=&mt('Smile representation: [_1]',
                    420:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  421: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    422: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    423: 	return $result;
1.335     albertel  424:     } elsif ( $response eq 'Task') {
                    425: 	if ( $answer eq 'SUBMITTED') {
                    426: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  427: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  428: 	    return $result;
                    429: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    430: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    431: 			       keys(%{$record}));
                    432: 	    return join('<br />',($version,@matches));
                    433: 			       
                    434: 			       
                    435: 	} else {
                    436: 	    my $result =
                    437: 		'<p>'
                    438: 		.&mt('Overall result: [_1]',
                    439: 		     $record->{$version."resource.$respid.$partid.status"})
                    440: 		.'</p>';
                    441: 	    
                    442: 	    $result .= '<ul>';
                    443: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    444: 			     keys(%{$record}));
                    445: 	    foreach my $grade (sort(@grade)) {
                    446: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    447: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    448: 				     $dim, $record->{$grade}).
                    449: 			  '</li>';
                    450: 	    }
                    451: 	    $result.='</ul>';
                    452: 	    return $result;
                    453: 	}
1.716     bisitz    454:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    455:         # Respect multiple input fields, see Bug #5409
1.440     albertel  456: 	$answer = 
                    457: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    458: 							      $answer);
1.720     kruse     459: 	return $answer;
1.122     ng        460:     }
1.720     kruse     461:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        462: }
                    463: 
                    464: #-- A couple of common js functions
                    465: sub commonJSfunctions {
                    466:     my $request = shift;
1.597     wenzelju  467:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        468:     function radioSelection(radioButton) {
                    469: 	var selection=null;
                    470: 	if (radioButton.length > 1) {
                    471: 	    for (var i=0; i<radioButton.length; i++) {
                    472: 		if (radioButton[i].checked) {
                    473: 		    return radioButton[i].value;
                    474: 		}
                    475: 	    }
                    476: 	} else {
                    477: 	    if (radioButton.checked) return radioButton.value;
                    478: 	}
                    479: 	return selection;
                    480:     }
                    481: 
                    482:     function pullDownSelection(selectOne) {
                    483: 	var selection="";
                    484: 	if (selectOne.length > 1) {
                    485: 	    for (var i=0; i<selectOne.length; i++) {
                    486: 		if (selectOne[i].selected) {
                    487: 		    return selectOne[i].value;
                    488: 		}
                    489: 	    }
                    490: 	} else {
1.138     albertel  491:             // only one value it must be the selected one
                    492: 	    return selectOne.value;
1.118     ng        493: 	}
                    494:     }
                    495: COMMONJSFUNCTIONS
                    496: }
                    497: 
1.44      ng        498: #--- Dumps the class list with usernames,list of sections,
                    499: #--- section, ids and fullnames for each user.
                    500: sub getclasslist {
1.449     banghart  501:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  502:     my @getsec;
1.450     banghart  503:     my @getgroup;
1.442     banghart  504:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  505:     if (!ref($getsec)) {
                    506: 	if ($getsec ne '' && $getsec ne 'all') {
                    507: 	    @getsec=($getsec);
                    508: 	}
                    509:     } else {
                    510: 	@getsec=@{$getsec};
                    511:     }
                    512:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  513:     if (!ref($getgroup)) {
                    514: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    515: 	    @getgroup=($getgroup);
                    516: 	}
                    517:     } else {
                    518: 	@getgroup=@{$getgroup};
                    519:     }
                    520:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  521: 
1.449     banghart  522:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  523:     # Bail out if we were unable to get the classlist
1.56      matthew   524:     return if (! defined($classlist));
1.449     banghart  525:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   526:     #
                    527:     my %sections;
                    528:     my %fullnames;
1.205     matthew   529:     foreach my $student (keys(%$classlist)) {
                    530:         my $end      = 
                    531:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    532:         my $start    = 
                    533:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    534:         my $id       = 
                    535:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    536:         my $section  = 
                    537:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    538:         my $fullname = 
                    539:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    540:         my $status   = 
                    541:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  542:         my $group   = 
                    543:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        544: 	# filter students according to status selected
1.442     banghart  545: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    546: 	    if (!($stu_status =~ $status)) {
1.450     banghart  547: 		delete($classlist->{$student});
1.76      ng        548: 		next;
                    549: 	    }
                    550: 	}
1.450     banghart  551: 	# filter students according to groups selected
1.453     banghart  552: 	my @stu_groups = split(/,/,$group);
1.450     banghart  553: 	if (@getgroup) {
                    554: 	    my $exclude = 1;
1.454     banghart  555: 	    foreach my $grp (@getgroup) {
                    556: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  557: 	            if ($stu_group eq $grp) {
                    558: 	                $exclude = 0;
                    559:     	            } 
1.450     banghart  560: 	        }
1.453     banghart  561:     	        if (($grp eq 'none') && !$group) {
                    562:         	        $exclude = 0;
                    563:         	}
1.450     banghart  564: 	    }
                    565: 	    if ($exclude) {
                    566: 	        delete($classlist->{$student});
                    567: 	    }
                    568: 	}
1.205     matthew   569: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  570: 	if (&canview($section)) {
1.291     albertel  571: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  572: 		$sections{$section}++;
1.450     banghart  573: 		if ($classlist->{$student}) {
                    574: 		    $fullnames{$student}=$fullname;
                    575: 		}
1.103     albertel  576: 	    } else {
1.205     matthew   577: 		delete($classlist->{$student});
1.103     albertel  578: 	    }
                    579: 	} else {
1.205     matthew   580: 	    delete($classlist->{$student});
1.103     albertel  581: 	}
1.44      ng        582:     }
                    583:     my %seen = ();
1.56      matthew   584:     my @sections = sort(keys(%sections));
                    585:     return ($classlist,\@sections,\%fullnames);
1.44      ng        586: }
                    587: 
1.103     albertel  588: sub canmodify {
                    589:     my ($sec)=@_;
                    590:     if ($perm{'mgr'}) {
                    591: 	if (!defined($perm{'mgr_section'})) {
                    592: 	    # can modify whole class
                    593: 	    return 1;
                    594: 	} else {
                    595: 	    if ($sec eq $perm{'mgr_section'}) {
                    596: 		#can modify the requested section
                    597: 		return 1;
                    598: 	    } else {
                    599: 		# can't modify the request section
                    600: 		return 0;
                    601: 	    }
                    602: 	}
                    603:     }
                    604:     #can't modify
                    605:     return 0;
                    606: }
                    607: 
                    608: sub canview {
                    609:     my ($sec)=@_;
                    610:     if ($perm{'vgr'}) {
                    611: 	if (!defined($perm{'vgr_section'})) {
                    612: 	    # can modify whole class
                    613: 	    return 1;
                    614: 	} else {
                    615: 	    if ($sec eq $perm{'vgr_section'}) {
                    616: 		#can modify the requested section
                    617: 		return 1;
                    618: 	    } else {
                    619: 		# can't modify the request section
                    620: 		return 0;
                    621: 	    }
                    622: 	}
                    623:     }
                    624:     #can't modify
                    625:     return 0;
                    626: }
                    627: 
1.44      ng        628: #--- Retrieve the grade status of a student for all the parts
                    629: sub student_gradeStatus {
1.324     albertel  630:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  631:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        632:     my %partstatus = ();
                    633:     foreach (@$partlist) {
1.128     ng        634: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        635: 	$status              = 'nothing' if ($status eq '');
                    636: 	$partstatus{$_}      = $status;
                    637: 	my $subkey           = "resource.$_.submitted_by";
                    638: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    639:     }
                    640:     return %partstatus;
                    641: }
                    642: 
1.45      ng        643: # hidden form and javascript that calls the form
                    644: # Use by verifyscript and viewgrades
                    645: # Shows a student's view of problem and submission
                    646: sub jscriptNform {
1.324     albertel  647:     my ($symb) = @_;
1.442     banghart  648:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  649:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        650: 	'    function viewOneStudent(user,domain) {'."\n".
                    651: 	'	document.onestudent.student.value = user;'."\n".
                    652: 	'	document.onestudent.userdom.value = domain;'."\n".
                    653: 	'	document.onestudent.submit();'."\n".
                    654: 	'    }'."\n".
1.597     wenzelju  655: 	"\n");
1.45      ng        656:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  657: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  658: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        659: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    660: 	'<input type="hidden" name="student" value="" />'."\n".
                    661: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    662: 	'</form>'."\n";
                    663:     return $jscript;
                    664: }
1.39      ng        665: 
1.447     foxr      666: 
                    667: 
1.315     bowersj2  668: # Given the score (as a number [0-1] and the weight) what is the final
                    669: # point value? This function will round to the nearest tenth, third,
                    670: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  671: sub compute_points {
1.315     bowersj2  672:     my ($score, $weight) = @_;
                    673:     
                    674:     my $tolerance = .00001;
                    675:     my $points = $score * $weight;
                    676: 
                    677:     # Check for nearness to 1/x.
                    678:     my $check_for_nearness = sub {
                    679:         my ($factor) = @_;
                    680:         my $num = ($points * $factor) + $tolerance;
                    681:         my $floored_num = floor($num);
1.316     albertel  682:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  683:             return $floored_num / $factor;
                    684:         }
                    685:         return $points;
                    686:     };
                    687: 
                    688:     $points = $check_for_nearness->(10);
                    689:     $points = $check_for_nearness->(3);
                    690:     $points = $check_for_nearness->(4);
                    691:     
                    692:     return $points;
                    693: }
                    694: 
1.44      ng        695: #------------------ End of general use routines --------------------
1.87      www       696: 
                    697: #
                    698: # Find most similar essay
                    699: #
                    700: 
                    701: sub most_similar {
1.674     raeburn   702:     my ($uname,$udom,$symb,$uessay)=@_;
                    703: 
                    704:     unless ($symb) { return ''; }
                    705: 
                    706:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       707: 
                    708: # ignore spaces and punctuation
                    709: 
                    710:     $uessay=~s/\W+/ /gs;
                    711: 
1.282     www       712: # ignore empty submissions (occuring when only files are sent)
                    713: 
1.598     www       714:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       715: 
1.87      www       716: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       717:     my $limit=0.6;
1.87      www       718:     my $sname='';
                    719:     my $sdom='';
                    720:     my $scrsid='';
                    721:     my $sessay='';
                    722: # go through all essays ...
1.674     raeburn   723:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  724: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       725: # ... except the same student
1.426     albertel  726:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   727: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  728: 	$tessay=~s/\W+/ /gs;
1.87      www       729: # String similarity gives up if not even limit
1.426     albertel  730: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       731: # Found one
1.426     albertel  732: 	if ($tsimilar>$limit) {
                    733: 	    $limit=$tsimilar;
                    734: 	    $sname=$tname;
                    735: 	    $sdom=$tdom;
                    736: 	    $scrsid=$tcrsid;
1.674     raeburn   737: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  738: 	}
1.87      www       739:     }
1.88      www       740:     if ($limit>0.6) {
1.87      www       741:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    742:     } else {
                    743:        return ('','','','',0);
                    744:     }
                    745: }
                    746: 
1.44      ng        747: #-------------------------------------------------------------------
                    748: 
                    749: #------------------------------------ Receipt Verification Routines
1.45      ng        750: #
1.602     www       751: 
                    752: sub initialverifyreceipt {
1.608     www       753:    my ($request,$symb) = @_;
1.602     www       754:    &commonJSfunctions($request);
1.694     bisitz    755:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       756:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    757:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       758:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    759:         '<input type="hidden" name="command" value="verify" />'.
                    760:         "</form>\n";
1.602     www       761: }
                    762: 
1.44      ng        763: #--- Check whether a receipt number is valid.---
                    764: sub verifyreceipt {
1.608     www       765:     my ($request,$symb)  = @_;
1.44      ng        766: 
1.257     albertel  767:     my $courseid = $env{'request.course.id'};
1.184     www       768:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  769: 	$env{'form.receipt'};
1.44      ng        770:     $receipt     =~ s/[^\-\d]//g;
                    771: 
1.487     albertel  772:     my $title.=
                    773: 	'<h3><span class="LC_info">'.
1.605     www       774: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    775: 	'</span></h3>'."\n";
1.44      ng        776: 
                    777:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   778:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  779:     
                    780:     my $receiptparts=0;
1.390     albertel  781:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    782: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  783:     my $parts=['0'];
1.582     raeburn   784:     if ($receiptparts) {
                    785:         my $res_error; 
                    786:         ($parts)=&response_type($symb,\$res_error);
                    787:         if ($res_error) {
                    788:             return &navmap_errormsg();
                    789:         } 
                    790:     }
1.486     albertel  791:     
                    792:     my $header = 
                    793: 	&Apache::loncommon::start_data_table().
                    794: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  795: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    796: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    797: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  798:     if ($receiptparts) {
1.487     albertel  799: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  800:     }
                    801:     $header.=
                    802: 	&Apache::loncommon::end_data_table_header_row();
                    803: 
1.294     albertel  804:     foreach (sort 
                    805: 	     {
                    806: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    807: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    808: 		 }
                    809: 		 return $a cmp $b;
                    810: 	     } (keys(%$fullname))) {
1.44      ng        811: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  812: 	foreach my $part (@$parts) {
                    813: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  814: 		$contents.=
                    815: 		    &Apache::loncommon::start_data_table_row().
                    816: 		    '<td>&nbsp;'."\n".
1.177     albertel  817: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  818: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  819: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    820: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    821: 		if ($receiptparts) {
                    822: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    823: 		}
1.486     albertel  824: 		$contents.= 
                    825: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  826: 		
                    827: 		$matches++;
                    828: 	    }
1.44      ng        829: 	}
                    830:     }
                    831:     if ($matches == 0) {
1.584     bisitz    832:         $string = $title
                    833:                  .'<p class="LC_warning">'
                    834:                  .&mt('No match found for the above receipt number.')
                    835:                  .'</p>';
1.44      ng        836:     } else {
1.324     albertel  837: 	$string = &jscriptNform($symb).$title.
1.487     albertel  838: 	    '<p>'.
1.584     bisitz    839: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  840: 	    '</p>'.
1.486     albertel  841: 	    $header.
                    842: 	    $contents.
                    843: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        844:     }
1.614     www       845:     return $string;
1.44      ng        846: }
                    847: 
                    848: #--- This is called by a number of programs.
                    849: #--- Called from the Grading Menu - View/Grade an individual student
                    850: #--- Also called directly when one clicks on the subm button 
                    851: #    on the problem page.
1.30      ng        852: sub listStudents {
1.617     www       853:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  854: 
1.257     albertel  855:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    856:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    857:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  858:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       859:     unless ($submitonly) {
                    860:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    861:     }
1.49      albertel  862: 
1.632     www       863:     my $result='';
1.623     www       864:     my $res_error;
                    865:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  866: 
1.736     damieng   867:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   868: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    869: 		'single'   => 'Please select the student before clicking on the Next button.',
                    870: 	     );
1.736     damieng   871:     &js_escape(\%js_lt);
1.597     wenzelju  872:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        873:     function checkSelect(checkBox) {
                    874: 	var ctr=0;
                    875: 	var sense="";
                    876: 	if (checkBox.length > 1) {
                    877: 	    for (var i=0; i<checkBox.length; i++) {
                    878: 		if (checkBox[i].checked) {
                    879: 		    ctr++;
                    880: 		}
                    881: 	    }
1.736     damieng   882: 	    sense = '$js_lt{'multiple'}';
1.110     ng        883: 	} else {
                    884: 	    if (checkBox.checked) {
                    885: 		ctr = 1;
                    886: 	    }
1.736     damieng   887: 	    sense = '$js_lt{'single'}';
1.110     ng        888: 	}
                    889: 	if (ctr == 0) {
1.485     albertel  890: 	    alert(sense);
1.110     ng        891: 	    return false;
                    892: 	}
                    893: 	document.gradesub.submit();
                    894:     }
                    895: 
                    896:     function reLoadList(formname) {
1.112     ng        897: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        898: 	formname.command.value = 'submission';
                    899: 	formname.submit();
                    900:     }
1.45      ng        901: LISTJAVASCRIPT
                    902: 
1.118     ng        903:     &commonJSfunctions($request);
1.41      ng        904:     $request->print($result);
1.39      ng        905: 
1.154     albertel  906:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       907: 	"\n";
1.485     albertel  908: 	
1.561     bisitz    909:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    910:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    911:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    912:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    913:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    914:                   .&Apache::lonhtmlcommon::row_closure();
                    915:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    916:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    917:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    918:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    919:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  920: 
                    921:     my $submission_options;
1.442     banghart  922:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    923:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  924:     $env{'form.Status'} = $saveStatus;
1.485     albertel  925:     $submission_options.=
1.592     bisitz    926:         '<span class="LC_nobreak">'.
1.624     www       927:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     928:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    929:         '<span class="LC_nobreak">'.
                    930:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     931:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    932:         '<span class="LC_nobreak">'.
1.628     www       933:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     934:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    935:         '<span class="LC_nobreak">'.
                    936:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     937:         &mt('all submissions with details').'</label></span>';
                    938:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    939:                   .$submission_options
                    940:                   .&Apache::lonhtmlcommon::row_closure();
                    941: 
                    942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    943:                   .'<select name="increment">'
                    944:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    945:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    946:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    947:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    948:                   .'</select>'
                    949:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  950: 
                    951:     $gradeTable .= 
1.432     banghart  952:         &build_section_inputs().
1.45      ng        953: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  954: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        955: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    956: 
1.618     www       957:     if (exists($env{'form.Status'})) {
1.561     bisitz    958: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        959:     } else {
1.561     bisitz    960:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    961:                       .&Apache::lonhtmlcommon::StatusOptions(
                    962:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    963:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        964:     }
1.112     ng        965: 
1.561     bisitz    966:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    967:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    968:                   .&Apache::lonhtmlcommon::row_closure(1)
                    969:                   .&Apache::lonhtmlcommon::end_pick_box();
                    970: 
                    971:     $gradeTable .= '<p>'
1.618     www       972:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz    973:                   .'<input type="hidden" name="command" value="processGroup" />'
                    974:                   .'</p>';
1.249     albertel  975: 
                    976: # checkall buttons
                    977:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        978:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    979:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    980:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  981:     $gradeTable.=&check_buttons();
1.450     banghart  982:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  983:     $gradeTable.= &Apache::loncommon::start_data_table().
                    984: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        985:     my $loop = 0;
                    986:     while ($loop < 2) {
1.485     albertel  987: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    988: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       989: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  990: 	    foreach my $part (sort(@$partlist)) {
                    991: 		my $display_part=
                    992: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    993: 		$gradeTable.=
                    994: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        995: 	    }
1.301     albertel  996: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  997: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        998: 	}
                    999: 	$loop++;
1.126     ng       1000: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1001:     }
1.474     albertel 1002:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1003: 
1.45      ng       1004:     my $ctr = 0;
1.294     albertel 1005:     foreach my $student (sort 
                   1006: 			 {
                   1007: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1008: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1009: 			     }
                   1010: 			     return $a cmp $b;
                   1011: 			 }
                   1012: 			 (keys(%$fullname))) {
1.41      ng       1013: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1014: 
1.110     ng       1015: 	my %status = ();
1.301     albertel 1016: 
                   1017: 	if ($submitonly eq 'queued') {
                   1018: 	    my %queue_status = 
                   1019: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1020: 							$udom,$uname);
                   1021: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1022: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1023: 	}
                   1024: 
1.618     www      1025: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1026: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1027: 	    my $submitted = 0;
1.164     albertel 1028: 	    my $graded = 0;
1.248     albertel 1029: 	    my $incorrect = 0;
1.110     ng       1030: 	    foreach (keys(%status)) {
1.145     albertel 1031: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1032: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1033: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1034: 		
1.110     ng       1035: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1036: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1037: 		    $submitted = 0;
1.150     albertel 1038: 		    my ($part)=split(/\./,$partid);
1.110     ng       1039: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1040: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1041: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1042: 		}
1.41      ng       1043: 	    }
1.248     albertel 1044: 	    
1.156     albertel 1045: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1046: 				     $submitonly eq 'incorrect' ||
                   1047: 				     $submitonly eq 'graded'));
1.248     albertel 1048: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1049: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1050: 	}
1.34      ng       1051: 
1.45      ng       1052: 	$ctr++;
1.249     albertel 1053: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1054:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1055: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1056: 	    if ($ctr%2 ==1) {
                   1057: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1058: 	    }
1.126     ng       1059: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1060:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1061:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1062: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1063: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1064: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1065: 
1.618     www      1066: 	    if ($submitonly ne 'all') {
1.524     raeburn  1067: 		foreach (sort(keys(%status))) {
1.485     albertel 1068: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1069: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1070: 		}
1.41      ng       1071: 	    }
1.126     ng       1072: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1073: 	    if ($ctr%2 ==0) {
                   1074: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1075: 	    }
1.41      ng       1076: 	}
                   1077:     }
1.110     ng       1078:     if ($ctr%2 ==1) {
1.126     ng       1079: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1080: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1081: 		foreach (@$partlist) {
                   1082: 		    $gradeTable.='<td>&nbsp;</td>';
                   1083: 		}
1.301     albertel 1084: 	    } elsif ($submitonly eq 'queued') {
                   1085: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1086: 	    }
1.474     albertel 1087: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1088:     }
                   1089: 
1.474     albertel 1090:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1091:         '<input type="button" '.
                   1092:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1093:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1094:     if ($ctr == 0) {
1.96      albertel 1095: 	my $num_students=(scalar(keys(%$fullname)));
                   1096: 	if ($num_students eq 0) {
1.485     albertel 1097: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1098: 	} else {
1.171     albertel 1099: 	    my $submissions='submissions';
                   1100: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1101: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1102: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1103: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1104: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1105: 		    $num_students).
                   1106: 		'</span><br />';
1.96      albertel 1107: 	}
1.46      ng       1108:     } elsif ($ctr == 1) {
1.474     albertel 1109: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1110:     }
                   1111:     $request->print($gradeTable);
1.44      ng       1112:     return '';
1.10      ng       1113: }
                   1114: 
1.44      ng       1115: #---- Called from the listStudents routine
1.249     albertel 1116: 
                   1117: sub check_script {
                   1118:     my ($form, $type)=@_;
1.597     wenzelju 1119:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1120:     function checkall() {
                   1121:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1122:             ele = document.forms.'.$form.'.elements[i];
                   1123:             if (ele.name == "'.$type.'") {
                   1124:             document.forms.'.$form.'.elements[i].checked=true;
                   1125:                                        }
                   1126:         }
                   1127:     }
                   1128: 
                   1129:     function checksec() {
                   1130:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1131:             ele = document.forms.'.$form.'.elements[i];
                   1132:            string = document.forms.'.$form.'.chksec.value;
                   1133:            if
                   1134:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1135:               document.forms.'.$form.'.elements[i].checked=true;
                   1136:             }
                   1137:         }
                   1138:     }
                   1139: 
                   1140: 
                   1141:     function uncheckall() {
                   1142:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1143:             ele = document.forms.'.$form.'.elements[i];
                   1144:             if (ele.name == "'.$type.'") {
                   1145:             document.forms.'.$form.'.elements[i].checked=false;
                   1146:                                        }
                   1147:         }
                   1148:     }
                   1149: 
1.597     wenzelju 1150: '."\n");
1.249     albertel 1151:     return $chkallscript;
                   1152: }
                   1153: 
                   1154: sub check_buttons {
1.485     albertel 1155:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1156:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1157:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1158:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1159:     return $buttons;
                   1160: }
                   1161: 
1.44      ng       1162: #     Displays the submissions for one student or a group of students
1.34      ng       1163: sub processGroup {
1.619     www      1164:     my ($request,$symb)  = @_;
1.41      ng       1165:     my $ctr        = 0;
1.155     albertel 1166:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1167:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1168: 
1.396     banghart 1169:     foreach my $student (@stuchecked) {
                   1170: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1171: 	$env{'form.student'}        = $uname;
                   1172: 	$env{'form.userdom'}        = $udom;
                   1173: 	$env{'form.fullname'}       = $fullname;
1.619     www      1174: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1175: 	$ctr++;
                   1176:     }
                   1177:     return '';
1.35      ng       1178: }
1.34      ng       1179: 
1.44      ng       1180: #------------------------------------------------------------------------------------
                   1181: #
                   1182: #-------------------------- Next few routines handles grading by student, essentially
                   1183: #                           handles essay response type problem/part
                   1184: #
                   1185: #--- Javascript to handle the submission page functionality ---
                   1186: sub sub_page_js {
                   1187:     my $request = shift;
1.736     damieng  1188:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1189:     &js_escape(\$alertmsg);
1.597     wenzelju 1190:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1191:     function updateRadio(formname,id,weight) {
1.125     ng       1192: 	var gradeBox = formname["GD_BOX"+id];
                   1193: 	var radioButton = formname["RADVAL"+id];
                   1194: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1195: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1196: 	gradeBox.value = pts;
                   1197: 	var resetbox = false;
                   1198: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1199: 	    alert("$alertmsg"+pts);
1.71      ng       1200: 	    for (var i=0; i<radioButton.length; i++) {
                   1201: 		if (radioButton[i].checked) {
                   1202: 		    gradeBox.value = i;
                   1203: 		    resetbox = true;
                   1204: 		}
                   1205: 	    }
                   1206: 	    if (!resetbox) {
                   1207: 		formtextbox.value = "";
                   1208: 	    }
                   1209: 	    return;
1.44      ng       1210: 	}
1.71      ng       1211: 
                   1212: 	if (pts > weight) {
                   1213: 	    var resp = confirm("You entered a value ("+pts+
                   1214: 			       ") greater than the weight for the part. Accept?");
                   1215: 	    if (resp == false) {
1.125     ng       1216: 		gradeBox.value = oldpts;
1.71      ng       1217: 		return;
                   1218: 	    }
1.44      ng       1219: 	}
1.13      albertel 1220: 
1.71      ng       1221: 	for (var i=0; i<radioButton.length; i++) {
                   1222: 	    radioButton[i].checked=false;
                   1223: 	    if (pts == i && pts != "") {
                   1224: 		radioButton[i].checked=true;
                   1225: 	    }
                   1226: 	}
                   1227: 	updateSelect(formname,id);
1.125     ng       1228: 	formname["stores"+id].value = "0";
1.41      ng       1229:     }
1.5       albertel 1230: 
1.72      ng       1231:     function writeBox(formname,id,pts) {
1.125     ng       1232: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1233: 	if (checkSolved(formname,id) == 'update') {
                   1234: 	    gradeBox.value = pts;
                   1235: 	} else {
1.125     ng       1236: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1237: 	    gradeBox.value = oldpts;
1.125     ng       1238: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1239: 	    for (var i=0; i<radioButton.length; i++) {
                   1240: 		radioButton[i].checked=false;
1.72      ng       1241: 		if (i == oldpts) {
1.71      ng       1242: 		    radioButton[i].checked=true;
                   1243: 		}
                   1244: 	    }
1.41      ng       1245: 	}
1.125     ng       1246: 	formname["stores"+id].value = "0";
1.71      ng       1247: 	updateSelect(formname,id);
                   1248: 	return;
1.41      ng       1249:     }
1.44      ng       1250: 
1.71      ng       1251:     function clearRadBox(formname,id) {
                   1252: 	if (checkSolved(formname,id) == 'noupdate') {
                   1253: 	    updateSelect(formname,id);
                   1254: 	    return;
                   1255: 	}
1.125     ng       1256: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1257: 	for (var i=0; i<gradeSelect.length; i++) {
                   1258: 	    if (gradeSelect[i].selected) {
                   1259: 		var selectx=i;
                   1260: 	    }
                   1261: 	}
1.125     ng       1262: 	var stores = formname["stores"+id];
1.71      ng       1263: 	if (selectx == stores.value) { return };
1.125     ng       1264: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1265: 	gradeBox.value = "";
1.125     ng       1266: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1267: 	for (var i=0; i<radioButton.length; i++) {
                   1268: 	    radioButton[i].checked=false;
                   1269: 	}
                   1270: 	stores.value = selectx;
                   1271:     }
1.5       albertel 1272: 
1.71      ng       1273:     function checkSolved(formname,id) {
1.125     ng       1274: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1275: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1276: 	    if (!reply) {return "noupdate";}
1.120     ng       1277: 	    formname.overRideScore.value = 'yes';
1.41      ng       1278: 	}
1.71      ng       1279: 	return "update";
1.13      albertel 1280:     }
1.71      ng       1281: 
                   1282:     function updateSelect(formname,id) {
1.125     ng       1283: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1284: 	return;
1.41      ng       1285:     }
1.33      ng       1286: 
1.121     ng       1287: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1288:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1289: 	formname.gradeOpt.value = val;
1.71      ng       1290: 	if (val == "Save & Next") {
                   1291: 	    for (i=0;i<=total;i++) {
                   1292: 		for (j=0;j<parttot;j++) {
1.125     ng       1293: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1294: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1295: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1296: 			if (points == "") {
1.125     ng       1297: 			    var name = formname["name"+i].value;
1.129     ng       1298: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1299: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1300: 					       ", part "+partid+". Continue?");
1.71      ng       1301: 			    if (resp == false) {
1.125     ng       1302: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1303: 				return false;
                   1304: 			    }
                   1305: 			}
                   1306: 		    }
                   1307: 		}
                   1308: 	    }
                   1309: 	}
1.120     ng       1310: 	formname.submit();
                   1311:     }
                   1312: 
1.71      ng       1313: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1314:     function checkSubmitPage(formname,total) {
                   1315: 	noscore = new Array(100);
                   1316: 	var ptr = 0;
                   1317: 	for (i=1;i<total;i++) {
1.125     ng       1318: 	    var partid = formname["q_"+i].value;
1.127     ng       1319: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1320: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1321: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1322: 		if (points == "" && status != "correct_by_student") {
                   1323: 		    noscore[ptr] = i;
                   1324: 		    ptr++;
                   1325: 		}
                   1326: 	    }
                   1327: 	}
                   1328: 	if (ptr != 0) {
                   1329: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1330: 	    var prolist = "";
                   1331: 	    if (ptr == 1) {
                   1332: 		prolist = noscore[0];
                   1333: 	    } else {
                   1334: 		var i = 0;
                   1335: 		while (i < ptr-1) {
                   1336: 		    prolist += noscore[i]+", ";
                   1337: 		    i++;
                   1338: 		}
                   1339: 		prolist += "and "+noscore[i];
                   1340: 	    }
                   1341: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1342: 	    if (resp == false) {
                   1343: 		return false;
                   1344: 	    }
                   1345: 	}
1.45      ng       1346: 
1.71      ng       1347: 	formname.submit();
                   1348:     }
                   1349: SUBJAVASCRIPT
                   1350: }
1.45      ng       1351: 
1.71      ng       1352: #--- javascript for essay type problem --
                   1353: sub sub_page_kw_js {
                   1354:     my $request = shift;
1.80      ng       1355:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1356:     &commonJSfunctions($request);
1.350     albertel 1357: 
1.629     www      1358:     my $inner_js_msg_central= (<<INNERJS);
                   1359: <script type="text/javascript">
1.350     albertel 1360:     function checkInput() {
                   1361:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1362:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1363:       var usrctr = document.msgcenter.usrctr.value;
                   1364:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1365:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1366: 
                   1367:       var msgchk = "";
                   1368:       if (document.msgcenter.subchk.checked) {
                   1369:          msgchk = "msgsub,";
                   1370:       }
                   1371:       var includemsg = 0;
                   1372:       for (var i=1; i<=nmsg; i++) {
                   1373:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1374:           var frmmsg = document.msgcenter["msg"+i];
                   1375:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1376:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1377:           showflg.value = "1";
                   1378:           var chkbox = document.msgcenter["msgn"+i];
                   1379:           if (chkbox.checked) {
                   1380:              msgchk += "savemsg"+i+",";
                   1381:              includemsg = 1;
                   1382:           }
                   1383:       }
                   1384:       if (document.msgcenter.newmsgchk.checked) {
                   1385:          msgchk += "newmsg"+usrctr;
                   1386:          includemsg = 1;
                   1387:       }
                   1388:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1389:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1390:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1391:       includemsg.value = msgchk;
                   1392: 
                   1393:       self.close()
                   1394: 
                   1395:     }
1.629     www      1396: </script>
1.350     albertel 1397: INNERJS
                   1398: 
1.629     www      1399:     my $inner_js_highlight_central= (<<INNERJS);
                   1400: <script type="text/javascript">
1.351     albertel 1401:     function updateChoice(flag) {
                   1402:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1403:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1404:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1405:       opener.document.SCORE.refresh.value = "on";
                   1406:       if (opener.document.SCORE.keywords.value!=""){
                   1407:          opener.document.SCORE.submit();
                   1408:       }
                   1409:       self.close()
                   1410:     }
1.629     www      1411: </script>
1.351     albertel 1412: INNERJS
                   1413: 
                   1414:     my $start_page_msg_central = 
                   1415:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1416: 				       {'js_ready'  => 1,
                   1417: 					'only_body' => 1,
                   1418: 					'bgcolor'   =>'#FFFFFF',});
                   1419:     my $end_page_msg_central = 
                   1420: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1421: 
                   1422: 
                   1423:     my $start_page_highlight_central = 
                   1424:         &Apache::loncommon::start_page('Highlight Central',
                   1425: 				       $inner_js_highlight_central,
1.350     albertel 1426: 				       {'js_ready'  => 1,
                   1427: 					'only_body' => 1,
                   1428: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1429:     my $end_page_highlight_central = 
1.350     albertel 1430: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1431: 
1.219     www      1432:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1433:     $docopen=~s/^document\.//;
1.736     damieng  1434:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1435:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1436:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1437:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1438:                 col1 => 'red',
                   1439:                 col2 => 'green',
                   1440:                 col3 => 'blue',
                   1441:                 siz1 => 'normal',
                   1442:                 siz2 => '+1',
                   1443:                 siz3 => '+2',
                   1444:                 sty1 => 'normal',
                   1445:                 sty2 => 'italic',
                   1446:                 sty3 => 'bold',
                   1447:              );
                   1448:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1449:                 comp => 'Compose Message for: ',
                   1450:                 incl => 'Include',
1.656     raeburn  1451:                 type => 'Type',
1.652     raeburn  1452:                 subj => 'Subject',
                   1453:                 mesa => 'Message',
                   1454:                 new  => 'New',
                   1455:                 save => 'Save',
                   1456:                 canc => 'Cancel',
                   1457:                 kehi => 'Keyword Highlight Options',
                   1458:                 txtc => 'Text Color',
                   1459:                 font => 'Font Size',
1.656     raeburn  1460:                 fnst => 'Font Style',
1.652     raeburn  1461:              );
1.736     damieng  1462:     &js_escape(\%js_lt);
                   1463:     &html_escape(\%html_js_lt);
                   1464:     &js_escape(\%html_js_lt);
1.597     wenzelju 1465:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1466: 
1.44      ng       1467: //===================== Show list of keywords ====================
1.122     ng       1468:   function keywords(formname) {
1.736     damieng  1469:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1470:     if (nret==null) return;
1.122     ng       1471:     formname.keywords.value = nret;
1.44      ng       1472: 
1.122     ng       1473:     if (formname.keywords.value != "") {
1.128     ng       1474: 	formname.refresh.value = "on";
1.122     ng       1475: 	formname.submit();
1.44      ng       1476:     }
                   1477:     return;
                   1478:   }
                   1479: 
                   1480: //===================== Script to view submitted by ==================
                   1481:   function viewSubmitter(submitter) {
                   1482:     document.SCORE.refresh.value = "on";
                   1483:     document.SCORE.NCT.value = "1";
                   1484:     document.SCORE.unamedom0.value = submitter;
                   1485:     document.SCORE.submit();
                   1486:     return;
                   1487:   }
                   1488: 
                   1489: //===================== Script to add keyword(s) ==================
                   1490:   function getSel() {
                   1491:     if (document.getSelection) txt = document.getSelection();
                   1492:     else if (document.selection) txt = document.selection.createRange().text;
                   1493:     else return;
                   1494:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1495:     if (cleantxt=="") {
1.736     damieng  1496: 	alert("$js_lt{'plse'}");
1.44      ng       1497: 	return;
                   1498:     }
1.736     damieng  1499:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1500:     if (nret==null) return;
1.127     ng       1501:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1502:     if (document.SCORE.keywords.value != "") {
1.127     ng       1503: 	document.SCORE.refresh.value = "on";
1.44      ng       1504: 	document.SCORE.submit();
                   1505:     }
                   1506:     return;
                   1507:   }
                   1508: 
                   1509: //====================== Script for composing message ==============
1.80      ng       1510:    // preload images
                   1511:    img1 = new Image();
                   1512:    img1.src = "$iconpath/mailbkgrd.gif";
                   1513:    img2 = new Image();
                   1514:    img2.src = "$iconpath/mailto.gif";
                   1515: 
1.44      ng       1516:   function msgCenter(msgform,usrctr,fullname) {
                   1517:     var Nmsg  = msgform.savemsgN.value;
                   1518:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1519:     var subject = msgform.msgsub.value;
1.127     ng       1520:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1521:     re = /msgsub/;
                   1522:     var shwsel = "";
                   1523:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1524:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1525:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1526:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1527: 	var testmsg = "savemsg"+i+",";
                   1528: 	re = new RegExp(testmsg,"g");
1.44      ng       1529: 	shwsel = "";
                   1530: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1531: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1532: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1533: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1534: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1535:     }
1.125     ng       1536:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1537:     shwsel = "";
                   1538:     re = /newmsg/;
                   1539:     if (re.test(msgchk)) { shwsel = "checked" }
                   1540:     newMsg(newmsg,shwsel);
                   1541:     msgTail(); 
                   1542:     return;
                   1543:   }
                   1544: 
1.123     ng       1545:   function checkEntities(strx) {
                   1546:     if (strx.length == 0) return strx;
                   1547:     var orgStr = ["&", "<", ">", '"']; 
                   1548:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1549:     var counter = 0;
                   1550:     while (counter < 4) {
                   1551: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1552: 	counter++;
                   1553:     }
                   1554:     return strx;
                   1555:   }
                   1556: 
                   1557:   function strReplace(strx, orgStr, newStr) {
                   1558:     return strx.split(orgStr).join(newStr);
                   1559:   }
                   1560: 
1.44      ng       1561:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1562:     var height = 70*Nmsg+250;
1.44      ng       1563:     if (height > 600) {
                   1564: 	height = 600;
                   1565:     }
1.118     ng       1566:     var xpos = (screen.width-600)/2;
                   1567:     xpos = (xpos < 0) ? '0' : xpos;
                   1568:     var ypos = (screen.height-height)/2-30;
                   1569:     ypos = (ypos < 0) ? '0' : ypos;
                   1570: 
1.668     www      1571:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1572:     pWin.focus();
                   1573:     pDoc = pWin.document;
1.219     www      1574:     pDoc.$docopen;
1.351     albertel 1575:     pDoc.write('$start_page_msg_central');
1.76      ng       1576: 
                   1577:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1578:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1579:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1580: 
1.676     golterma 1581:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1582:     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       1583: }
                   1584:     function displaySubject(msg,shwsel) {
1.76      ng       1585:     pDoc = pWin.document;
1.676     golterma 1586:     pDoc.write("<tr>");
                   1587:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1588:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1589:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1590: }
                   1591: 
1.72      ng       1592:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1593:     pDoc = pWin.document;
1.676     golterma 1594:     pDoc.write("<tr>");
                   1595:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1596:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1597:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1598: }
                   1599: 
                   1600:   function newMsg(newmsg,shwsel) {
1.76      ng       1601:     pDoc = pWin.document;
1.676     golterma 1602:     pDoc.write("<tr>");
                   1603:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1604:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1605:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1606: }
                   1607: 
                   1608:   function msgTail() {
1.76      ng       1609:     pDoc = pWin.document;
1.676     golterma 1610:     //pDoc.write("<\\/table>");
1.465     albertel 1611:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1612:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1613:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1614:     pDoc.write("<\\/form>");
1.351     albertel 1615:     pDoc.write('$end_page_msg_central');
1.128     ng       1616:     pDoc.close();
1.44      ng       1617: }
                   1618: 
                   1619: //====================== Script for keyword highlight options ==============
                   1620:   function kwhighlight() {
                   1621:     var kwclr    = document.SCORE.kwclr.value;
                   1622:     var kwsize   = document.SCORE.kwsize.value;
                   1623:     var kwstyle  = document.SCORE.kwstyle.value;
                   1624:     var redsel = "";
                   1625:     var grnsel = "";
                   1626:     var blusel = "";
1.736     damieng  1627:     var txtcol1 = "$js_lt{'col1'}";
                   1628:     var txtcol2 = "$js_lt{'col2'}";
                   1629:     var txtcol3 = "$js_lt{'col3'}";
                   1630:     var txtsiz1 = "$js_lt{'siz1'}";
                   1631:     var txtsiz2 = "$js_lt{'siz2'}";
                   1632:     var txtsiz3 = "$js_lt{'siz3'}";
                   1633:     var txtsty1 = "$js_lt{'sty1'}";
                   1634:     var txtsty2 = "$js_lt{'sty2'}";
                   1635:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1636:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1637:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1638:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1639:     var sznsel = "";
                   1640:     var sz1sel = "";
                   1641:     var sz2sel = "";
1.718     bisitz   1642:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1643:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1644:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1645:     var synsel = "";
                   1646:     var syisel = "";
                   1647:     var sybsel = "";
1.718     bisitz   1648:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1649:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1650:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1651:     highlightCentral();
1.718     bisitz   1652:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1653:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1654:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1655:     highlightend();
                   1656:     return;
                   1657:   }
                   1658: 
                   1659:   function highlightCentral() {
1.76      ng       1660: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1661:     var xpos = (screen.width-400)/2;
                   1662:     xpos = (xpos < 0) ? '0' : xpos;
                   1663:     var ypos = (screen.height-330)/2-30;
                   1664:     ypos = (ypos < 0) ? '0' : ypos;
                   1665: 
1.206     albertel 1666:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1667:     hwdWin.focus();
                   1668:     var hDoc = hwdWin.document;
1.219     www      1669:     hDoc.$docopen;
1.351     albertel 1670:     hDoc.write('$start_page_highlight_central');
1.76      ng       1671:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1672:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1673: 
1.718     bisitz   1674:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1675:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1676:   }
                   1677: 
                   1678:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1679:     var hDoc = hwdWin.document;
1.718     bisitz   1680:     hDoc.write("<tr>");
1.76      ng       1681:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1682:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1683:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1684:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1685:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1686:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1687:     hDoc.write("<\\/tr>");
1.44      ng       1688:   }
                   1689: 
                   1690:   function highlightend() { 
1.76      ng       1691:     var hDoc = hwdWin.document;
1.718     bisitz   1692:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1693:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1694:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1695:     hDoc.write("<\\/form>");
1.351     albertel 1696:     hDoc.write('$end_page_highlight_central');
1.128     ng       1697:     hDoc.close();
1.44      ng       1698:   }
                   1699: 
                   1700: SUBJAVASCRIPT
                   1701: }
                   1702: 
1.349     albertel 1703: sub get_increment {
1.348     bowersj2 1704:     my $increment = $env{'form.increment'};
                   1705:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1706:         $increment != .1) {
                   1707:         $increment = 1;
                   1708:     }
                   1709:     return $increment;
                   1710: }
                   1711: 
1.585     bisitz   1712: sub gradeBox_start {
                   1713:     return (
                   1714:         &Apache::loncommon::start_data_table()
                   1715:        .&Apache::loncommon::start_data_table_header_row()
                   1716:        .'<th>'.&mt('Part').'</th>'
                   1717:        .'<th>'.&mt('Points').'</th>'
                   1718:        .'<th>&nbsp;</th>'
                   1719:        .'<th>'.&mt('Assign Grade').'</th>'
                   1720:        .'<th>'.&mt('Weight').'</th>'
                   1721:        .'<th>'.&mt('Grade Status').'</th>'
                   1722:        .&Apache::loncommon::end_data_table_header_row()
                   1723:     );
                   1724: }
                   1725: 
                   1726: sub gradeBox_end {
                   1727:     return (
                   1728:         &Apache::loncommon::end_data_table()
                   1729:     );
                   1730: }
1.71      ng       1731: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1732: sub gradeBox {
1.322     albertel 1733:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1734:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1735: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1736:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1737:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1738:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1739:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1740:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1741: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1742:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1743:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1744:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1745: 				       [$partid]);
                   1746:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1747:     if ($last_resets{$partid}) {
                   1748:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1749:     }
1.695     bisitz   1750:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1751:     my $ctr = 0;
1.348     bowersj2 1752:     my $thisweight = 0;
1.349     albertel 1753:     my $increment = &get_increment();
1.485     albertel 1754: 
                   1755:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1756:     while ($thisweight<=$wgt) {
1.532     bisitz   1757: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1758:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1759: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1760: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1761: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1762:         $thisweight += $increment;
1.71      ng       1763: 	$ctr++;
                   1764:     }
1.485     albertel 1765:     $radio.='</tr></table>';
                   1766: 
                   1767:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1768: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1769: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1770: 	$wgt.')" /></td>'."\n";
1.485     albertel 1771:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1772: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1773: 	' </td>'."\n";
                   1774:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1775: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1776:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1777: 	$line.='<option></option>'.
                   1778: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1779:     } else {
1.485     albertel 1780: 	$line.='<option selected="selected"></option>'.
                   1781: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1782:     }
1.485     albertel 1783:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1784: 
                   1785: 
                   1786:     $result .= 
1.695     bisitz   1787: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1788:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1789:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1790:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1791: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1792: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1793: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1794:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1795:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1796:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1797:         $aggtries.'" />'."\n";
1.582     raeburn  1798:     my $res_error;
                   1799:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1800:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1801:     if ($res_error) {
                   1802:         return &navmap_errormsg();
                   1803:     }
1.318     banghart 1804:     return $result;
                   1805: }
1.322     albertel 1806: 
                   1807: sub handback_box {
1.623     www      1808:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1809:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1810:     my (@respids);
1.652     raeburn  1811:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1812:     foreach my $part_response_id (@part_response_id) {
                   1813:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1814:         if ($part eq $partid) {
1.375     albertel 1815:             push(@respids,$resp);
1.323     banghart 1816:         }
                   1817:     }
1.318     banghart 1818:     my $result;
1.323     banghart 1819:     foreach my $respid (@respids) {
1.322     albertel 1820: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1821: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1822: 	next if (!@$files);
1.654     raeburn  1823: 	my $file_counter = 0;
1.313     banghart 1824: 	foreach my $file (@$files) {
1.368     banghart 1825: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1826:                 $file_counter++;
1.368     banghart 1827:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1828:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1829:     	        $file_disp = "$name.$ext";
                   1830:     	        $file = $file_path.$file_disp;
                   1831:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1832:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1833:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1834:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1835: 	    }
1.322     albertel 1836: 	}
1.654     raeburn  1837:         if ($file_counter) {
                   1838:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1839:                        '<span class="LC_info">'.
                   1840:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1841:         }
1.313     banghart 1842:     }
1.318     banghart 1843:     return $result;    
1.71      ng       1844: }
1.44      ng       1845: 
1.58      albertel 1846: sub show_problem {
1.382     albertel 1847:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1848:     my $rendered;
1.382     albertel 1849:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1850:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1851:     if ($mode eq 'both' or $mode eq 'text') {
                   1852: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1853: 						       $env{'request.course.id'},
                   1854: 						       undef,\%form);
1.144     albertel 1855:     }
1.58      albertel 1856:     if ($removeform) {
                   1857: 	$rendered=~s|<form(.*?)>||g;
                   1858: 	$rendered=~s|</form>||g;
1.374     albertel 1859: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1860:     }
1.144     albertel 1861:     my $companswer;
                   1862:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1863: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1864: 	$companswer=
                   1865: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1866: 						    $env{'request.course.id'},
                   1867: 						    %form);
1.144     albertel 1868:     }
1.58      albertel 1869:     if ($removeform) {
                   1870: 	$companswer=~s|<form(.*?)>||g;
                   1871: 	$companswer=~s|</form>||g;
1.144     albertel 1872: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1873:     }
1.671     raeburn  1874:     my $renderheading = &mt('View of the problem');
                   1875:     my $answerheading = &mt('Correct answer');
                   1876:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1877:         my $stu_fullname = $env{'form.fullname'};
                   1878:         if ($stu_fullname eq '') {
                   1879:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1880:         }
                   1881:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1882:         if ($forwhom ne '') {
                   1883:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1884:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1885:         }
                   1886:     }
1.468     albertel 1887:     $rendered=
1.588     bisitz   1888:         '<div class="LC_Box">'
1.671     raeburn  1889:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1890:        .$rendered
                   1891:        .'</div>';
1.468     albertel 1892:     $companswer=
1.588     bisitz   1893:         '<div class="LC_Box">'
1.671     raeburn  1894:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1895:        .$companswer
                   1896:        .'</div>';
1.468     albertel 1897:     my $result;
1.144     albertel 1898:     if ($mode eq 'both') {
1.588     bisitz   1899:         $result=$rendered.$companswer;
1.144     albertel 1900:     } elsif ($mode eq 'text') {
1.588     bisitz   1901:         $result=$rendered;
1.144     albertel 1902:     } elsif ($mode eq 'answer') {
1.588     bisitz   1903:         $result=$companswer;
1.144     albertel 1904:     }
1.71      ng       1905:     return $result;
1.58      albertel 1906: }
1.397     albertel 1907: 
1.396     banghart 1908: sub files_exist {
                   1909:     my ($r, $symb) = @_;
                   1910:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1911: 
1.396     banghart 1912:     foreach my $student (@students) {
                   1913:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1914:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1915: 					      $udom,$uname);
1.396     banghart 1916:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1917:         foreach my $submission (@$string) {
                   1918:             my ($partid,$respid) =
                   1919: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1920:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1921: 					   \%record);
                   1922:             return 1 if (@$files);
1.396     banghart 1923:         }
                   1924:     }
1.397     albertel 1925:     return 0;
1.396     banghart 1926: }
1.397     albertel 1927: 
1.394     banghart 1928: sub download_all_link {
                   1929:     my ($r,$symb) = @_;
1.621     www      1930:     unless (&files_exist($r, $symb)) {
                   1931:        $r->print(&mt('There are currently no submitted documents.'));
                   1932:        return;
                   1933:     }
                   1934: 
1.395     albertel 1935:     my $all_students = 
                   1936: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1937: 
                   1938:     my $parts =
                   1939: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1940: 
1.394     banghart 1941:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1942:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1943:                              'cgi.'.$identifier.'.symb' => $symb,
                   1944:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1945:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1946: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1947:     return;
                   1948: }
                   1949: 
                   1950: sub submit_download_link {
                   1951:     my ($request,$symb) = @_;
                   1952:     if (!$symb) { return ''; }
                   1953: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1954:     &download_all_link($request,$symb);
1.394     banghart 1955: }
1.395     albertel 1956: 
1.432     banghart 1957: sub build_section_inputs {
                   1958:     my $section_inputs;
                   1959:     if ($env{'form.section'} eq '') {
                   1960:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1961:     } else {
                   1962:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1963:         foreach my $section (@sections) {
1.432     banghart 1964:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1965:         }
                   1966:     }
                   1967:     return $section_inputs;
                   1968: }
                   1969: 
1.44      ng       1970: # --------------------------- show submissions of a student, option to grade 
                   1971: sub submission {
1.608     www      1972:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1973:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1974:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1975:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1976:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1977: 
1.605     www      1978:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1979:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1980: 
                   1981:     if (!&canview($usec)) {
1.712     bisitz   1982:         $request->print(
                   1983:             '<span class="LC_warning">'.
1.713     bisitz   1984:             &mt('Unable to view requested student.').
1.712     bisitz   1985:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1986:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1987:             '</span>');
1.104     albertel 1988: 	return;
                   1989:     }
                   1990: 
1.257     albertel 1991:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1992:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1993:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1994:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1995:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1996: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1997: 	'/check.gif" height="16" border="0" />';
1.41      ng       1998: 
                   1999:     # header info
                   2000:     if ($counter == 0) {
                   2001: 	&sub_page_js($request);
1.621     www      2002: 	&sub_page_kw_js($request);
1.118     ng       2003: 
1.44      ng       2004: 	# option to display problem, only once else it cause problems 
                   2005:         # with the form later since the problem has a form.
1.257     albertel 2006: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2007: 	    my $mode;
1.257     albertel 2008: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2009: 		$mode='both';
1.257     albertel 2010: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2011: 		$mode='text';
1.257     albertel 2012: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2013: 		$mode='answer';
                   2014: 	    }
1.329     albertel 2015: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2016: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2017: 	}
1.441     www      2018: 
1.704     raeburn  2019: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2020:         # if this subroutine has been called once.
1.41      ng       2021: 	my %keyhash = ();
1.624     www      2022: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2023:         if (1) {
1.41      ng       2024: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2025: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2026: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2027: 
1.257     albertel 2028: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2029: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2030: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2031: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2032: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2033: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2034: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2035: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2036: 	}
1.257     albertel 2037: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2038: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2039: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2040: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2041: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2042: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2043: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2044: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2045: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2046: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2047: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2048: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2049: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2050: 			&build_section_inputs().
1.326     albertel 2051: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2052: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2053: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2054: #	if ($env{'form.handgrade'} eq 'yes') {
                   2055:         if (1) {
1.257     albertel 2056: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2057: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2058: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2059: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2060: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2061: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2062: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2063: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2064: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2065: 	    }
1.123     ng       2066: 	}
1.41      ng       2067: 	
                   2068: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2069: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2070: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2071: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2072: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2073: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2074: 		'" />'."\n".
                   2075: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2076: 	    $cts++;
                   2077: 	}
                   2078: 	$request->print($prnmsg);
1.32      ng       2079: 
1.624     www      2080: #	if ($env{'form.handgrade'} eq 'yes') {
                   2081:         if (1) {
1.652     raeburn  2082: 
                   2083:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2084:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2085:                           keyw => 'Keyword Options',
1.655     raeburn  2086:                           list => 'List',
1.652     raeburn  2087:                           past => 'Paste Selection to List',
1.661     www      2088:                           high => 'Highlight Attribute',
1.652     raeburn  2089:                      );    
1.88      www      2090: #
                   2091: # Print out the keyword options line
                   2092: #
1.718     bisitz   2093: 	    $request->print(
                   2094:                 '<div class="LC_columnSection">'
                   2095:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2096:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2097:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2098:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2099:  class="page">'.$lt{'past'}.'</a>',
                   2100:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2101:                     {legend => $lt{'keyw'}})
                   2102:                .'</fieldset></div>'
                   2103:             );
                   2104: 
1.88      www      2105: #
                   2106: # Load the other essays for similarity check
                   2107: #
1.324     albertel 2108:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2109: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2110: 	    $apath=&escape($apath);
1.88      www      2111: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2112:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2113:         }
                   2114:     }
1.44      ng       2115: 
1.441     www      2116: # This is where output for one specific student would start
1.592     bisitz   2117:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2118:     $request->print(
                   2119:         "\n\n"
                   2120:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2121:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2122:        ."\n"
                   2123:     );
1.441     www      2124: 
1.592     bisitz   2125:     # Show additional functions if allowed
                   2126:     if ($perm{'vgr'}) {
                   2127:         $request->print(
                   2128:             &Apache::loncommon::track_student_link(
1.708     bisitz   2129:                 'View recent activity',
1.592     bisitz   2130:                 $uname,$udom,'check')
                   2131:            .' '
                   2132:         );
                   2133:     }
                   2134:     if ($perm{'opa'}) {
                   2135:         $request->print(
                   2136:             &Apache::loncommon::pprmlink(
                   2137:                 &mt('Set/Change parameters'),
                   2138:                 $uname,$udom,$symb,'check'));
                   2139:     }
                   2140: 
                   2141:     # Show Problem
1.257     albertel 2142:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2143: 	my $mode;
1.257     albertel 2144: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2145: 	    $mode='both';
1.257     albertel 2146: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2147: 	    $mode='text';
1.257     albertel 2148: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2149: 	    $mode='answer';
                   2150: 	}
1.329     albertel 2151: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2152: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2153:     }
1.144     albertel 2154: 
1.257     albertel 2155:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2156:     my $res_error;
                   2157:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2158:     if ($res_error) {
                   2159:         $request->print(&navmap_errormsg());
                   2160:         return;
                   2161:     }
1.41      ng       2162: 
1.44      ng       2163:     # Display student info
1.41      ng       2164:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2165: 
                   2166:     my $result='<div class="LC_Box">'
                   2167:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2168:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2169:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2170: #    if ($env{'form.handgrade'} eq 'no') {
                   2171:     if (1) {
1.588     bisitz   2172:         $result.='<p class="LC_info">'
                   2173:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2174:                 ."</p>\n";
1.469     albertel 2175:     }
                   2176: 
1.118     ng       2177:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2178:     my $fullname;
                   2179:     my $col_fullnames = [];
1.624     www      2180: #    if ($env{'form.handgrade'} eq 'yes') {
                   2181:     if (1) {
1.464     albertel 2182: 	(my $sub_result,$fullname,$col_fullnames)=
                   2183: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2184: 				 $counter);
                   2185: 	$result.=$sub_result;
1.41      ng       2186:     }
1.44      ng       2187:     $request->print($result."\n");
1.702     kruse    2188:     
1.44      ng       2189:     # print student answer/submission
1.588     bisitz   2190:     # Options are (1) Handgraded submission only
1.44      ng       2191:     #             (2) Last submission, includes submission that is not handgraded 
                   2192:     #                  (for multi-response type part)
                   2193:     #             (3) Last submission plus the parts info
                   2194:     #             (4) The whole record for this student
1.702     kruse    2195:     
                   2196:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2197: 	
1.702     kruse    2198:     my $lastsubonly;
1.468     albertel 2199: 
1.702     kruse    2200:     if ($$timestamp eq '') {
                   2201:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2202:     } else {
                   2203:         $lastsubonly =
                   2204:             '<div class="LC_grade_submissions_body">'
                   2205:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2206: 
                   2207: 	my %seenparts;
                   2208: 	my @part_response_id = &flatten_responseType($responseType);
                   2209: 	foreach my $part (@part_response_id) {
                   2210: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2211: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2212: 
1.702     kruse    2213: 	    my ($partid,$respid) = @{ $part };
                   2214: 	    my $display_part=&get_display_part($partid,$symb);
                   2215: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2216: 		if (exists($seenparts{$partid})) { next; }
                   2217: 		$seenparts{$partid}=1;
                   2218:                 $request->print(
                   2219:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2220:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2221:                                '<a href="javascript:viewSubmitter(\''.
                   2222:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2223:                                '\');" target="_self">'.
                   2224:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2225:                     '<br />');
                   2226: 		next;
                   2227: 		}
                   2228: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2229: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2230:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2231:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2232:                     ' <span class="LC_internal_info">'.
                   2233:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2234:                     '</span>&nbsp; &nbsp;'.
                   2235: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2236: 		next;
                   2237: 	    }
                   2238: 	    foreach my $submission (@$string) {
                   2239: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2240: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2241: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2242: 		# Similarity check
                   2243:                 my $similar='';
                   2244:                 my ($type,$trial,$rndseed);
                   2245:                 if ($hide eq 'rand') {
                   2246:                     $type = 'randomizetry';
                   2247:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2248:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2249:                 }
                   2250: 	        if ($env{'form.checkPlag'}) {
                   2251:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2252: 		        &most_similar($uname,$udom,$symb,$subval);
                   2253: 		    if ($osim) {
                   2254: 			$osim=int($osim*100.0);
                   2255: 			my %old_course_desc = 
                   2256: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2257: 							{'one_time' => 1});
                   2258: 
                   2259:                         if ($hide eq 'anon') {
                   2260:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2261:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2262:                         } else {
                   2263: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2264: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2265: 				    $osim,
                   2266: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2267: 				        $old_course_desc{'description'},
                   2268: 				        $old_course_desc{'num'},
                   2269: 				        $old_course_desc{'domain'}).
                   2270: 				    '</span></h3><blockquote><i>'.
                   2271: 				    &keywords_highlight($oessay).
                   2272: 				    '</i></blockquote><hr />';
1.702     kruse    2273:                         }
                   2274: 	            }
                   2275: 		}
                   2276: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2277:                                      undef,$type,$trial,$rndseed);
                   2278:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2279: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2280: 		    my $display_part=&get_display_part($partid,$symb);
                   2281:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2282:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2283:                         ' <span class="LC_internal_info">'.
                   2284:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2285:                         '</span>&nbsp; &nbsp;';
                   2286: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2287:                         
                   2288: 		    if (@$files) {
                   2289:                         if ($hide eq 'anon') {
                   2290:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2291:                         } else {
                   2292:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2293:                                         .'<br /><span class="LC_warning">';
                   2294:                             if(@$files == 1) {
                   2295:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2296:                             } else {
1.702     kruse    2297:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2298:                             }
                   2299:                             $lastsubonly .= '</span>';                         
                   2300:                             foreach my $file (@$files) {
                   2301:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2302:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2303:                             }
                   2304:                         }
1.702     kruse    2305: 			$lastsubonly.='<br />';
                   2306:                     }
                   2307:                     if ($hide eq 'anon') {
                   2308:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2309:                     } else {
1.724     raeburn  2310:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2311:                         if ($draft) {
                   2312:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2313:                         }
                   2314:                         $subval =
1.702     kruse    2315: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2316: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2317:                         if ($responsetype eq 'essay') {
                   2318:                             $subval =~ s{\n}{<br />}g;
                   2319:                         }
                   2320:                         $lastsubonly.=$subval."\n";
1.702     kruse    2321:                     }
                   2322: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2323: 		    $lastsubonly.='</div>';
1.41      ng       2324: 		}
1.702     kruse    2325:             }
1.151     albertel 2326: 	}
1.702     kruse    2327: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2328:     }
                   2329:     $request->print($lastsubonly);
                   2330:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2331:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2332: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2333:   
1.702     kruse    2334:     } 
                   2335:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2336:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2337:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2338: 								 $env{'request.course.id'},
1.44      ng       2339: 								 $last,'.submission',
1.726     raeburn  2340: 								 'Apache::grades::keywords_highlight',
                   2341:                                                                  $usec,$identifier));
1.41      ng       2342:     }
1.121     ng       2343:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2344: 	.$udom.'" />'."\n");
1.44      ng       2345:     # return if view submission with no grading option
1.618     www      2346:     if (!&canmodify($usec)) {
1.633     www      2347: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2348: 	return;
1.180     albertel 2349:     } else {
1.468     albertel 2350: 	$request->print('</div>'."\n");
1.41      ng       2351:     }
1.33      ng       2352: 
1.121     ng       2353:     # essay grading message center
1.624     www      2354: #    if ($env{'form.handgrade'} eq 'yes') {
                   2355:     if (1) {
1.468     albertel 2356: 	my $result='<div class="LC_grade_message_center">';
                   2357:     
                   2358: 	$result.='<div class="LC_grade_message_center_header">'.
                   2359: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2360: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2361: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2362: 	if (scalar(@$col_fullnames) > 0) {
                   2363: 	    my $lastone = pop(@$col_fullnames);
                   2364: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2365: 	}
                   2366: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2367: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2368: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2369: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2370: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2371: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2372: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2373: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2374: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2375: 	    '<br />&nbsp;('.
1.468     albertel 2376: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2377: 	$result.='</div></div>';
1.121     ng       2378: 	$request->print($result);
1.118     ng       2379:     }
1.41      ng       2380: 
                   2381:     my %seen = ();
                   2382:     my @partlist;
1.129     ng       2383:     my @gradePartRespid;
1.375     albertel 2384:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2385:     $request->print(
1.588     bisitz   2386:         '<div class="LC_Box">'
                   2387:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2388:     );
1.592     bisitz   2389:     $request->print(&gradeBox_start());
1.375     albertel 2390:     foreach my $part_response_id (@part_response_id) {
                   2391:     	my ($partid,$respid) = @{ $part_response_id };
                   2392: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2393: 	next if ($seen{$partid} > 0);
1.41      ng       2394: 	$seen{$partid}++;
1.393     albertel 2395: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2396: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2397: 	push(@partlist,$partid);
                   2398: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2399: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2400:     }
1.585     bisitz   2401:     $request->print(&gradeBox_end()); # </div>
                   2402:     $request->print('</div>');
1.468     albertel 2403: 
                   2404:     $request->print('<div class="LC_grade_info_links">');
                   2405:     $request->print('</div>');
                   2406: 
1.45      ng       2407:     $result='<input type="hidden" name="partlist'.$counter.
                   2408: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2409:     $result.='<input type="hidden" name="gradePartRespid'.
                   2410: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2411:     my $ctr = 0;
                   2412:     while ($ctr < scalar(@partlist)) {
                   2413: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2414: 	    $partlist[$ctr].'" />'."\n";
                   2415: 	$ctr++;
                   2416:     }
1.468     albertel 2417:     $request->print($result.''."\n");
1.41      ng       2418: 
1.441     www      2419: # Done with printing info for one student
                   2420: 
1.468     albertel 2421:     $request->print('</div>');#LC_grade_show_user
1.441     www      2422: 
                   2423: 
1.41      ng       2424:     # print end of form
                   2425:     if ($counter == $total) {
1.592     bisitz   2426:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2427: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2428: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2429: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2430: 	my $ntstu ='<select name="NTSTU">'.
                   2431: 	    '<option>1</option><option>2</option>'.
                   2432: 	    '<option>3</option><option>5</option>'.
                   2433: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2434: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2435: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2436:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2437: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2438: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2439: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2440: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2441:         $endform.='<span class="LC_warning">'.
                   2442:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2443:                   '</span>'."\n" ;
1.349     albertel 2444:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2445:             "' name='increment' />";
1.485     albertel 2446: 	$endform.='</td></tr></table></form>';
1.41      ng       2447: 	$request->print($endform);
                   2448:     }
                   2449:     return '';
1.38      ng       2450: }
                   2451: 
1.464     albertel 2452: sub check_collaborators {
                   2453:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2454:     my ($result,@col_fullnames);
                   2455:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2456:     foreach my $part (keys(%$handgrade)) {
                   2457: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2458: 					'.maxcollaborators',
                   2459: 					$symb,$udom,$uname);
                   2460: 	next if ($ncol <= 0);
                   2461: 	$part =~ s/\_/\./g;
                   2462: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2463: 	my (@good_collaborators, @bad_collaborators);
                   2464: 	foreach my $possible_collaborator
1.630     www      2465: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2466: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2467: 	    next if ($possible_collaborator eq '');
1.631     www      2468: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2469: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2470: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2471: 	    # Doing this grep allows 'fuzzy' specification
                   2472: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2473: 			       keys(%$classlist));
                   2474: 	    if (! scalar(@matches)) {
                   2475: 		push(@bad_collaborators, $possible_collaborator);
                   2476: 	    } else {
                   2477: 		push(@good_collaborators, @matches);
                   2478: 	    }
                   2479: 	}
                   2480: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2481: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2482: 	    foreach my $name (@good_collaborators) {
                   2483: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2484: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2485: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2486: 	    }
1.630     www      2487: 	    $result.='</ol><br />'."\n";
1.466     albertel 2488: 	    my ($part)=split(/\./,$part);
1.464     albertel 2489: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2490: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2491: 		"\n";
                   2492: 	}
                   2493: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2494: 	    $result.='<div class="LC_warning">';
1.464     albertel 2495: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2496: 	    $result .= '</div>';
                   2497: 	}         
                   2498: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2499: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2500: 	    $result .= &mt('This student has submitted too many '.
                   2501: 		'collaborators.  Maximum is [_1].',$ncol);
                   2502: 	    $result .= '</div>';
                   2503: 	}
                   2504:     }
                   2505:     return ($result,$fullname,\@col_fullnames);
                   2506: }
                   2507: 
1.44      ng       2508: #--- Retrieve the last submission for all the parts
1.38      ng       2509: sub get_last_submission {
1.119     ng       2510:     my ($returnhash)=@_;
1.596     raeburn  2511:     my (@string,$timestamp,%lasthidden);
1.119     ng       2512:     if ($$returnhash{'version'}) {
1.46      ng       2513: 	my %lasthash=();
                   2514: 	my ($version);
1.119     ng       2515: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2516: 	    foreach my $key (sort(split(/\:/,
                   2517: 					$$returnhash{$version.':keys'}))) {
                   2518: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2519: 		$timestamp = 
1.545     raeburn  2520: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2521: 	    }
                   2522: 	}
1.640     raeburn  2523:         my (%typeparts,%randombytry);
1.596     raeburn  2524:         my $showsurv = 
                   2525:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2526:         foreach my $key (sort(keys(%lasthash))) {
                   2527:             if ($key =~ /\.type$/) {
                   2528:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2529:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2530:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2531:                     my ($ign,@parts) = split(/\./,$key);
                   2532:                     pop(@parts);
1.641     raeburn  2533:                     my $id = join('.',@parts);
1.640     raeburn  2534:                     if ($lasthash{$key} eq 'randomizetry') {
                   2535:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2536:                     } else {
                   2537:                         unless ($showsurv) {
                   2538:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2539:                         }
1.596     raeburn  2540:                     }
                   2541:                     delete($lasthash{$key});
                   2542:                 }
                   2543:             }
                   2544:         }
                   2545:         my @hidden = keys(%typeparts);
1.640     raeburn  2546:         my @randomize = keys(%randombytry);
1.397     albertel 2547: 	foreach my $key (keys(%lasthash)) {
                   2548: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2549:             my $hide;
                   2550:             if (@hidden) {
                   2551:                 foreach my $id (@hidden) {
                   2552:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2553:                         $hide = 'anon';
1.596     raeburn  2554:                         last;
                   2555:                     }
                   2556:                 }
                   2557:             }
1.640     raeburn  2558:             unless ($hide) {
                   2559:                 if (@randomize) {
1.732     raeburn  2560:                     foreach my $id (@randomize) {
1.640     raeburn  2561:                         if ($key =~ /^\Q$id\E/) {
                   2562:                             $hide = 'rand';
                   2563:                             last;
                   2564:                         }
                   2565:                     }
                   2566:                 }
                   2567:             }
1.397     albertel 2568: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2569: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2570:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2571:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2572:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2573: 	}
                   2574:     }
1.397     albertel 2575:     if (!@string) {
                   2576: 	$string[0] =
1.539     riegler  2577: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2578:     }
                   2579:     return (\@string,\$timestamp);
1.38      ng       2580: }
1.35      ng       2581: 
1.44      ng       2582: #--- High light keywords, with style choosen by user.
1.38      ng       2583: sub keywords_highlight {
1.44      ng       2584:     my $string    = shift;
1.257     albertel 2585:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2586:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2587:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2588:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2589:     foreach my $keyword (@keylist) {
                   2590: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2591:     }
                   2592:     return $string;
1.38      ng       2593: }
1.36      ng       2594: 
1.671     raeburn  2595: # For Tasks provide a mechanism to display previous version for one specific student
                   2596: 
                   2597: sub show_previous_task_version {
                   2598:     my ($request,$symb) = @_;
                   2599:     if ($symb eq '') {
1.717     bisitz   2600:         $request->print(
                   2601:             '<span class="LC_error">'.
                   2602:             &mt('Unable to handle ambiguous references.').
                   2603:             '</span>');
1.671     raeburn  2604:         return '';
                   2605:     }
                   2606:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2607:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2608:     if (!&canview($usec)) {
1.712     bisitz   2609:         $request->print(
                   2610:             '<span class="LC_warning">'.
1.713     bisitz   2611:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2612:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2613:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2614:             '</span>');
1.671     raeburn  2615:         return;
                   2616:     }
                   2617:     my $mode = 'both';
                   2618:     my $isTask = ($symb =~/\.task$/);
                   2619:     if ($isTask) {
                   2620:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2621:             if ($env{'form.fullname'} eq '') {
                   2622:                 $env{'form.fullname'} =
                   2623:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2624:             }
                   2625:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2626:             $request->print("\n\n".
                   2627:                             '<div class="LC_grade_show_user">'.
                   2628:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2629:                             '</h2>'."\n");
                   2630:             &Apache::lonxml::clear_problem_counter();
                   2631:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2632:                             {'previousversion' => $env{'form.previousversion'} }));
                   2633:             $request->print("\n</div>");
                   2634:         }
                   2635:     }
                   2636:     return;
                   2637: }
                   2638: 
                   2639: sub choose_task_version_form {
                   2640:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2641:     my $isTask = ($symb =~/\.task$/);
                   2642:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2643:     if ($isTask) {
                   2644:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2645:                                               $udom,$uname);
                   2646:         if (($record{'resource.0.version'} eq '') ||
                   2647:             ($record{'resource.0.version'} < 2)) {
                   2648:             return ($record{'resource.0.version'},
                   2649:                     $record{'resource.0.version'},$result,$js);
                   2650:         } else {
                   2651:             $current = $record{'resource.0.version'};
                   2652:         }
                   2653:         if ($env{'form.previousversion'}) {
                   2654:             $displayed = $env{'form.previousversion'};
                   2655:             $rowtitle = &mt('Choose another version:')
                   2656:         } else {
                   2657:             $displayed = $current;
                   2658:             $rowtitle = &mt('Show earlier version:');
                   2659:         }
                   2660:         $result = '<div class="LC_left_float">';
                   2661:         my $list;
                   2662:         my $numversions = 0;
                   2663:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2664:             if ($i == $current) {
                   2665:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2666:                     next;
                   2667:                 } else {
                   2668:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2669:                     $numversions ++;
                   2670:                 }
                   2671:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2672:                 unless ($i == $env{'form.previousversion'}) {
                   2673:                     $numversions ++;
                   2674:                 }
                   2675:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2676:             }
                   2677:         }
                   2678:         if ($numversions) {
                   2679:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2680:             $result .=
                   2681:                 '<form name="getprev" method="post" action=""'.
                   2682:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2683:                 &Apache::loncommon::start_data_table().
                   2684:                 &Apache::loncommon::start_data_table_row().
                   2685:                 '<th align="left">'.$rowtitle.'</th>'.
                   2686:                 '<td><select name="version">'.
                   2687:                 '<option>'.&mt('Select').'</option>'.
                   2688:                 $list.
                   2689:                 '</select></td>'.
                   2690:                 &Apache::loncommon::end_data_table_row();
                   2691:             unless ($nomenu) {
                   2692:                 $result .= &Apache::loncommon::start_data_table_row().
                   2693:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2694:                 '<td><span class="LC_nobreak">'.
                   2695:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2696:                 &mt('Yes').'</label>'.
                   2697:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2698:                 '</span></td>'.
                   2699:                 &Apache::loncommon::end_data_table_row();
                   2700:             }
                   2701:             $result .=
                   2702:                 &Apache::loncommon::start_data_table_row().
                   2703:                 '<th align="left">&nbsp;</th>'.
                   2704:                 '<td>'.
                   2705:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2706:                 '</td>'.
                   2707:                 &Apache::loncommon::end_data_table_row().
                   2708:                 &Apache::loncommon::end_data_table().
                   2709:                 '</form>';
                   2710:             $js = &previous_display_javascript($nomenu,$current);
                   2711:         } elsif ($displayed && $nomenu) {
                   2712:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2713:         } else {
                   2714:             $result .= &mt('No previous versions to show for this student');
                   2715:         }
                   2716:         $result .= '</div>';
                   2717:     }
                   2718:     return ($current,$displayed,$result,$js);
                   2719: }
                   2720: 
                   2721: sub previous_display_javascript {
                   2722:     my ($nomenu,$current) = @_;
                   2723:     my $js = <<"JSONE";
                   2724: <script type="text/javascript">
                   2725: // <![CDATA[
                   2726: function previousVersion(uname,udom,symb) {
                   2727:     var current = '$current';
                   2728:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2729:     var prevstr = new RegExp("^\\\\d+\$");
                   2730:     if (!prevstr.test(version)) {
                   2731:         return false;
                   2732:     }
                   2733:     var url = '';
                   2734:     if (version == current) {
                   2735:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2736:     } else {
                   2737:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2738:     }
                   2739: JSONE
                   2740:     if ($nomenu) {
                   2741:         $js .= <<"JSTWO";
                   2742:     document.location.href = url;
                   2743: JSTWO
                   2744:     } else {
                   2745:         $js .= <<"JSTHREE";
                   2746:     var newwin = 0;
                   2747:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2748:         if (document.getprev.prevwin[i].checked == true) {
                   2749:             newwin = document.getprev.prevwin[i].value;
                   2750:         }
                   2751:     }
                   2752:     if (newwin == 1) {
                   2753:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2754:         url = url+'&inhibitmenu=yes';
                   2755:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2756:             previousWin = window.open(url,'',options,1);
                   2757:         } else {
                   2758:             previousWin.location.href = url;
                   2759:         }
                   2760:         previousWin.focus();
                   2761:         return false;
                   2762:     } else {
                   2763:         document.location.href = url;
                   2764:         return false;
                   2765:     }
                   2766: JSTHREE
                   2767:     }
                   2768:     $js .= <<"ENDJS";
                   2769:     return false;
                   2770: }
                   2771: // ]]>
                   2772: </script>
                   2773: ENDJS
                   2774: 
                   2775: }
                   2776: 
1.44      ng       2777: #--- Called from submission routine
1.38      ng       2778: sub processHandGrade {
1.608     www      2779:     my ($request,$symb) = @_;
1.324     albertel 2780:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2781:     my $button = $env{'form.gradeOpt'};
                   2782:     my $ngrade = $env{'form.NCT'};
                   2783:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2784:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2785:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2786: 
1.44      ng       2787:     if ($button eq 'Save & Next') {
                   2788: 	my $ctr = 0;
                   2789: 	while ($ctr < $ngrade) {
1.257     albertel 2790: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2791: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2792:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2793: 	    if ($errorflag eq 'no_score') {
                   2794: 		$ctr++;
                   2795: 		next;
                   2796: 	    }
1.104     albertel 2797: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2798: 		$request->print(
                   2799:                     '<span class="LC_error">'
                   2800:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2801:                    .'</span>');
1.104     albertel 2802: 		$ctr++;
                   2803: 		next;
                   2804: 	    }
1.726     raeburn  2805:             if ($numhidden) {
                   2806:                 $request->print(
                   2807:                     '<span class="LC_info">'
                   2808:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2809:                    .'</span><br />');
                   2810:             }
1.257     albertel 2811: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2812: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2813: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2814:             my ($feedurl,$showsymb) =
                   2815: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2816: 	    my $messagetail;
1.62      albertel 2817: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2818: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2819: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2820: 		$subject.=' ['.$restitle.']';
1.44      ng       2821: 		my (@msgnum) = split(/,/,$includemsg);
                   2822: 		foreach (@msgnum) {
1.257     albertel 2823: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2824: 		}
1.80      ng       2825: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2826: 		if ($env{'form.withgrades'.$ctr}) {
                   2827: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2828: 		    $messagetail = " for <a href=\"".
1.605     www      2829: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2830: 		}
                   2831: 		$msgstatus = 
                   2832:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2833: 						     $message.$messagetail,
1.418     albertel 2834:                                                      undef,$feedurl,undef,
1.386     raeburn  2835:                                                      undef,undef,$showsymb,
                   2836:                                                      $restitle);
1.574     bisitz   2837: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2838: 				$msgstatus.'<br />');
1.44      ng       2839: 	    }
1.257     albertel 2840: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2841: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2842: 		foreach my $collabstr (@collabstrs) {
                   2843: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2844: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2845: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2846: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2847: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2848: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2849: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2850: 			    next;
1.418     albertel 2851: 			} elsif ($message ne '') {
                   2852: 			    my ($baseurl,$showsymb) = 
                   2853: 				&get_feedurl_and_symb($symb,$collaborator,
                   2854: 						      $udom);
                   2855: 			    if ($env{'form.withgrades'.$ctr}) {
                   2856: 				$messagetail = " for <a href=\"".
1.605     www      2857:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2858: 			    }
1.418     albertel 2859: 			    $msgstatus = 
                   2860: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2861: 			}
1.44      ng       2862: 		    }
                   2863: 		}
                   2864: 	    }
                   2865: 	    $ctr++;
                   2866: 	}
                   2867:     }
                   2868: 
1.624     www      2869: #    if ($env{'form.handgrade'} eq 'yes') {
                   2870:     if (1) {
1.119     ng       2871: 	# Keywords sorted in alphabatical order
1.257     albertel 2872: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2873: 	my %keyhash = ();
1.257     albertel 2874: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2875: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2876: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2877: 	$env{'form.keywords'} = join(' ',@keywords);
                   2878: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2879: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2880: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2881: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2882: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2883: 
                   2884: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2885: 	# New messages are saved in env for the next student.
1.119     ng       2886: 	# All messages are saved in nohist_handgrade.db
                   2887: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2888: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2889: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2890: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2891: 		$idx++;
                   2892: 	    }
                   2893: 	    $ctr++;
1.41      ng       2894: 	}
1.119     ng       2895: 	$ctr = 0;
                   2896: 	while ($ctr < $ngrade) {
1.257     albertel 2897: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2898: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2899: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2900: 		$idx++;
                   2901: 	    }
                   2902: 	    $ctr++;
1.41      ng       2903: 	}
1.257     albertel 2904: 	$env{'form.savemsgN'} = --$idx;
                   2905: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2906: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2907: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2908:     }
1.44      ng       2909:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2910:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2911:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2912: 	my ($ctr,$total) = (0,0);
                   2913: 	while ($ctr < $ngrade) {
1.257     albertel 2914: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2915: 	    $ctr++;
                   2916: 	}
1.257     albertel 2917: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2918: 	$ctr = 0;
                   2919: 	while ($ctr < $total) {
1.257     albertel 2920: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2921: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2922: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2923: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2924: 	    $ctr++;
                   2925: 	}
                   2926: 	return '';
                   2927:     }
1.36      ng       2928: 
1.44      ng       2929:     # Get the next/previous one or group of students
1.257     albertel 2930:     my $firststu = $env{'form.unamedom0'};
                   2931:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2932:     my $ctr = 2;
1.41      ng       2933:     while ($laststu eq '') {
1.257     albertel 2934: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2935: 	$ctr++;
                   2936: 	$laststu = $firststu if ($ctr > $ngrade);
                   2937:     }
1.44      ng       2938: 
1.41      ng       2939:     my (@parsedlist,@nextlist);
                   2940:     my ($nextflg) = 0;
1.524     raeburn  2941:     foreach my $item (sort 
1.294     albertel 2942: 	     {
                   2943: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2944: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2945: 		 }
                   2946: 		 return $a cmp $b;
                   2947: 	     } (keys(%$fullname))) {
1.605     www      2948: # FIXME: this is fishy, looks like the button label
1.41      ng       2949: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2950: 	    push(@parsedlist,$item);
1.41      ng       2951: 	}
1.524     raeburn  2952: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2953: 	if ($button eq 'Previous') {
1.524     raeburn  2954: 	    last if ($item eq $firststu);
                   2955: 	    push(@parsedlist,$item);
1.41      ng       2956: 	}
                   2957:     }
                   2958:     $ctr = 0;
1.605     www      2959: # FIXME: this is fishy, looks like the button label
1.41      ng       2960:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2961:     my $res_error;
                   2962:     my ($partlist) = &response_type($symb,\$res_error);
                   2963:     if ($res_error) {
                   2964:         $request->print(&navmap_errormsg());
                   2965:         return;
                   2966:     }
1.41      ng       2967:     foreach my $student (@parsedlist) {
1.257     albertel 2968: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2969: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2970: 	
                   2971: 	if ($submitonly eq 'queued') {
                   2972: 	    my %queue_status = 
                   2973: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2974: 							$udom,$uname);
                   2975: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2976: 	}
                   2977: 
1.156     albertel 2978: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2979: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2980: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2981: 	    my $submitted = 0;
1.248     albertel 2982: 	    my $ungraded = 0;
                   2983: 	    my $incorrect = 0;
1.524     raeburn  2984: 	    foreach my $item (keys(%status)) {
                   2985: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2986: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2987: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2988: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2989: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2990: 		    $submitted = 0;
                   2991: 		}
1.41      ng       2992: 	    }
1.156     albertel 2993: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2994: 				     $submitonly eq 'incorrect' ||
                   2995: 				     $submitonly eq 'graded'));
1.248     albertel 2996: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2997: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2998: 	}
1.524     raeburn  2999: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3000: 	last if ($ctr == $ntstu);
1.41      ng       3001: 	$ctr++;
                   3002:     }
1.36      ng       3003: 
1.41      ng       3004:     $ctr = 0;
                   3005:     my $total = scalar(@nextlist)-1;
1.39      ng       3006: 
1.524     raeburn  3007:     foreach (sort(@nextlist)) {
1.41      ng       3008: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3009: 	$env{'form.student'}  = $uname;
                   3010: 	$env{'form.userdom'}  = $udom;
                   3011: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3012: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3013: 	$ctr++;
                   3014:     }
                   3015:     if ($total < 0) {
1.653     raeburn  3016: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3017: 	$request->print($the_end);
                   3018:     }
                   3019:     return '';
1.38      ng       3020: }
1.36      ng       3021: 
1.44      ng       3022: #---- Save the score and award for each student, if changed
1.38      ng       3023: sub saveHandGrade {
1.324     albertel 3024:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3025:     my @version_parts;
1.104     albertel 3026:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3027: 					   $env{'request.course.id'});
1.104     albertel 3028:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3029:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3030:     my @parts_graded;
1.77      ng       3031:     my %newrecord  = ();
1.726     raeburn  3032:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3033:     my %aggregate = ();
                   3034:     my $aggregateflag = 0;
1.726     raeburn  3035:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3036:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3037:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3038:         $totchg += $numchgs;
                   3039:     }
1.301     albertel 3040:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3041:     foreach my $new_part (@parts) {
1.337     banghart 3042: 	#collaborator ($submi may vary for different parts
1.259     banghart 3043: 	if ($submitter && $new_part ne $part) { next; }
                   3044: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3045: 	if ($dropMenu eq 'excused') {
1.259     banghart 3046: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3047: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3048: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3049: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3050: 		}
1.364     banghart 3051: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3052: 	    }
1.125     ng       3053: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3054: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3055: 	    foreach my $key (keys(%record)) {
1.259     banghart 3056: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3057: 	    }
1.259     banghart 3058: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3059: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3060:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3061: 
                   3062:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3063: 					       [$new_part]);
                   3064:             my $aggtries =$totaltries;
1.269     raeburn  3065:             if ($last_resets{$new_part}) {
1.270     albertel 3066:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3067: 					   $new_part);
1.269     raeburn  3068:             }
1.270     albertel 3069: 
                   3070:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3071:             if ($aggtries > 0) {
1.327     albertel 3072:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3073:                 $aggregateflag = 1;
                   3074:             }
1.125     ng       3075: 	} elsif ($dropMenu eq '') {
1.259     banghart 3076: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3077: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3078: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3079: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3080: 		next;
                   3081: 	    }
1.259     banghart 3082: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3083: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3084: 	    my $partial= $pts/$wgt;
1.259     banghart 3085: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3086: 		#do not update score for part if not changed.
1.346     banghart 3087:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3088: 		next;
1.251     banghart 3089: 	    } else {
1.524     raeburn  3090: 	        push(@parts_graded,$new_part);
1.153     albertel 3091: 	    }
1.259     banghart 3092: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3093: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3094: 	    }
1.259     banghart 3095: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3096: 	    if ($partial == 0) {
1.153     albertel 3097: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3098: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3099: 		}
1.41      ng       3100: 	    } else {
1.153     albertel 3101: 		if ($record{$reckey} ne 'correct_by_override') {
                   3102: 		    $newrecord{$reckey} = 'correct_by_override';
                   3103: 		}
                   3104: 	    }	    
                   3105: 	    if ($submitter && 
1.259     banghart 3106: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3107: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3108: 	    }
1.259     banghart 3109: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3110: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3111: 	}
1.259     banghart 3112: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3113: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3114: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3115: 	        $dropMenu eq 'reset status')
                   3116: 	   {
1.524     raeburn  3117: 	    push(@version_parts,$new_part);
1.259     banghart 3118: 	}
1.41      ng       3119:     }
1.301     albertel 3120:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3121:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3122: 
1.344     albertel 3123:     if (%newrecord) {
                   3124:         if (@version_parts) {
1.364     banghart 3125:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3126:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3127: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3128: 	    foreach my $new_part (@version_parts) {
                   3129: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3130: 				$new_part,\%newrecord);
                   3131: 	    }
1.259     banghart 3132:         }
1.44      ng       3133: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3134: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3135: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3136: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3137:     }
1.269     raeburn  3138:     if ($aggregateflag) {
                   3139:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3140: 			      $cdom,$cnum);
1.269     raeburn  3141:     }
1.726     raeburn  3142:     return ('',$pts,$wgt,$totchg);
                   3143: }
                   3144: 
                   3145: sub makehidden {
1.728     raeburn  3146:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3147:     return unless (ref($record) eq 'HASH');
                   3148:     my %modified;
                   3149:     my $numchanged = 0;
                   3150:     if (exists($record->{$version.':keys'})) {
                   3151:         my $partsregexp = $parts;
                   3152:         $partsregexp =~ s/,/|/g;
                   3153:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3154:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3155:                  my $item = $1;
                   3156:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3157:                      $modified{$key} = $record->{$version.':'.$key};
                   3158:                  }
                   3159:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3160:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3161:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3162:                 $modified{$key} = $record->{$version.':'.$key};
                   3163:             }
                   3164:         }
                   3165:         if (keys(%modified)) {
                   3166:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3167:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3168:                 $numchanged ++;
                   3169:             }
                   3170:         }
                   3171:     }
                   3172:     return $numchanged;
1.36      ng       3173: }
1.322     albertel 3174: 
1.380     albertel 3175: sub check_and_remove_from_queue {
                   3176:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3177:     my @ungraded_parts;
                   3178:     foreach my $part (@{$parts}) {
                   3179: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3180: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3181: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3182: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3183: 		) {
                   3184: 	    push(@ungraded_parts, $part);
                   3185: 	}
                   3186:     }
                   3187:     if ( !@ungraded_parts ) {
                   3188: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3189: 					       $cnum,$domain,$stuname);
                   3190:     }
                   3191: }
                   3192: 
1.337     banghart 3193: sub handback_files {
                   3194:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3195:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3196:     my $res_error;
                   3197:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3198:     if ($res_error) {
                   3199:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3200:         return;
                   3201:     }
1.654     raeburn  3202:     my @handedback;
                   3203:     my $file_msg;
1.375     albertel 3204:     my @part_response_id = &flatten_responseType($responseType);
                   3205:     foreach my $part_response_id (@part_response_id) {
                   3206:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3207: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3208:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3209:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3210:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3211:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3212:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3213:                     my ($directory,$answer_file) = 
1.654     raeburn  3214:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3215:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3216: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3217: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3218:                     my $getpropath = 1;
1.662     raeburn  3219:                     my ($dir_list,$listerror) = 
                   3220:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3221:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3222: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3223:                     # fix filename
1.355     banghart 3224:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3225:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3226:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3227:             	                                $save_file_name);
1.337     banghart 3228:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3229:                         $request->print('<br /><span class="LC_error">'.
                   3230:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3231:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3232:                                         '</span>');
1.356     banghart 3233:                     } else {
1.360     banghart 3234:                         # mark the file as read only
1.654     raeburn  3235:                         push(@handedback,$save_file_name);
1.367     albertel 3236: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3237: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3238: 			}
                   3239:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3240: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3241:                     }
1.686     bisitz   3242:                     $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 3243:                 }
                   3244:             }
                   3245:         }
1.654     raeburn  3246:     }
                   3247:     if (@handedback > 0) {
                   3248:         $request->print('<br />');
                   3249:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3250:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3251:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3252:         my ($subject,$message);
                   3253:         if (scalar(@handedback) == 1) {
                   3254:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3255:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3256:         } else {
                   3257:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3258:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3259:         }
                   3260:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3261:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3262:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3263:         my ($feedurl,$showsymb) =
                   3264:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3265:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3266:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3267:         my $msgstatus =
                   3268:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3269:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3270:                  $restitle);
                   3271:         if ($msgstatus) {
                   3272:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3273:         }
                   3274:     }
1.338     banghart 3275:     return;
1.337     banghart 3276: }
                   3277: 
1.418     albertel 3278: sub get_feedurl_and_symb {
                   3279:     my ($symb,$uname,$udom) = @_;
                   3280:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3281:     $url = &Apache::lonnet::clutter($url);
                   3282:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3283: 					$symb,$udom,$uname);
                   3284:     if ($encrypturl =~ /^yes$/i) {
                   3285: 	&Apache::lonenc::encrypted(\$url,1);
                   3286: 	&Apache::lonenc::encrypted(\$symb,1);
                   3287:     }
                   3288:     return ($url,$symb);
                   3289: }
                   3290: 
1.313     banghart 3291: sub get_submitted_files {
                   3292:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3293:     my @files;
                   3294:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3295:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3296:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3297:     	    push(@files,$file_url.$file);
                   3298:         }
                   3299:     }
                   3300:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3301:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3302:     }
                   3303:     return (\@files);
                   3304: }
1.322     albertel 3305: 
1.269     raeburn  3306: # ----------- Provides number of tries since last reset.
                   3307: sub get_num_tries {
                   3308:     my ($record,$last_reset,$part) = @_;
                   3309:     my $timestamp = '';
                   3310:     my $num_tries = 0;
                   3311:     if ($$record{'version'}) {
                   3312:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3313:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3314:                 $timestamp = $$record{$version.':timestamp'};
                   3315:                 if ($timestamp > $last_reset) {
                   3316:                     $num_tries ++;
                   3317:                 } else {
                   3318:                     last;
                   3319:                 }
                   3320:             }
                   3321:         }
                   3322:     }
                   3323:     return $num_tries;
                   3324: }
                   3325: 
                   3326: # ----------- Determine decrements required in aggregate totals 
                   3327: sub decrement_aggs {
                   3328:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3329:     my %decrement = (
                   3330:                         attempts => 0,
                   3331:                         users => 0,
                   3332:                         correct => 0
                   3333:                     );
                   3334:     $decrement{'attempts'} = $aggtries;
                   3335:     if ($solvedstatus =~ /^correct/) {
                   3336:         $decrement{'correct'} = 1;
                   3337:     }
                   3338:     if ($aggtries == $totaltries) {
                   3339:         $decrement{'users'} = 1;
                   3340:     }
1.524     raeburn  3341:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3342:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3343:     }
                   3344:     return;
                   3345: }
                   3346: 
                   3347: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3348: sub get_last_resets {
1.270     albertel 3349:     my ($symb,$courseid,$partids) =@_;
                   3350:     my %last_resets;
1.269     raeburn  3351:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3352:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3353:     my @keys;
                   3354:     foreach my $part (@{$partids}) {
                   3355: 	push(@keys,"$symb\0$part\0resettime");
                   3356:     }
                   3357:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3358: 				     $cdom,$cname);
                   3359:     foreach my $part (@{$partids}) {
                   3360: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3361:     }
1.270     albertel 3362:     return %last_resets;
1.269     raeburn  3363: }
                   3364: 
1.251     banghart 3365: # ----------- Handles creating versions for portfolio files as answers
                   3366: sub version_portfiles {
1.343     banghart 3367:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3368:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3369:     my @returned_keys;
1.255     banghart 3370:     my $parts = join('|', @$parts_graded);
1.277     albertel 3371:     foreach my $key (keys(%$record)) {
1.259     banghart 3372:         my $new_portfiles;
1.263     banghart 3373:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3374:             my @versioned_portfiles;
1.367     albertel 3375:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3376:             if (@portfiles) {
                   3377:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3378:                                                       \@versioned_portfiles);
1.252     banghart 3379:             }
1.343     banghart 3380:             $$record{$key} = join(',',@versioned_portfiles);
                   3381:             push(@returned_keys,$key);
1.251     banghart 3382:         }
                   3383:     } 
1.343     banghart 3384:     return (@returned_keys);   
1.305     banghart 3385: }
                   3386: 
1.44      ng       3387: #--------------------------------------------------------------------------------------
                   3388: #
                   3389: #-------------------------- Next few routines handles grading by section or whole class
                   3390: #
                   3391: #--- Javascript to handle grading by section or whole class
1.42      ng       3392: sub viewgrades_js {
                   3393:     my ($request) = shift;
                   3394: 
1.539     riegler  3395:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3396:     &js_escape(\$alertmsg);
1.597     wenzelju 3397:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3398:    function writePoint(partid,weight,point) {
1.125     ng       3399: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3400: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3401: 	if (point == "textval") {
1.125     ng       3402: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3403: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3404: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3405: 		var resetbox = false;
                   3406: 		for (var i=0; i<radioButton.length; i++) {
                   3407: 		    if (radioButton[i].checked) {
                   3408: 			textbox.value = i;
                   3409: 			resetbox = true;
                   3410: 		    }
                   3411: 		}
                   3412: 		if (!resetbox) {
                   3413: 		    textbox.value = "";
                   3414: 		}
                   3415: 		return;
                   3416: 	    }
1.109     matthew  3417: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3418: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3419: 				   ") greater than the weight for the part. Accept?");
                   3420: 		if (resp == false) {
                   3421: 		    textbox.value = "";
                   3422: 		    return;
                   3423: 		}
                   3424: 	    }
1.42      ng       3425: 	    for (var i=0; i<radioButton.length; i++) {
                   3426: 		radioButton[i].checked=false;
1.109     matthew  3427: 		if (parseFloat(point) == i) {
1.42      ng       3428: 		    radioButton[i].checked=true;
                   3429: 		}
                   3430: 	    }
1.41      ng       3431: 
1.42      ng       3432: 	} else {
1.125     ng       3433: 	    textbox.value = parseFloat(point);
1.42      ng       3434: 	}
1.41      ng       3435: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3436: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3437: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3438: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3439: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3440: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3441: 	    if (saveval != "correct") {
                   3442: 		scorename.value = point;
1.43      ng       3443: 		if (selname[0].selected != true) {
                   3444: 		    selname[0].selected = true;
                   3445: 		}
1.42      ng       3446: 	    }
                   3447: 	}
1.125     ng       3448: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3449:     }
                   3450: 
                   3451:     function writeRadText(partid,weight) {
1.125     ng       3452: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3453: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3454:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3455: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3456: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3457: 	    for (var i=0; i<radioButton.length; i++) {
                   3458: 		radioButton[i].checked=false;
                   3459: 
                   3460: 	    }
                   3461: 	    textbox.value = "";
                   3462: 
                   3463: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3464: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3465: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3466: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3467: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3468: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3469: 		if ((saveval != "correct") || override) {
1.42      ng       3470: 		    scorename.value = "";
1.125     ng       3471: 		    if (selval[1].selected) {
                   3472: 			selname[1].selected = true;
                   3473: 		    } else {
                   3474: 			selname[2].selected = true;
                   3475: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3476: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3477: 		    }
1.42      ng       3478: 		}
                   3479: 	    }
1.43      ng       3480: 	} else {
                   3481: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3482: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3483: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3484: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3485: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3486: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3487: 		if ((saveval != "correct") || override) {
1.125     ng       3488: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3489: 		    selname[0].selected = true;
                   3490: 		}
                   3491: 	    }
                   3492: 	}	    
1.42      ng       3493:     }
                   3494: 
                   3495:     function changeSelect(partid,user) {
1.125     ng       3496: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3497: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3498: 	var point  = textbox.value;
1.125     ng       3499: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3500: 
1.109     matthew  3501: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3502: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3503: 	    textbox.value = "";
                   3504: 	    return;
                   3505: 	}
1.109     matthew  3506: 	if (parseFloat(point) > parseFloat(weight)) {
                   3507: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3508: 			       ") greater than the weight of the part. Accept?");
                   3509: 	    if (resp == false) {
                   3510: 		textbox.value = "";
                   3511: 		return;
                   3512: 	    }
                   3513: 	}
1.42      ng       3514: 	selval[0].selected = true;
                   3515:     }
                   3516: 
                   3517:     function changeOneScore(partid,user) {
1.125     ng       3518: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3519: 	if (selval[1].selected || selval[2].selected) {
                   3520: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3521: 	    if (selval[2].selected) {
                   3522: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3523: 	    }
1.269     raeburn  3524:         }
1.42      ng       3525:     }
                   3526: 
                   3527:     function resetEntry(numpart) {
                   3528: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3529: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3530: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3531: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3532: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3533: 	    for (var i=0; i<radioButton.length; i++) {
                   3534: 		radioButton[i].checked=false;
                   3535: 
                   3536: 	    }
                   3537: 	    textbox.value = "";
                   3538: 	    selval[0].selected = true;
                   3539: 
                   3540: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3541: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3542: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3543: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3544: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3545: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3546: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3547: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3548: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3549: 		if (saveselval == "excused") {
1.43      ng       3550: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3551: 		} else {
1.43      ng       3552: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3553: 		}
                   3554: 	    }
1.41      ng       3555: 	}
1.42      ng       3556:     }
                   3557: 
1.41      ng       3558: VIEWJAVASCRIPT
1.42      ng       3559: }
                   3560: 
1.44      ng       3561: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3562: sub viewgrades {
1.608     www      3563:     my ($request,$symb) = @_;
1.42      ng       3564:     &viewgrades_js($request);
1.41      ng       3565: 
1.168     albertel 3566:     #need to make sure we have the correct data for later EXT calls, 
                   3567:     #thus invalidate the cache
                   3568:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3569:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3570:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3571:     &Apache::lonnet::clear_EXT_cache_status();
                   3572: 
1.398     albertel 3573:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3574: 
                   3575:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3576:     $result.=&jscriptNform($symb);
1.41      ng       3577: 
1.44      ng       3578:     #beginning of class grading form
1.442     banghart 3579:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3580:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3581: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3582: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3583: 	&build_section_inputs().
1.442     banghart 3584: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3585: 
1.738     raeburn  3586:     #retrieve selected groups
                   3587:     my (@groups,$group_display);
                   3588:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3589:     if (grep(/^all$/,@groups)) {
                   3590:         @groups = ('all');
                   3591:     } elsif (grep(/^none$/,@groups)) {
                   3592:         @groups = ('none');
                   3593:     } elsif (@groups > 0) {
                   3594:         $group_display = join(', ',@groups);
                   3595:     }
                   3596: 
                   3597:     my ($common_header,$specific_header,@sections,$section_display);
                   3598:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3599:     if (grep(/^all$/,@sections)) {
                   3600:         @sections = ('all');
                   3601:         if ($group_display) {
                   3602:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3603:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3604:         } elsif (grep(/^none$/,@groups)) {
                   3605:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3606:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3607:         } else {
                   3608: 	    $common_header = &mt('Assign Common Grade to Class');
                   3609:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3610:         }
                   3611:     } elsif (grep(/^none$/,@sections)) {
                   3612:         @sections = ('none');
                   3613:         if ($group_display) {
                   3614:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3615:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3616:         } elsif (grep(/^none$/,@groups)) {
                   3617:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3618:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3619:         } else {
                   3620:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3621: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3622:         }
                   3623:     } else {
                   3624:         $section_display = join (", ",@sections);
                   3625:         if ($group_display) {
                   3626:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3627:                                  $section_display,$group_display);
                   3628:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3629:                                    $section_display,$group_display);
                   3630:         } elsif (grep(/^none$/,@groups)) {
                   3631:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3632:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3633:         } else {
                   3634:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3635: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3636:         }
                   3637:     }
                   3638:     my %submit_types = &substatus_options();
                   3639:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3640: 
                   3641:     if ($env{'form.submitonly'} eq 'all') {
                   3642:         $result.= '<h3>'.$common_header.'</h3>';
                   3643:     } else {
                   3644:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
1.52      albertel 3645:     }
1.738     raeburn  3646:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3647:     #radio buttons/text box for assigning points for a section or class.
                   3648:     #handles different parts of a problem
1.582     raeburn  3649:     my $res_error;
                   3650:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3651:     if ($res_error) {
                   3652:         return &navmap_errormsg();
                   3653:     }
1.42      ng       3654:     my %weight = ();
                   3655:     my $ctsparts = 0;
1.45      ng       3656:     my %seen = ();
1.375     albertel 3657:     my @part_response_id = &flatten_responseType($responseType);
                   3658:     foreach my $part_response_id (@part_response_id) {
                   3659:     	my ($partid,$respid) = @{ $part_response_id };
                   3660: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3661: 	next if $seen{$partid};
                   3662: 	$seen{$partid}++;
1.375     albertel 3663: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3664: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3665: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3666: 
1.324     albertel 3667: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3668: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3669: 	my $ctr = 0;
1.42      ng       3670: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3671: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3672: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3673: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3674: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3675: 	    $ctr++;
                   3676: 	}
1.485     albertel 3677: 	$radio.='</tr></table>';
                   3678: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3679: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3680: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3681: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3682:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3683:             '<select name="SELVAL_'.$partid.'" '.
                   3684:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3685:                 $weight{$partid}.')"> '.
1.401     albertel 3686: 	    '<option selected="selected"> </option>'.
1.485     albertel 3687: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3688: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3689: 	    '</select></td>'.
                   3690:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3691: 	$line.='<input type="hidden" name="partid_'.
                   3692: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3693: 	$line.='<input type="hidden" name="weight_'.
                   3694: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3695: 
                   3696: 	$result.=
                   3697: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3698: 	    '<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 3699: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3700: 	$ctsparts++;
1.41      ng       3701:     }
1.474     albertel 3702:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3703: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3704:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3705: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3706: 
1.44      ng       3707:     #table listing all the students in a section/class
                   3708:     #header of table
1.738     raeburn  3709:     if ($env{'form.submitonly'} eq 'all') {
                   3710:         $result.= '<h3>'.$specific_header.'</h3>';
                   3711:     } else {
                   3712:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   3713:     }
                   3714:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3715: 	      &Apache::loncommon::start_data_table_header_row().
                   3716: 	      '<th>'.&mt('No.').'</th>'.
                   3717: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3718:     my $partserror;
                   3719:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3720:     if ($partserror) {
                   3721:         return &navmap_errormsg();
                   3722:     }
1.324     albertel 3723:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3724:     my @partids = ();
1.41      ng       3725:     foreach my $part (@parts) {
                   3726: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3727:         my $narrowtext = &mt('Tries');
                   3728: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3729: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3730: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3731:         push(@partids,$partid);
1.628     www      3732: #
                   3733: # FIXME: Looks like $display looks at English text
                   3734: #
1.324     albertel 3735: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3736: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3737: 	    $result.='<th>'.
1.697     bisitz   3738: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3739: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3740: 	    next;
1.485     albertel 3741: 	    
1.207     albertel 3742: 	} else {
1.485     albertel 3743: 	    if ($display =~ /Problem Status/) {
                   3744: 		my $grade_status_mt = &mt('Grade Status');
                   3745: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3746: 	    }
                   3747: 	    my $part_mt = &mt('Part:');
                   3748: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3749: 	}
1.485     albertel 3750: 
1.474     albertel 3751: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3752:     }
1.474     albertel 3753:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3754: 
1.270     albertel 3755:     my %last_resets = 
                   3756: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3757: 
1.41      ng       3758:     #get info for each student
1.44      ng       3759:     #list all the students - with points and grade status
1.738     raeburn  3760:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3761:     my $ctr = 0;
1.294     albertel 3762:     foreach (sort 
                   3763: 	     {
                   3764: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3765: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3766: 		 }
                   3767: 		 return $a cmp $b;
                   3768: 	     } (keys(%$fullname))) {
1.324     albertel 3769: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.738     raeburn  3770: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       3771:     }
1.474     albertel 3772:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3773:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3774:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3775: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  3776:     if ($ctr == 0) {
1.442     banghart 3777:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  3778:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3779:                 '<span class="LC_warning">';
                   3780:         if ($env{'form.submitonly'} eq 'all') {
                   3781:             if (grep(/^all$/,@sections)) {
                   3782:                 if (grep(/^all$/,@groups)) {
                   3783:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3784:                                    $stu_status);
                   3785:                 } elsif (grep(/^none$/,@groups)) {
                   3786:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3787:                                    $stu_status); 
                   3788:                 } else {
                   3789:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3790:                                    $group_display,$stu_status);
                   3791:                 }
                   3792:             } elsif (grep(/^none$/,@sections)) {
                   3793:                 if (grep(/^all$/,@groups)) {
                   3794:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3795:                                    $stu_status);
                   3796:                 } elsif (grep(/^none$/,@groups)) {
                   3797:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3798:                                    $stu_status);
                   3799:                 } else {
                   3800:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3801:                                    $group_display,$stu_status);
                   3802:                 }
                   3803:             } else {
                   3804:                 if (grep(/^all$/,@groups)) {
                   3805:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3806:                                    $section_display,$stu_status);
                   3807:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  3808:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  3809:                                    $section_display,$stu_status);
                   3810:                 } else {
                   3811:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3812:                                    $section_display,$group_display,$stu_status);
                   3813:                 }
                   3814:             }
                   3815:         } else {
                   3816:             if (grep(/^all$/,@sections)) {
                   3817:                 if (grep(/^all$/,@groups)) {
                   3818:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3819:                                    $stu_status,$submission_status);
                   3820:                 } elsif (grep(/^none$/,@groups)) {
                   3821:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3822:                                    $stu_status,$submission_status);
                   3823:                 } else {
                   3824:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   3825:                                    $group_display,$stu_status,$submission_status);
                   3826:                 }
                   3827:             } elsif (grep(/^none$/,@sections)) {
                   3828:                 if (grep(/^all$/,@groups)) {
                   3829:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3830:                                    $stu_status,$submission_status);
                   3831:                 } elsif (grep(/^none$/,@groups)) {
                   3832:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3833:                                    $stu_status,$submission_status);
                   3834:                 } else {
                   3835:                     $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.',
                   3836:                                    $group_display,$stu_status,$submission_status);
                   3837:                 }
                   3838:             } else {
                   3839:                 if (grep(/^all$/,@groups)) {
                   3840: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   3841: 	                           $section_display,$stu_status,$submission_status);
                   3842:                 } elsif (grep(/^none$/,@groups)) {
                   3843:                     $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.',
                   3844:                                    $section_display,$stu_status,$submission_status);
                   3845:                 } else {
                   3846:                     $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.',
                   3847:                                    $section_display,$group_display,$stu_status,$submission_status);
                   3848:                 }
                   3849:             }
                   3850:         }
                   3851: 	$result .= '</span><br />';
1.96      albertel 3852:     }
1.41      ng       3853:     return $result;
                   3854: }
                   3855: 
1.738     raeburn  3856: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       3857: sub viewstudentgrade {
1.324     albertel 3858:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3859:     my ($uname,$udom) = split(/:/,$student);
                   3860:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  3861:     my $submitonly = $env{'form.submitonly'};
                   3862:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   3863:         my %partstatus = ();
                   3864:         if (ref($parts) eq 'ARRAY') {
                   3865:             foreach my $apart (@{$parts}) {
                   3866:                 my ($part,$type) = &split_part_type($apart);
                   3867:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   3868:                 $status = 'nothing' if ($status eq '');
                   3869:                 $partstatus{$part}      = $status;
                   3870:                 my $subkey = "resource.$part.submitted_by";
                   3871:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   3872:             }
                   3873:             my $submitted = 0;
                   3874:             my $graded = 0;
                   3875:             my $incorrect = 0;
                   3876:             foreach my $key (keys(%partstatus)) {
                   3877:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   3878:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   3879:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   3880: 
                   3881:                 my $partid = (split(/\./,$key))[1];
                   3882:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   3883:                     $submitted = 0;
                   3884:                 }
                   3885:             }
                   3886:             return if (!$submitted && ($submitonly eq 'yes' ||
                   3887:                                        $submitonly eq 'incorrect' ||
                   3888:                                        $submitonly eq 'graded'));
                   3889:             return if (!$graded && ($submitonly eq 'graded'));
                   3890:             return if (!$incorrect && $submitonly eq 'incorrect');
                   3891:         }
                   3892:     }
                   3893:     if ($submitonly eq 'queued') {
                   3894:         my ($cdom,$cnum) = split(/_/,$courseid);
                   3895:         my %queue_status =
                   3896:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3897:                                                     $udom,$uname);
                   3898:         return if (!defined($queue_status{'gradingqueue'}));
                   3899:     }
                   3900:     $$ctr++;
                   3901:     my %aggregates = ();
1.474     albertel 3902:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  3903: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   3904: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3905: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3906: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3907: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3908:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3909:     foreach my $apart (@$parts) {
                   3910: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3911: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3912:         $result.='<td align="center">';
1.269     raeburn  3913:         my ($aggtries,$totaltries);
                   3914:         unless (exists($aggregates{$part})) {
1.270     albertel 3915: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3916: 	    $aggtries = $totaltries;
1.269     raeburn  3917:             if ($$last_resets{$part}) {  
1.270     albertel 3918:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3919: 					   $part);
                   3920:             }
1.269     raeburn  3921:             $result.='<input type="hidden" name="'.
                   3922:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3923:             $result.='<input type="hidden" name="'.
                   3924:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3925:             $aggregates{$part} = 1;
                   3926:         }
1.41      ng       3927: 	if ($type eq 'awarded') {
1.320     albertel 3928: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3929: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3930: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3931: 	    $result.='<input type="text" name="'.
1.89      albertel 3932: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3933:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3934: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3935: 	} elsif ($type eq 'solved') {
                   3936: 	    my ($status,$foo)=split(/_/,$score,2);
                   3937: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3938: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3939: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3940: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3941: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3942:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3943: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3944: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3945: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3946: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3947: 	} else {
                   3948: 	    $result.='<input type="hidden" name="'.
                   3949: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3950: 		    "\n";
1.233     albertel 3951: 	    $result.='<input type="text" name="'.
1.122     ng       3952: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3953: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3954: 	}
                   3955:     }
1.474     albertel 3956:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3957:     return $result;
1.38      ng       3958: }
                   3959: 
1.44      ng       3960: #--- change scores for all the students in a section/class
                   3961: #    record does not get update if unchanged
1.38      ng       3962: sub editgrades {
1.608     www      3963:     my ($request,$symb) = @_;
1.41      ng       3964: 
1.433     banghart 3965:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3966:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3967:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3968: 
1.477     albertel 3969:     my $result= &Apache::loncommon::start_data_table().
                   3970: 	&Apache::loncommon::start_data_table_header_row().
                   3971: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3972: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3973:     my %scoreptr = (
                   3974: 		    'correct'  =>'correct_by_override',
                   3975: 		    'incorrect'=>'incorrect_by_override',
                   3976: 		    'excused'  =>'excused',
                   3977: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3978:                     'credited' =>'credit_attempted',
1.43      ng       3979: 		    'nothing'  => '',
                   3980: 		    );
1.257     albertel 3981:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3982: 
1.44      ng       3983:     my (@partid);
                   3984:     my %weight = ();
1.54      albertel 3985:     my %columns = ();
1.44      ng       3986:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3987: 
1.582     raeburn  3988:     my $partserror;
                   3989:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3990:     if ($partserror) {
                   3991:         return &navmap_errormsg();
                   3992:     }
1.54      albertel 3993:     my $header;
1.257     albertel 3994:     while ($ctr < $env{'form.totalparts'}) {
                   3995: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3996: 	push(@partid,$partid);
1.257     albertel 3997: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3998: 	$ctr++;
1.54      albertel 3999:     }
1.324     albertel 4000:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 4001:     foreach my $partid (@partid) {
1.478     albertel 4002: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4003: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4004: 	$columns{$partid}=2;
                   4005: 	foreach my $stores (@parts) {
                   4006: 	    my ($part,$type) = &split_part_type($stores);
                   4007: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4008: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4009: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4010: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4011:             my $narrowtext = &mt('Tries');
                   4012: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4013: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4014: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4015: 	    $columns{$partid}+=2;
                   4016: 	}
                   4017:     }
                   4018:     foreach my $partid (@partid) {
1.324     albertel 4019: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4020: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4021: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4022: 	    '</th>';
1.54      albertel 4023: 
1.44      ng       4024:     }
1.477     albertel 4025:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4026: 	&Apache::loncommon::start_data_table_header_row().
                   4027: 	$header.
                   4028: 	&Apache::loncommon::end_data_table_header_row();
                   4029:     my @noupdate;
1.126     ng       4030:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4031:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 4032: 	my $line;
1.257     albertel 4033: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4034: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4035: 	my %newrecord;
                   4036: 	my $updateflag = 0;
1.281     albertel 4037: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 4038: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 4039: 	if (!&canmodify($usec)) {
1.126     ng       4040: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 4041: 	    push(@noupdate,
1.478     albertel 4042: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   4043: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 4044: 	    next;
                   4045: 	}
1.269     raeburn  4046:         my %aggregate = ();
                   4047:         my $aggregateflag = 0;
1.281     albertel 4048: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4049: 	foreach (@partid) {
1.257     albertel 4050: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4051: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4052: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4053: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4054: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4055: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4056: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4057: 	    my $score;
                   4058: 	    if ($partial eq '') {
1.257     albertel 4059: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4060: 	    } elsif ($partial > 0) {
                   4061: 		$score = 'correct_by_override';
                   4062: 	    } elsif ($partial == 0) {
                   4063: 		$score = 'incorrect_by_override';
                   4064: 	    }
1.257     albertel 4065: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4066: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4067: 
1.292     albertel 4068: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4069: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4070: 	    if ($dropMenu eq 'reset status' &&
                   4071: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4072: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4073: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4074: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4075: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4076: 		$updateflag = 1;
1.269     raeburn  4077:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4078:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4079:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4080:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4081:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4082:                     $aggregateflag = 1;
                   4083:                 }
1.139     albertel 4084: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4085: 		$updateflag = 1;
                   4086: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4087: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4088: 		$rec_update++;
1.125     ng       4089: 	    }
                   4090: 
1.93      albertel 4091: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4092: 		'<td align="center">'.$awarded.
                   4093: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4094: 
1.54      albertel 4095: 
                   4096: 	    my $partid=$_;
                   4097: 	    foreach my $stores (@parts) {
                   4098: 		my ($part,$type) = &split_part_type($stores);
                   4099: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4100: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4101: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4102: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4103: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4104: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4105: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4106: 		    $updateflag=1;
                   4107: 		}
1.93      albertel 4108: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4109: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4110: 	    }
1.44      ng       4111: 	}
1.477     albertel 4112: 	$line.="\n";
1.301     albertel 4113: 
                   4114: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4115: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4116: 
1.44      ng       4117: 	if ($updateflag) {
                   4118: 	    $count++;
1.257     albertel 4119: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4120: 				    $udom,$uname);
1.301     albertel 4121: 
                   4122: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4123: 					      $cnum,$udom,$uname)) {
                   4124: 		# need to figure out if should be in queue.
                   4125: 		my %record =  
                   4126: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4127: 					     $udom,$uname);
                   4128: 		my $all_graded = 1;
                   4129: 		my $none_graded = 1;
                   4130: 		foreach my $part (@parts) {
                   4131: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4132: 			$all_graded = 0;
                   4133: 		    } else {
                   4134: 			$none_graded = 0;
                   4135: 		    }
                   4136: 		}
                   4137: 
                   4138: 		if ($all_graded || $none_graded) {
                   4139: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4140: 							   $symb,$cdom,$cnum,
                   4141: 							   $udom,$uname);
                   4142: 		}
                   4143: 	    }
                   4144: 
1.477     albertel 4145: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4146: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4147: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4148: 	    $updateCtr++;
1.93      albertel 4149: 	} else {
1.477     albertel 4150: 	    push(@noupdate,
                   4151: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4152: 	    $noupdateCtr++;
1.44      ng       4153: 	}
1.269     raeburn  4154:         if ($aggregateflag) {
                   4155:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4156: 				  $cdom,$cnum);
1.269     raeburn  4157:         }
1.93      albertel 4158:     }
1.477     albertel 4159:     if (@noupdate) {
1.126     ng       4160: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4161: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4162: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4163: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4164: 	    &mt('No Changes Occurred For the Students Below').
                   4165: 	    '</td>'.
1.477     albertel 4166: 	    &Apache::loncommon::end_data_table_row();
                   4167: 	foreach my $line (@noupdate) {
                   4168: 	    $result.=
                   4169: 		&Apache::loncommon::start_data_table_row().
                   4170: 		$line.
                   4171: 		&Apache::loncommon::end_data_table_row();
                   4172: 	}
1.44      ng       4173:     }
1.614     www      4174:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4175:     my $msg = '<p><b>'.
                   4176: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4177: 	    $rec_update,$count).'</b><br />'.
                   4178: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4179: 	'</b></p>';
1.44      ng       4180:     return $title.$msg.$result;
1.5       albertel 4181: }
1.54      albertel 4182: 
                   4183: sub split_part_type {
                   4184:     my ($partstr) = @_;
                   4185:     my ($temp,@allparts)=split(/_/,$partstr);
                   4186:     my $type=pop(@allparts);
1.439     albertel 4187:     my $part=join('_',@allparts);
1.54      albertel 4188:     return ($part,$type);
                   4189: }
                   4190: 
1.44      ng       4191: #------------- end of section for handling grading by section/class ---------
                   4192: #
                   4193: #----------------------------------------------------------------------------
                   4194: 
1.5       albertel 4195: 
1.44      ng       4196: #----------------------------------------------------------------------------
                   4197: #
                   4198: #-------------------------- Next few routines handles grading by csv upload
                   4199: #
                   4200: #--- Javascript to handle csv upload
1.27      albertel 4201: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4202:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4203:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4204:   &js_escape(\$error1);
                   4205:   &js_escape(\$error2);
1.27      albertel 4206:   return(<<ENDPICK);
                   4207:   function verify(vf) {
                   4208:     var foundsomething=0;
                   4209:     var founduname=0;
1.243     albertel 4210:     var foundID=0;
1.27      albertel 4211:     for (i=0;i<=vf.nfields.value;i++) {
                   4212:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4213:       if (i==0 && tw!=0) { foundID=1; }
                   4214:       if (i==1 && tw!=0) { founduname=1; }
                   4215:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4216:     }
1.246     albertel 4217:     if (founduname==0 && foundID==0) {
                   4218: 	alert('$error1');
                   4219: 	return;
1.27      albertel 4220:     }
                   4221:     if (foundsomething==0) {
1.246     albertel 4222: 	alert('$error2');
                   4223: 	return;
1.27      albertel 4224:     }
                   4225:     vf.submit();
                   4226:   }
                   4227:   function flip(vf,tf) {
                   4228:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4229:     var i;
                   4230:     for (i=0;i<=vf.nfields.value;i++) {
                   4231:       //can not pick the same destination field for both name and domain
                   4232:       if (((i ==0)||(i ==1)) && 
                   4233:           ((tf==0)||(tf==1)) && 
                   4234:           (i!=tf) &&
                   4235:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4236:         eval('vf.f'+i+'.selectedIndex=0;')
                   4237:       }
                   4238:     }
                   4239:   }
                   4240: ENDPICK
                   4241: }
                   4242: 
                   4243: sub csvupload_javascript_forward_associate {
1.573     bisitz   4244:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4245:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4246:   &js_escape(\$error1);
                   4247:   &js_escape(\$error2);
1.27      albertel 4248:   return(<<ENDPICK);
                   4249:   function verify(vf) {
                   4250:     var foundsomething=0;
                   4251:     var founduname=0;
1.243     albertel 4252:     var foundID=0;
1.27      albertel 4253:     for (i=0;i<=vf.nfields.value;i++) {
                   4254:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4255:       if (tw==1) { foundID=1; }
                   4256:       if (tw==2) { founduname=1; }
                   4257:       if (tw>3) { foundsomething=1; }
1.27      albertel 4258:     }
1.246     albertel 4259:     if (founduname==0 && foundID==0) {
                   4260: 	alert('$error1');
                   4261: 	return;
1.27      albertel 4262:     }
                   4263:     if (foundsomething==0) {
1.246     albertel 4264: 	alert('$error2');
                   4265: 	return;
1.27      albertel 4266:     }
                   4267:     vf.submit();
                   4268:   }
                   4269:   function flip(vf,tf) {
                   4270:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4271:     var i;
                   4272:     //can not pick the same destination field twice
                   4273:     for (i=0;i<=vf.nfields.value;i++) {
                   4274:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4275:         eval('vf.f'+i+'.selectedIndex=0;')
                   4276:       }
                   4277:     }
                   4278:   }
                   4279: ENDPICK
                   4280: }
                   4281: 
1.26      albertel 4282: sub csvuploadmap_header {
1.324     albertel 4283:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4284:     my $javascript;
1.257     albertel 4285:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4286: 	$javascript=&csvupload_javascript_reverse_associate();
                   4287:     } else {
                   4288: 	$javascript=&csvupload_javascript_forward_associate();
                   4289:     }
1.45      ng       4290: 
1.418     albertel 4291:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4292:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4293:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4294:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4295:     my $reverse=&mt("Reverse Association");
1.41      ng       4296:     $request->print(<<ENDPICK);
1.632     www      4297: <br />
                   4298: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4299: <input type="hidden" name="associate"  value="" />
                   4300: <input type="hidden" name="phase"      value="three" />
                   4301: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4302: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4303: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4304: <input type="hidden" name="upfile_associate" 
1.257     albertel 4305:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4306: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4307: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4308: <hr />
                   4309: ENDPICK
1.597     wenzelju 4310:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4311:     return '';
1.26      albertel 4312: 
                   4313: }
                   4314: 
                   4315: sub csvupload_fields {
1.582     raeburn  4316:     my ($symb,$errorref) = @_;
                   4317:     my (@parts) = &getpartlist($symb,$errorref);
                   4318:     if (ref($errorref)) {
                   4319:         if ($$errorref) {
                   4320:             return;
                   4321:         }
                   4322:     }
                   4323: 
1.556     weissno  4324:     my @fields=(['ID','Student/Employee ID'],
1.737     raeburn  4325:                 ['clicker','Clicker ID'],
1.243     albertel 4326: 		['username','Student Username'],
                   4327: 		['domain','Student Domain']);
1.324     albertel 4328:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4329:     foreach my $part (sort(@parts)) {
                   4330: 	my @datum;
                   4331: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4332: 	my $name=$part;
                   4333: 	if  (!$display) { $display = $name; }
                   4334: 	@datum=($name,$display);
1.244     albertel 4335: 	if ($name=~/^stores_(.*)_awarded/) {
                   4336: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4337: 	}
1.41      ng       4338: 	push(@fields,\@datum);
                   4339:     }
                   4340:     return (@fields);
1.26      albertel 4341: }
                   4342: 
                   4343: sub csvuploadmap_footer {
1.41      ng       4344:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4345:     my $buttontext = &mt('Assign Grades');
1.41      ng       4346:     $request->print(<<ENDPICK);
1.26      albertel 4347: </table>
                   4348: <input type="hidden" name="nfields" value="$i" />
                   4349: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4350: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4351: </form>
                   4352: ENDPICK
                   4353: }
                   4354: 
1.283     albertel 4355: sub checkforfile_js {
1.638     www      4356:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4357:     &js_escape(\$alertmsg);
1.597     wenzelju 4358:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4359:     function checkUpload(formname) {
                   4360: 	if (formname.upfile.value == "") {
1.539     riegler  4361: 	    alert("$alertmsg");
1.86      ng       4362: 	    return false;
                   4363: 	}
                   4364: 	formname.submit();
                   4365:     }
                   4366: CSVFORMJS
1.283     albertel 4367:     return $result;
                   4368: }
                   4369: 
                   4370: sub upcsvScores_form {
1.608     www      4371:     my ($request,$symb) = @_;
1.283     albertel 4372:     if (!$symb) {return '';}
                   4373:     my $result=&checkforfile_js();
1.632     www      4374:     $result.=&Apache::loncommon::start_data_table().
                   4375:              &Apache::loncommon::start_data_table_header_row().
                   4376:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4377:              &Apache::loncommon::end_data_table_header_row().
                   4378:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4379:     my $upload=&mt("Upload Scores");
1.86      ng       4380:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4381:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4382:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4383:     $result.=<<ENDUPFORM;
1.106     albertel 4384: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4385: <input type="hidden" name="symb" value="$symb" />
                   4386: <input type="hidden" name="command" value="csvuploadmap" />
                   4387: $upfile_select
1.589     bisitz   4388: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4389: </form>
                   4390: ENDUPFORM
1.370     www      4391:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4392:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4393:              '</td>'.
                   4394:             &Apache::loncommon::end_data_table_row().
                   4395:             &Apache::loncommon::end_data_table();
1.86      ng       4396:     return $result;
                   4397: }
                   4398: 
                   4399: 
1.26      albertel 4400: sub csvuploadmap {
1.608     www      4401:     my ($request,$symb)= @_;
1.41      ng       4402:     if (!$symb) {return '';}
1.72      ng       4403: 
1.41      ng       4404:     my $datatoken;
1.257     albertel 4405:     if (!$env{'form.datatoken'}) {
1.41      ng       4406: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4407:     } else {
1.257     albertel 4408: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4409: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4410:     }
1.41      ng       4411:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4412:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4413:     my ($i,$keyfields);
                   4414:     if (@records) {
1.582     raeburn  4415:         my $fieldserror;
                   4416: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4417:         if ($fieldserror) {
                   4418:             $request->print(&navmap_errormsg());
                   4419:             return;
                   4420:         }
1.257     albertel 4421: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4422: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4423: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4424: 							  \@fields);
                   4425: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4426: 	    chop($keyfields);
                   4427: 	} else {
                   4428: 	    unshift(@fields,['none','']);
                   4429: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4430: 							    \@fields);
1.311     banghart 4431:             foreach my $rec (@records) {
                   4432:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4433:                 if (%temp) {
                   4434:                     $keyfields=join(',',sort(keys(%temp)));
                   4435:                     last;
                   4436:                 }
                   4437:             }
1.41      ng       4438: 	}
                   4439:     }
                   4440:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4441: 
1.41      ng       4442:     return '';
1.27      albertel 4443: }
                   4444: 
1.246     albertel 4445: sub csvuploadoptions {
1.608     www      4446:     my ($request,$symb)= @_;
1.632     www      4447:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4448:     $request->print(<<ENDPICK);
                   4449: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4450: <input type="hidden" name="command"    value="csvuploadassign" />
                   4451: <p>
                   4452: <label>
                   4453:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4454:    $overwrite
1.246     albertel 4455: </label>
                   4456: </p>
                   4457: ENDPICK
                   4458:     my %fields=&get_fields();
                   4459:     if (!defined($fields{'domain'})) {
1.257     albertel 4460: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4461: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4462:     }
1.257     albertel 4463:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4464: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4465: 	my $cleankey=$1;
                   4466: 	if ($cleankey eq 'command') { next; }
                   4467: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4468: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4469:     }
                   4470:     # FIXME do a check for any duplicated user ids...
                   4471:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4472:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4473: <hr /></form>'."\n");
1.246     albertel 4474:     return '';
                   4475: }
                   4476: 
                   4477: sub get_fields {
                   4478:     my %fields;
1.257     albertel 4479:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4480:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4481: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4482: 	    if ($env{'form.f'.$i} ne 'none') {
                   4483: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4484: 	    }
                   4485: 	} else {
1.257     albertel 4486: 	    if ($env{'form.f'.$i} ne 'none') {
                   4487: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4488: 	    }
                   4489: 	}
1.27      albertel 4490:     }
1.246     albertel 4491:     return %fields;
                   4492: }
                   4493: 
                   4494: sub csvuploadassign {
1.608     www      4495:     my ($request,$symb)= @_;
1.246     albertel 4496:     if (!$symb) {return '';}
1.345     bowersj2 4497:     my $error_msg = '';
1.246     albertel 4498:     &Apache::loncommon::load_tmp_file($request);
                   4499:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4500:     my %fields=&get_fields();
1.257     albertel 4501:     my $courseid=$env{'request.course.id'};
1.97      albertel 4502:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4503:     my @notallowed;
1.41      ng       4504:     my @skipped;
1.657     raeburn  4505:     my @warnings;
1.41      ng       4506:     my $countdone=0;
                   4507:     foreach my $grade (@gradedata) {
                   4508: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4509: 	my $domain;
                   4510: 	if ($entries{$fields{'domain'}}) {
                   4511: 	    $domain=$entries{$fields{'domain'}};
                   4512: 	} else {
1.257     albertel 4513: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4514: 	}
1.243     albertel 4515: 	$domain=~s/\s//g;
1.41      ng       4516: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4517: 	$username=~s/\s//g;
1.243     albertel 4518: 	if (!$username) {
                   4519: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4520: 	    $id=~s/\s//g;
1.737     raeburn  4521:             if ($id ne '') {
                   4522: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4523: 	        $username=$ids{$id};
                   4524:             } else {
                   4525:                 if ($entries{$fields{'clicker'}}) {
                   4526:                     my $clicker = $entries{$fields{'clicker'}};
                   4527:                     $clicker=~s/\s//g;
                   4528:                     if ($clicker ne '') {
                   4529:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4530:                         if ($clickers{$clicker} ne '') {  
                   4531:                             my $match = 0;
                   4532:                             my @inclass;
                   4533:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4534:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4535:                                     $username = $poss;
                   4536:                                     push(@inclass,$poss);
                   4537:                                     $match ++;
                   4538:                                     
                   4539:                                 }
                   4540:                             }
                   4541:                             if ($match > 1) {
                   4542:                                 undef($username); 
                   4543:                                 $request->print('<p class="LC_warning">'.
                   4544:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4545:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4546:                             }
                   4547:                         }
                   4548:                     }
                   4549:                 }
                   4550:             }
1.243     albertel 4551: 	}
1.41      ng       4552: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4553: 	    my $id=$entries{$fields{'ID'}};
                   4554: 	    $id=~s/\s//g;
1.737     raeburn  4555:             my $clicker = $entries{$fields{'clicker'}};
                   4556:             $clicker=~s/\s//g;
                   4557:             if ($clicker) {
                   4558:                 push(@skipped,"$clicker:$domain");
                   4559: 	    } elsif ($id) {
1.247     albertel 4560: 		push(@skipped,"$id:$domain");
                   4561: 	    } else {
                   4562: 		push(@skipped,"$username:$domain");
                   4563: 	    }
1.41      ng       4564: 	    next;
                   4565: 	}
1.108     albertel 4566: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4567: 	if (!&canmodify($usec)) {
                   4568: 	    push(@notallowed,"$username:$domain");
                   4569: 	    next;
                   4570: 	}
1.244     albertel 4571: 	my %points;
1.41      ng       4572: 	my %grades;
                   4573: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4574: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4575: 		$dest eq 'domain') { next; }
                   4576: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4577: 	    if ($dest=~/stores_(.*)_points/) {
                   4578: 		my $part=$1;
                   4579: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4580: 					      $symb,$domain,$username);
1.345     bowersj2 4581:                 if ($wgt) {
                   4582:                     $entries{$fields{$dest}}=~s/\s//g;
                   4583:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4584:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4585:                                           : 'correct_by_override';
1.638     www      4586:                     if ($pcr>1) {
1.657     raeburn  4587:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4588:                     }
1.345     bowersj2 4589:                     $grades{"resource.$part.awarded"}=$pcr;
                   4590:                     $grades{"resource.$part.solved"}=$award;
                   4591:                     $points{$part}=1;
                   4592:                 } else {
                   4593:                     $error_msg = "<br />" .
                   4594:                         &mt("Some point values were assigned"
                   4595:                             ." for problems with a weight "
                   4596:                             ."of zero. These values were "
                   4597:                             ."ignored.");
                   4598:                 }
1.244     albertel 4599: 	    } else {
                   4600: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4601: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4602: 		my $store_key=$dest;
                   4603: 		$store_key=~s/^stores/resource/;
                   4604: 		$store_key=~s/_/\./g;
                   4605: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4606: 	    }
1.41      ng       4607: 	}
1.508     www      4608: 	if (! %grades) { 
                   4609:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4610:         } else {
                   4611: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4612: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4613: 					   $env{'request.course.id'},
                   4614: 					   $domain,$username);
1.508     www      4615: 	   if ($result eq 'ok') {
1.627     www      4616: # Successfully stored
1.508     www      4617: 	      $request->print('.');
1.627     www      4618: # Remove from grading queue
                   4619:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4620:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4621:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4622:                                              $domain,$username);
                   4623:               $countdone++;
                   4624:            } else {
1.508     www      4625: 	      $request->print("<p><span class=\"LC_error\">".
                   4626:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4627:                                   "$username:$domain",$result)."</span></p>");
                   4628: 	   }
                   4629: 	   $request->rflush();
                   4630:         }
1.41      ng       4631:     }
1.570     www      4632:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4633:     if (@warnings) {
                   4634:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4635:         $request->print(join(', ',@warnings));
                   4636:     }
1.41      ng       4637:     if (@skipped) {
1.571     www      4638: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4639:         $request->print(join(', ',@skipped));
1.106     albertel 4640:     }
                   4641:     if (@notallowed) {
1.571     www      4642: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4643: 	$request->print(join(', ',@notallowed));
1.41      ng       4644:     }
1.106     albertel 4645:     $request->print("<br />\n");
1.345     bowersj2 4646:     return $error_msg;
1.26      albertel 4647: }
1.44      ng       4648: #------------- end of section for handling csv file upload ---------
                   4649: #
                   4650: #-------------------------------------------------------------------
                   4651: #
1.122     ng       4652: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4653: #
                   4654: #--- Select a page/sequence and a student to grade
1.68      ng       4655: sub pickStudentPage {
1.608     www      4656:     my ($request,$symb) = @_;
1.68      ng       4657: 
1.539     riegler  4658:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4659:     &js_escape(\$alertmsg);
1.597     wenzelju 4660:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4661: 
                   4662: function checkPickOne(formname) {
1.76      ng       4663:     if (radioSelection(formname.student) == null) {
1.539     riegler  4664: 	alert("$alertmsg");
1.68      ng       4665: 	return;
                   4666:     }
1.125     ng       4667:     ptr = pullDownSelection(formname.selectpage);
                   4668:     formname.page.value = formname["page"+ptr].value;
                   4669:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4670:     formname.submit();
                   4671: }
                   4672: 
                   4673: LISTJAVASCRIPT
1.118     ng       4674:     &commonJSfunctions($request);
1.608     www      4675: 
1.257     albertel 4676:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4677:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4678:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4679: 
1.398     albertel 4680:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4681: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4682: 
1.80      ng       4683:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4684:     my $map_error;
                   4685:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4686:     if ($map_error) {
                   4687:         $request->print(&navmap_errormsg());
                   4688:         return; 
                   4689:     }
1.137     albertel 4690:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4691: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4692: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4693: 
                   4694:     # Collection of hidden fields
1.70      ng       4695:     my $ctr=0;
1.68      ng       4696:     foreach (@$titles) {
1.700     bisitz   4697:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4698:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4699:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4700:         $ctr++;
1.68      ng       4701:     }
1.700     bisitz   4702:     $result.='<input type="hidden" name="page" />'."\n".
                   4703:         '<input type="hidden" name="title" />'."\n";
                   4704: 
                   4705:     $result.=&build_section_inputs();
                   4706:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4707:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4708: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4709: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4710: 
1.700     bisitz   4711:     # Show grading options
                   4712:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4713:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4714:     $ctr=0;
                   4715:     foreach (@$titles) {
                   4716: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4717: 	$select.='<option value="'.$ctr.'"'.
                   4718: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4719: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4720: 	$ctr++;
                   4721:     }
1.700     bisitz   4722:     $select.= '</select>';
1.68      ng       4723: 
1.700     bisitz   4724:     $result.=
                   4725:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4726:        .$select
                   4727:        .&Apache::lonhtmlcommon::row_closure();
                   4728: 
                   4729:     $result.=
                   4730:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4731:        .'<label><input type="radio" name="vProb" value="no"'
                   4732:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4733:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4734:            .&mt('yes').'</label>'."\n"
                   4735:        .&Apache::lonhtmlcommon::row_closure();
                   4736: 
                   4737:     $result.=
                   4738:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4739:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4740:            .&mt('none').' </label>'."\n"
                   4741:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4742:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4743:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4744:            .&mt('all submissions with details').' </label>'
                   4745:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4746:     
1.700     bisitz   4747:     $result.=
                   4748:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4749:        .'<input type="text" name="CODE" value="" />'
                   4750:        .&Apache::lonhtmlcommon::row_closure(1)
                   4751:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4752: 
1.700     bisitz   4753:     # Show list of students to select for grading
                   4754:     $result.='<br /><input type="button" '.
1.589     bisitz   4755:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4756: 
1.68      ng       4757:     $request->print($result);
                   4758: 
1.485     albertel 4759:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4760: 	&Apache::loncommon::start_data_table().
                   4761: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4762: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4763: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4764: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4765: 	'<th>'.&nameUserString('header').'</th>'.
                   4766: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4767:  
1.76      ng       4768:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4769:     my $ptr = 1;
1.294     albertel 4770:     foreach my $student (sort 
                   4771: 			 {
                   4772: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4773: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4774: 			     }
                   4775: 			     return $a cmp $b;
                   4776: 			 } (keys(%$fullname))) {
1.68      ng       4777: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4778: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4779:                                   : '</td>');
1.126     ng       4780: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4781: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4782: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4783: 	$studentTable.=
                   4784: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4785:                          : '');
1.68      ng       4786: 	$ptr++;
                   4787:     }
1.484     albertel 4788:     if ($ptr%2 == 0) {
                   4789: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4790: 	    &Apache::loncommon::end_data_table_row();
                   4791:     }
                   4792:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4793:     $studentTable.='<input type="button" '.
1.589     bisitz   4794:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4795: 
                   4796:     $request->print($studentTable);
                   4797: 
                   4798:     return '';
                   4799: }
                   4800: 
                   4801: sub getSymbMap {
1.582     raeburn  4802:     my ($map_error) = @_;
1.132     bowersj2 4803:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4804:     unless (ref($navmap)) {
                   4805:         if (ref($map_error)) {
                   4806:             $$map_error = 'navmap';
                   4807:         }
                   4808:         return;
                   4809:     }
1.68      ng       4810:     my %symbx = ();
                   4811:     my @titles = ();
1.117     bowersj2 4812:     my $minder = 0;
                   4813: 
                   4814:     # Gather every sequence that has problems.
1.240     albertel 4815:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4816: 					       1,0,1);
1.117     bowersj2 4817:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4818: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4819: 	    my $title = $minder.'.'.
                   4820: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4821: 	    push(@titles, $title); # minder in case two titles are identical
                   4822: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4823: 	    $minder++;
1.241     albertel 4824: 	}
1.68      ng       4825:     }
                   4826:     return \@titles,\%symbx;
                   4827: }
                   4828: 
1.72      ng       4829: #
                   4830: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4831: sub displayPage {
1.608     www      4832:     my ($request,$symb) = @_;
1.257     albertel 4833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4836:     my $pageTitle = $env{'form.page'};
1.103     albertel 4837:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4838:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4839:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4840: 
                   4841:     #need to make sure we have the correct data for later EXT calls, 
                   4842:     #thus invalidate the cache
                   4843:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4844:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4845:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4846:     &Apache::lonnet::clear_EXT_cache_status();
                   4847: 
1.103     albertel 4848:     if (!&canview($usec)) {
1.712     bisitz   4849:         $request->print(
                   4850:             '<span class="LC_warning">'.
                   4851:             &mt('Unable to view requested student. ([_1])',
                   4852:                     $env{'form.student'}).
                   4853:             '</span>');
                   4854:         return;
1.103     albertel 4855:     }
1.398     albertel 4856:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4857:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4858: 	'</h3>'."\n";
1.500     albertel 4859:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4860:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4861: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4862:     } else {
                   4863: 	delete($env{'form.CODE'});
                   4864:     }
1.71      ng       4865:     &sub_page_js($request);
                   4866:     $request->print($result);
                   4867: 
1.132     bowersj2 4868:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4869:     unless (ref($navmap)) {
                   4870:         $request->print(&navmap_errormsg());
                   4871:         return;
                   4872:     }
1.257     albertel 4873:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4874:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4875:     if (!$map) {
1.485     albertel 4876: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4877: 	return; 
                   4878:     }
1.68      ng       4879:     my $iterator = $navmap->getIterator($map->map_start(),
                   4880: 					$map->map_finish());
                   4881: 
1.71      ng       4882:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4883: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4884: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4885: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4886: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4887: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4888: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4889: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4890: 
1.382     albertel 4891:     if (defined($env{'form.CODE'})) {
                   4892: 	$studentTable.=
                   4893: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4894:     }
1.381     albertel 4895:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4896: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4897: 
1.594     bisitz   4898:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4899:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4900:         '</span>'."\n".
1.484     albertel 4901: 	&Apache::loncommon::start_data_table().
                   4902: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4903: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4904: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4905: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4906: 
1.329     albertel 4907:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4908:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4909:     $iterator->next(); # skip the first BEGIN_MAP
                   4910:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4911:     while ($depth > 0) {
1.68      ng       4912:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4913:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4914: 
1.385     albertel 4915:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4916: 	    my $parts = $curRes->parts();
1.68      ng       4917:             my $title = $curRes->compTitle();
1.71      ng       4918: 	    my $symbx = $curRes->symb();
1.484     albertel 4919: 	    $studentTable.=
                   4920: 		&Apache::loncommon::start_data_table_row().
                   4921: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4922: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4923: 		                        : '<br />('.&mt('[_1]parts',
                   4924: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4925: 		 ).
                   4926: 		 '</td>';
1.71      ng       4927: 	    $studentTable.='<td valign="top">';
1.382     albertel 4928: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4929: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4930: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4931: 					     undef,'both',\%form);
1.71      ng       4932: 	    } else {
1.382     albertel 4933: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4934: 		$companswer =~ s|<form(.*?)>||g;
                   4935: 		$companswer =~ s|</form>||g;
1.71      ng       4936: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4937: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4938: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4939: #		}
1.116     ng       4940: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4941: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4942: 	    }
                   4943: 
1.257     albertel 4944: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4945: 
1.257     albertel 4946: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4947: 		if ($record{'version'} eq '') {
1.485     albertel 4948: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4949: 		} else {
1.116     ng       4950: 		    my %responseType = ();
                   4951: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4952: 			my @responseIds =$curRes->responseIds($partid);
                   4953: 			my @responseType =$curRes->responseType($partid);
                   4954: 			my %responseIds;
                   4955: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4956: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4957: 			}
                   4958: 			$responseType{$partid} = \%responseIds;
1.116     ng       4959: 		    }
1.148     albertel 4960: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4961: 
1.71      ng       4962: 		}
1.257     albertel 4963: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4964: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  4965:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       4966: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4967: 									$env{'request.course.id'},
1.726     raeburn  4968: 									'','.submission',undef,
                   4969:                                                                         $usec,$identifier);
1.71      ng       4970:  
                   4971: 	    }
1.103     albertel 4972: 	    if (&canmodify($usec)) {
1.585     bisitz   4973:             $studentTable.=&gradeBox_start();
1.103     albertel 4974: 		foreach my $partid (@{$parts}) {
                   4975: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4976: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4977: 		    $question++;
                   4978: 		}
1.585     bisitz   4979:             $studentTable.=&gradeBox_end();
1.196     albertel 4980: 		$prob++;
1.71      ng       4981: 	    }
                   4982: 	    $studentTable.='</td></tr>';
1.68      ng       4983: 
1.103     albertel 4984: 	}
1.68      ng       4985:         $curRes = $iterator->next();
                   4986:     }
                   4987: 
1.589     bisitz   4988:     $studentTable.=
                   4989:         '</table>'."\n".
                   4990:         '<input type="button" value="'.&mt('Save').'" '.
                   4991:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4992:         '</form>'."\n";
1.71      ng       4993:     $request->print($studentTable);
                   4994: 
                   4995:     return '';
1.119     ng       4996: }
                   4997: 
                   4998: sub displaySubByDates {
1.148     albertel 4999:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5000:     my $isCODE=0;
1.335     albertel 5001:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5002:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5003:     my $studentTable=&Apache::loncommon::start_data_table().
                   5004: 	&Apache::loncommon::start_data_table_header_row().
                   5005: 	'<th>'.&mt('Date/Time').'</th>'.
                   5006: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5007:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5008: 	'<th>'.&mt('Submission').'</th>'.
                   5009: 	'<th>'.&mt('Status').'</th>'.
                   5010: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5011:     my ($version);
                   5012:     my %mark;
1.148     albertel 5013:     my %orders;
1.119     ng       5014:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5015:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5016: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5017:     }
1.335     albertel 5018: 
                   5019:     my $interaction;
1.525     raeburn  5020:     my $no_increment = 1;
1.735     raeburn  5021:     my (%lastrndseed,%lasttype);
1.119     ng       5022:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5023: 	my $timestamp = 
                   5024: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5025: 	if (exists($$record{$version.':resource.0.version'})) {
                   5026: 	    $interaction = $$record{$version.':resource.0.version'};
                   5027: 	}
1.671     raeburn  5028:         if ($isTask && $env{'form.previousversion'}) {
                   5029:             next unless ($interaction == $env{'form.previousversion'});
                   5030:         }
1.335     albertel 5031: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5032: 		             : "$version:resource");
1.467     albertel 5033: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5034: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5035: 	if ($isCODE) {
                   5036: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5037: 	}
1.671     raeburn  5038:         if ($isTask) {
                   5039:             $studentTable.='<td>'.$interaction.'</td>';
                   5040:         }
1.119     ng       5041: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5042: 	my @displaySub = ();
                   5043: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5044:             my ($hidden,$type);
                   5045:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5046:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5047:                 $hidden = 1;
                   5048:             }
1.335     albertel 5049: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   5050: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5051: 	    
1.122     ng       5052: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5053: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5054: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5055: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5056: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5057:                     
1.335     albertel 5058: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5059: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  5060:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5061:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5062:                                    .' <span class="LC_internal_info">'
1.625     www      5063:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5064:                                    .'</span>'
                   5065:                                    .' <b>';
1.596     raeburn  5066:                     if ($hidden) {
                   5067:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5068:                     } else {
1.640     raeburn  5069:                         my ($trial,$rndseed,$newvariation);
                   5070:                         if ($type eq 'randomizetry') {
                   5071:                             $trial = $$record{"$where.$partid.tries"};
1.733     raeburn  5072:                             $rndseed = $$record{"$where.$partid.rndseed"};
1.640     raeburn  5073:                         }
1.596     raeburn  5074: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5075: 			    $displaySub[0].=&mt('Trial not counted');
                   5076: 		        } else {
                   5077: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5078: 					    $$record{"$where.$partid.tries"});
1.734     raeburn  5079:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
1.735     raeburn  5080:                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5081:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.640     raeburn  5082:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5083:                                 }
                   5084:                             }
                   5085:                             $lastrndseed{$partid} = $rndseed;
1.735     raeburn  5086:                             $lasttype{$partid} = $type;
1.596     raeburn  5087: 		        }
                   5088: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5089:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5090: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  5091: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5092: 			    $orders{$partid}->{$responseId}=
                   5093: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  5094:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5095: 		        }
1.640     raeburn  5096: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5097: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  5098: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5099:                     }
1.147     albertel 5100: 		}
                   5101: 	    }
1.335     albertel 5102: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5103: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5104: 				    $$record{"$where.$partid.checkedin"},
                   5105: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5106: 					'<br />';
1.335     albertel 5107: 	    }
                   5108: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5109: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5110: 		    lc($$record{"$where.$partid.award"}).' '.
                   5111: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5112: 		    '<br />';
                   5113: 	    }
1.335     albertel 5114: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5115: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5116: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5117: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5118: 		$displaySub[2].=
                   5119: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5120: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5121: 	    }
                   5122: 	}
                   5123: 	# needed because old essay regrader has not parts info
                   5124: 	if (exists $$record{"$version:resource.regrader"}) {
                   5125: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5126: 	}
                   5127: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5128: 	if ($displaySub[2]) {
1.467     albertel 5129: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5130: 	}
1.467     albertel 5131: 	$studentTable.='&nbsp;</td>'.
                   5132: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5133:     }
1.467     albertel 5134:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5135:     return $studentTable;
1.71      ng       5136: }
                   5137: 
                   5138: sub updateGradeByPage {
1.608     www      5139:     my ($request,$symb) = @_;
1.71      ng       5140: 
1.257     albertel 5141:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5142:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5143:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5144:     my $pageTitle = $env{'form.page'};
1.103     albertel 5145:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5146:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5147:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5148:     if (!&canmodify($usec)) {
1.526     raeburn  5149: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5150: 	return;
                   5151:     }
1.398     albertel 5152:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5153:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5154: 	'</h3>'."\n";
1.70      ng       5155: 
1.68      ng       5156:     $request->print($result);
                   5157: 
1.582     raeburn  5158: 
1.132     bowersj2 5159:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5160:     unless (ref($navmap)) {
                   5161:         $request->print(&navmap_errormsg());
                   5162:         return;
                   5163:     }
1.257     albertel 5164:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5165:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5166:     if (!$map) {
1.527     raeburn  5167: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5168: 	return; 
                   5169:     }
1.71      ng       5170:     my $iterator = $navmap->getIterator($map->map_start(),
                   5171: 					$map->map_finish());
1.70      ng       5172: 
1.484     albertel 5173:     my $studentTable=
                   5174: 	&Apache::loncommon::start_data_table().
                   5175: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5176: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5177: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5178: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5179: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5180: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5181: 
                   5182:     $iterator->next(); # skip the first BEGIN_MAP
                   5183:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5184:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5185:     while ($depth > 0) {
1.71      ng       5186:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5187:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5188: 
1.385     albertel 5189:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5190: 	    my $parts = $curRes->parts();
1.71      ng       5191:             my $title = $curRes->compTitle();
                   5192: 	    my $symbx = $curRes->symb();
1.484     albertel 5193: 	    $studentTable.=
                   5194: 		&Apache::loncommon::start_data_table_row().
                   5195: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5196: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5197:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5198: 		.')').'</td>';
1.71      ng       5199: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5200: 
                   5201: 	    my %newrecord=();
                   5202: 	    my @displayPts=();
1.269     raeburn  5203:             my %aggregate = ();
                   5204:             my $aggregateflag = 0;
1.726     raeburn  5205:             if ($env{'form.HIDE'.$prob}) {
                   5206:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5207:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5208:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5209:                 $hideflag += $numchgs;
                   5210:             }
1.71      ng       5211: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5212: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5213: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5214: 
1.257     albertel 5215: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5216: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5217: 		my $partial = $newpts/$wgt;
                   5218: 		my $score;
                   5219: 		if ($partial > 0) {
                   5220: 		    $score = 'correct_by_override';
1.125     ng       5221: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5222: 		    $score = 'incorrect_by_override';
                   5223: 		}
1.257     albertel 5224: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5225: 		if ($dropMenu eq 'excused') {
1.71      ng       5226: 		    $partial = '';
                   5227: 		    $score = 'excused';
1.125     ng       5228: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5229: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5230: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5231: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5232: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5233: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5234: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5235: 		    $changeflag++;
                   5236: 		    $newpts = '';
1.269     raeburn  5237:                     
                   5238:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5239:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5240:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5241:                     if ($aggtries > 0) {
                   5242:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5243:                         $aggregateflag = 1;
                   5244:                     }
1.71      ng       5245: 		}
1.324     albertel 5246: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5247: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5248: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5249: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5250: 		    '&nbsp;<br />';
1.526     raeburn  5251: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5252: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5253: 		    '&nbsp;<br />';
1.71      ng       5254: 		$question++;
1.380     albertel 5255: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5256: 
1.71      ng       5257: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5258: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5259: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5260: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5261: 
                   5262: 		$changeflag++;
                   5263: 	    }
                   5264: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5265: 		my %record = 
                   5266: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5267: 					     $udom,$uname);
                   5268: 
                   5269: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5270: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5271: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5272: 		    $newrecord{'resource.CODE'} = '';
                   5273: 		}
1.257     albertel 5274: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5275: 					$udom,$uname);
1.382     albertel 5276: 		%record = &Apache::lonnet::restore($symbx,
                   5277: 						   $env{'request.course.id'},
                   5278: 						   $udom,$uname);
1.380     albertel 5279: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5280: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5281: 	    }
1.380     albertel 5282: 	    
1.269     raeburn  5283:             if ($aggregateflag) {
                   5284:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5285:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5286:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5287:             }
1.125     ng       5288: 
1.71      ng       5289: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5290: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5291: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5292: 
1.196     albertel 5293: 	    $prob++;
1.68      ng       5294: 	}
1.71      ng       5295:         $curRes = $iterator->next();
1.68      ng       5296:     }
1.98      albertel 5297: 
1.484     albertel 5298:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5299:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5300: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5301: 		  $changeflag).'<br />');
                   5302:     my $hidemsg=($hideflag == 0 ? '' :
                   5303:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5304:                      $hideflag).'<br />');
                   5305:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5306: 
1.70      ng       5307:     return '';
                   5308: }
                   5309: 
1.72      ng       5310: #-------- end of section for handling grading by page/sequence ---------
                   5311: #
                   5312: #-------------------------------------------------------------------
                   5313: 
1.581     www      5314: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5315: #
                   5316: #------ start of section for handling grading by page/sequence ---------
                   5317: 
1.423     albertel 5318: =pod
                   5319: 
                   5320: =head1 Bubble sheet grading routines
                   5321: 
1.424     albertel 5322:   For this documentation:
                   5323: 
                   5324:    'scanline' refers to the full line of characters
                   5325:    from the file that we are parsing that represents one entire sheet
                   5326: 
                   5327:    'bubble line' refers to the data
1.659     raeburn  5328:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5329: 
                   5330: 
1.659     raeburn  5331: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5332: into a course. When a user wants to grade, they select a
1.659     raeburn  5333: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5334: one of the predefined configurations for what each scanline looks
                   5335: like.
                   5336: 
                   5337: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5338: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5339: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5340: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5341: invalid student/employee ID
1.424     albertel 5342: 
                   5343: If the CODE option is used that determines the randomization of the
1.556     weissno  5344: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5345: username:domain.
                   5346: 
                   5347: During the validation phase the instructor can choose to skip scanlines. 
                   5348: 
1.659     raeburn  5349: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5350: 
                   5351:   scantron_original_filename (unmodified original file)
                   5352:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5353:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5354: 
                   5355: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5356: correction information that isn't representable in the bubblesheet
1.424     albertel 5357: file (see &scantron_getfile() for more information)
                   5358: 
                   5359: After all scanlines are either valid, marked as valid or skipped, then
                   5360: foreach line foreach problem in the picked sequence, an ssi request is
                   5361: made that simulates a user submitting their selected letter(s) against
                   5362: the homework problem.
1.423     albertel 5363: 
                   5364: =over 4
                   5365: 
                   5366: 
                   5367: 
                   5368: =item defaultFormData
                   5369: 
                   5370:   Returns html hidden inputs used to hold context/default values.
                   5371: 
                   5372:  Arguments:
                   5373:   $symb - $symb of the current resource 
                   5374: 
                   5375: =cut
1.422     foxr     5376: 
1.81      albertel 5377: sub defaultFormData {
1.324     albertel 5378:     my ($symb)=@_;
1.613     www      5379:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5380: }
                   5381: 
1.447     foxr     5382: 
1.423     albertel 5383: =pod 
                   5384: 
                   5385: =item getSequenceDropDown
                   5386: 
                   5387:    Return html dropdown of possible sequences to grade
                   5388:  
                   5389:  Arguments:
1.582     raeburn  5390:    $symb - $symb of the current resource
                   5391:    $map_error - ref to scalar which will container error if
                   5392:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5393: 
                   5394: =cut
1.422     foxr     5395: 
1.75      albertel 5396: sub getSequenceDropDown {
1.582     raeburn  5397:     my ($symb,$map_error)=@_;
1.75      albertel 5398:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5399:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5400:     if (ref($map_error)) {
                   5401:         return if ($$map_error);
                   5402:     }
1.137     albertel 5403:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5404:     my $ctr=0;
                   5405:     foreach (@$titles) {
                   5406: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5407: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5408: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5409: 	    '>'.$showtitle.'</option>'."\n";
                   5410: 	$ctr++;
                   5411:     }
                   5412:     $result.= '</select>';
                   5413:     return $result;
                   5414: }
                   5415: 
1.495     albertel 5416: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5417:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5418: 
                   5419: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5420: 
1.509     raeburn  5421: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5422:                                    # matchresponse or rankresponse, where 
                   5423:                                    # an individual response can have multiple 
                   5424:                                    # lines
1.503     raeburn  5425: 
                   5426: my %responsetype_per_response;     # responsetype for each response
                   5427: 
1.691     raeburn  5428: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5429:                                    # numbered response. Needed when randomorder
                   5430:                                    # or randompick are in use. Key is ID, value 
                   5431:                                    # is response number.
                   5432: 
1.495     albertel 5433: # Save and restore the bubble lines array to the form env.
                   5434: 
                   5435: 
                   5436: sub save_bubble_lines {
                   5437:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5438: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5439: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5440: 	    $first_bubble_line{$line};
1.503     raeburn  5441:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5442:             $subdivided_bubble_lines{$line};
                   5443:         $env{"form.scantron.responsetype.$line"} =
                   5444:             $responsetype_per_response{$line};
1.495     albertel 5445:     }
1.691     raeburn  5446:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5447:         my $line = $masterseq_id_responsenum{$resid};
                   5448:         $env{"form.scantron.residpart.$line"} = $resid;
                   5449:     }
1.495     albertel 5450: }
                   5451: 
                   5452: 
                   5453: sub restore_bubble_lines {
                   5454:     my $line = 0;
                   5455:     %bubble_lines_per_response = ();
1.691     raeburn  5456:     %masterseq_id_responsenum = ();
1.495     albertel 5457:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5458: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5459: 	$bubble_lines_per_response{$line} = $value;
                   5460: 	$first_bubble_line{$line}  =
                   5461: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5462:         $subdivided_bubble_lines{$line} =
                   5463:             $env{"form.scantron.sub_bubblelines.$line"};
                   5464:         $responsetype_per_response{$line} =
                   5465:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5466:         my $id = $env{"form.scantron.residpart.$line"};
                   5467:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5468: 	$line++;
                   5469:     }
                   5470: }
                   5471: 
1.423     albertel 5472: =pod 
                   5473: 
                   5474: =item scantron_filenames
                   5475: 
                   5476:    Returns a list of the scantron files in the current course 
                   5477: 
                   5478: =cut
1.422     foxr     5479: 
1.202     albertel 5480: sub scantron_filenames {
1.257     albertel 5481:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5482:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5483:     my $getpropath = 1;
1.662     raeburn  5484:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5485:                                                         $cname,$getpropath);
1.202     albertel 5486:     my @possiblenames;
1.662     raeburn  5487:     if (ref($dirlist) eq 'ARRAY') {
                   5488:         foreach my $filename (sort(@{$dirlist})) {
                   5489: 	    ($filename)=split(/&/,$filename);
                   5490: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5491: 	    $filename=~s/^scantron_orig_//;
                   5492: 	    push(@possiblenames,$filename);
                   5493:         }
1.202     albertel 5494:     }
                   5495:     return @possiblenames;
                   5496: }
                   5497: 
1.423     albertel 5498: =pod 
                   5499: 
                   5500: =item scantron_uploads
                   5501: 
                   5502:    Returns  html drop-down list of scantron files in current course.
                   5503: 
                   5504:  Arguments:
                   5505:    $file2grade - filename to set as selected in the dropdown
                   5506: 
                   5507: =cut
1.422     foxr     5508: 
1.202     albertel 5509: sub scantron_uploads {
1.209     ng       5510:     my ($file2grade) = @_;
1.202     albertel 5511:     my $result=	'<select name="scantron_selectfile">';
                   5512:     $result.="<option></option>";
                   5513:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5514: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5515:     }
                   5516:     $result.="</select>";
                   5517:     return $result;
                   5518: }
                   5519: 
1.423     albertel 5520: =pod 
                   5521: 
                   5522: =item scantron_scantab
                   5523: 
                   5524:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5525:   file.
                   5526: 
                   5527: =cut
1.422     foxr     5528: 
1.82      albertel 5529: sub scantron_scantab {
                   5530:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5531:     $result.='<option></option>'."\n";
1.518     raeburn  5532:     my @lines = &get_scantronformat_file();
                   5533:     if (@lines > 0) {
                   5534:         foreach my $line (@lines) {
                   5535:             next if (($line =~ /^\#/) || ($line eq ''));
                   5536: 	    my ($name,$descrip)=split(/:/,$line);
                   5537: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5538:         }
1.82      albertel 5539:     }
                   5540:     $result.='</select>'."\n";
1.518     raeburn  5541:     return $result;
                   5542: }
                   5543: 
                   5544: =pod
                   5545: 
                   5546: =item get_scantronformat_file
                   5547: 
                   5548:   Returns an array containing lines from the scantron format file for
                   5549:   the domain of the course.
                   5550: 
                   5551:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5552:   lines are from this file.
                   5553: 
                   5554:   Otherwise, if a default.tab has been published in RES space by the 
                   5555:   domainconfig user, lines are from this file.
                   5556: 
                   5557:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5558:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5559: 
1.518     raeburn  5560: =cut
                   5561: 
                   5562: sub get_scantronformat_file {
                   5563:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5564:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5565:     my $gottab = 0;
                   5566:     my @lines;
                   5567:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5568:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5569:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5570:             if ($formatfile ne '-1') {
                   5571:                 @lines = split("\n",$formatfile,-1);
                   5572:                 $gottab = 1;
                   5573:             }
                   5574:         }
                   5575:     }
                   5576:     if (!$gottab) {
                   5577:         my $confname = $cdom.'-domainconfig';
                   5578:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5579:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5580:         if ($formatfile ne '-1') {
                   5581:             @lines = split("\n",$formatfile,-1);
                   5582:             $gottab = 1;
                   5583:         }
                   5584:     }
                   5585:     if (!$gottab) {
1.519     raeburn  5586:         my @domains = &Apache::lonnet::current_machine_domains();
                   5587:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5588:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5589:             @lines = <$fh>;
                   5590:             close($fh);
                   5591:         } else {
                   5592:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5593:             @lines = <$fh>;
                   5594:             close($fh);
                   5595:         }
1.518     raeburn  5596:     }
                   5597:     return @lines;
1.82      albertel 5598: }
                   5599: 
1.423     albertel 5600: =pod 
                   5601: 
                   5602: =item scantron_CODElist
                   5603: 
                   5604:   Returns html drop down of the saved CODE lists from current course,
                   5605:   generated from earlier printings.
                   5606: 
                   5607: =cut
1.422     foxr     5608: 
1.186     albertel 5609: sub scantron_CODElist {
1.257     albertel 5610:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5611:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5612:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5613:     my $namechoice='<option></option>';
1.225     albertel 5614:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5615: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5616: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5617: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5618:     }
                   5619:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5620:     return $namechoice;
                   5621: }
                   5622: 
1.423     albertel 5623: =pod 
                   5624: 
                   5625: =item scantron_CODEunique
                   5626: 
                   5627:   Returns the html for "Each CODE to be used once" radio.
                   5628: 
                   5629: =cut
1.422     foxr     5630: 
1.186     albertel 5631: sub scantron_CODEunique {
1.532     bisitz   5632:     my $result='<span class="LC_nobreak">
1.272     albertel 5633:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5634:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5635:                 </span>
1.532     bisitz   5636:                 <span class="LC_nobreak">
1.272     albertel 5637:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5638:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5639:                 </span>';
1.186     albertel 5640:     return $result;
                   5641: }
1.423     albertel 5642: 
                   5643: =pod 
                   5644: 
                   5645: =item scantron_selectphase
                   5646: 
1.659     raeburn  5647:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5648:   Allows for - starting a grading run.
1.424     albertel 5649:              - downloading existing scan data (original, corrected
1.423     albertel 5650:                                                 or skipped info)
                   5651: 
                   5652:              - uploading new scan data
                   5653: 
                   5654:  Arguments:
                   5655:   $r          - The Apache request object
                   5656:   $file2grade - name of the file that contain the scanned data to score
                   5657: 
                   5658: =cut
1.186     albertel 5659: 
1.75      albertel 5660: sub scantron_selectphase {
1.608     www      5661:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5662:     if (!$symb) {return '';}
1.582     raeburn  5663:     my $map_error;
                   5664:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5665:     if ($map_error) {
                   5666:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5667:         return;
                   5668:     }
1.324     albertel 5669:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5670:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5671:     my $format_selector=&scantron_scantab();
1.186     albertel 5672:     my $CODE_selector=&scantron_CODElist();
                   5673:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5674:     my $result;
1.422     foxr     5675: 
1.513     foxr     5676:     $ssi_error = 0;
                   5677: 
1.606     wenzelju 5678:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5679:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5680: 
                   5681: 	# Chunk of form to prompt for a scantron file upload.
                   5682: 
                   5683:         $r->print('
                   5684:     <br />
                   5685:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5686:        '.&Apache::loncommon::start_data_table_header_row().'
                   5687:             <th>
                   5688:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5689:             </th>
                   5690:        '.&Apache::loncommon::end_data_table_header_row().'
                   5691:        '.&Apache::loncommon::start_data_table_row().'
                   5692:             <td>
                   5693: ');
1.608     www      5694:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5695:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5696:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5697:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5698:     &js_escape(\$alertmsg);
1.606     wenzelju 5699:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5700:     function checkUpload(formname) {
                   5701: 	if (formname.upfile.value == "") {
1.736     damieng  5702: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5703: 	    return false;
                   5704: 	}
                   5705: 	formname.submit();
                   5706:     }'));
                   5707:     $r->print('
                   5708:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5709:                 '.$default_form_data.'
                   5710:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5711:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5712:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5713:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5714:                 <br />
                   5715:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5716:               </form>
                   5717: ');
                   5718: 
                   5719:         $r->print('
                   5720:             </td>
                   5721:        '.&Apache::loncommon::end_data_table_row().'
                   5722:        '.&Apache::loncommon::end_data_table().'
                   5723: ');
                   5724:     }
                   5725: 
1.422     foxr     5726:     # Chunk of form to prompt for a file to grade and how:
                   5727: 
1.489     albertel 5728:     $result.= '
                   5729:     <br />
                   5730:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5731:     <input type="hidden" name="command" value="scantron_warning" />
                   5732:     '.$default_form_data.'
                   5733:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5734:        '.&Apache::loncommon::start_data_table_header_row().'
                   5735:             <th colspan="2">
1.492     albertel 5736:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5737:             </th>
                   5738:        '.&Apache::loncommon::end_data_table_header_row().'
                   5739:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5740:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5741:        '.&Apache::loncommon::end_data_table_row().'
                   5742:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5743:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5744:        '.&Apache::loncommon::end_data_table_row().'
                   5745:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5746:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5747:        '.&Apache::loncommon::end_data_table_row().'
                   5748:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5749:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5750:        '.&Apache::loncommon::end_data_table_row().'
                   5751:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5752:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5753:        '.&Apache::loncommon::end_data_table_row().'
                   5754:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5755: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5756:             <td>
1.492     albertel 5757: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5758:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5759:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5760: 	    </td>
1.489     albertel 5761:        '.&Apache::loncommon::end_data_table_row().'
                   5762:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5763:             <td colspan="2">
1.572     www      5764:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5765:             </td>
1.489     albertel 5766:        '.&Apache::loncommon::end_data_table_row().'
                   5767:     '.&Apache::loncommon::end_data_table().'
                   5768:     </form>
                   5769: ';
1.162     albertel 5770:    
                   5771:     $r->print($result);
                   5772: 
1.422     foxr     5773: 
                   5774: 
                   5775:     # Chunk of the form that prompts to view a scoring office file,
                   5776:     # corrected file, skipped records in a file.
                   5777: 
1.489     albertel 5778:     $r->print('
                   5779:    <br />
                   5780:    <form action="/adm/grades" name="scantron_download">
                   5781:      '.$default_form_data.'
                   5782:      <input type="hidden" name="command" value="scantron_download" />
                   5783:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5784:        '.&Apache::loncommon::start_data_table_header_row().'
                   5785:               <th>
1.492     albertel 5786:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5787:               </th>
                   5788:        '.&Apache::loncommon::end_data_table_header_row().'
                   5789:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5790:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5791:                 <br />
1.492     albertel 5792:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5793:        '.&Apache::loncommon::end_data_table_row().'
                   5794:      '.&Apache::loncommon::end_data_table().'
                   5795:    </form>
                   5796:    <br />
                   5797: ');
1.162     albertel 5798: 
1.457     banghart 5799:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5800: 
1.694     bisitz   5801:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5802:              $default_form_data."\n".
                   5803:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5804:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5805:              '<th colspan="2">
1.572     www      5806:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5807:              '</th>'."\n".
                   5808:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5809:               &Apache::loncommon::start_data_table_row()."\n".
                   5810:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5811:               '<td> '.$sequence_selector.' </td>'.
                   5812:               &Apache::loncommon::end_data_table_row()."\n".
                   5813:               &Apache::loncommon::start_data_table_row()."\n".
                   5814:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5815:               '<td> '.$file_selector.' </td>'."\n".
                   5816:               &Apache::loncommon::end_data_table_row()."\n".
                   5817:               &Apache::loncommon::start_data_table_row()."\n".
                   5818:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5819:               '<td> '.$format_selector.' </td>'."\n".
                   5820:               &Apache::loncommon::end_data_table_row()."\n".
                   5821:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5822:               '<td> '.&mt('Options').' </td>'."\n".
                   5823:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5824:               &Apache::loncommon::end_data_table_row()."\n".
                   5825:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5826:               '<td colspan="2">'."\n".
                   5827:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5828:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5829:               '</td>'."\n".
                   5830:               &Apache::loncommon::end_data_table_row()."\n".
                   5831:               &Apache::loncommon::end_data_table()."\n".
                   5832:               '</form><br />');
                   5833:     return;
1.75      albertel 5834: }
                   5835: 
1.423     albertel 5836: =pod
                   5837: 
                   5838: =item get_scantron_config
                   5839: 
1.711     bisitz   5840:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5841:    hash of configuration file fields.
                   5842: 
                   5843:  Arguments:
                   5844:     which - the name of the configuration to parse from the file.
                   5845: 
                   5846: 
                   5847:  Returns:
                   5848:             If the named configuration is not in the file, an empty
                   5849:             hash is returned.
                   5850:     a hash with the fields
                   5851:       name         - internal name for the this configuration setup
                   5852:       description  - text to display to operator that describes this config
                   5853:       CODElocation - if 0 or the string 'none'
                   5854:                           - no CODE exists for this config
                   5855:                      if -1 || the string 'letter'
                   5856:                           - a CODE exists for this config and is
                   5857:                             a string of letters
                   5858:                      Unsupported value (but planned for future support)
                   5859:                           if a positive integer
                   5860:                                - The CODE exists as the first n items from
                   5861:                                  the question section of the form
                   5862:                           if the string 'number'
                   5863:                                - The CODE exists for this config and is
                   5864:                                  a string of numbers
                   5865:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5866:                      the CODE starts
                   5867:       CODElength  - length of the CODE
1.573     bisitz   5868:       IDstart     - column where the student/employee ID starts
1.556     weissno  5869:       IDlength    - length of the student/employee ID info
1.423     albertel 5870:       Qstart      - column where the information from the bubbled
                   5871:                     'questions' start
                   5872:       Qlength     - number of columns comprising a single bubble line from
                   5873:                     the sheet. (usually either 1 or 10)
1.424     albertel 5874:       Qon         - either a single character representing the character used
1.423     albertel 5875:                     to signal a bubble was chosen in the positional setup, or
                   5876:                     the string 'letter' if the letter of the chosen bubble is
                   5877:                     in the final, or 'number' if a number representing the
                   5878:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5879:       Qoff        - the character used to represent that a bubble was
                   5880:                     left blank
1.423     albertel 5881:       PaperID     - if the scanning process generates a unique number for each
                   5882:                     sheet scanned the column that this ID number starts in
                   5883:       PaperIDlength - number of columns that comprise the unique ID number
                   5884:                       for the sheet of paper
1.424     albertel 5885:       FirstName   - column that the first name starts in
1.423     albertel 5886:       FirstNameLength - number of columns that the first name spans
                   5887:  
                   5888:       LastName    - column that the last name starts in
                   5889:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5890:       BubblesPerRow - number of bubbles available in each row used to 
                   5891:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5892: 
1.423     albertel 5893: =cut
1.422     foxr     5894: 
1.82      albertel 5895: sub get_scantron_config {
                   5896:     my ($which) = @_;
1.518     raeburn  5897:     my @lines = &get_scantronformat_file();
1.82      albertel 5898:     my %config;
1.157     albertel 5899:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5900:     foreach my $line (@lines) {
1.82      albertel 5901: 	my ($name,$descrip)=split(/:/,$line);
                   5902: 	if ($name ne $which ) { next; }
                   5903: 	chomp($line);
                   5904: 	my @config=split(/:/,$line);
                   5905: 	$config{'name'}=$config[0];
                   5906: 	$config{'description'}=$config[1];
                   5907: 	$config{'CODElocation'}=$config[2];
                   5908: 	$config{'CODEstart'}=$config[3];
                   5909: 	$config{'CODElength'}=$config[4];
                   5910: 	$config{'IDstart'}=$config[5];
                   5911: 	$config{'IDlength'}=$config[6];
                   5912: 	$config{'Qstart'}=$config[7];
1.497     foxr     5913:  	$config{'Qlength'}=$config[8];
1.82      albertel 5914: 	$config{'Qoff'}=$config[9];
                   5915: 	$config{'Qon'}=$config[10];
1.157     albertel 5916: 	$config{'PaperID'}=$config[11];
                   5917: 	$config{'PaperIDlength'}=$config[12];
                   5918: 	$config{'FirstName'}=$config[13];
                   5919: 	$config{'FirstNamelength'}=$config[14];
                   5920: 	$config{'LastName'}=$config[15];
                   5921: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5922:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5923: 	last;
                   5924:     }
                   5925:     return %config;
                   5926: }
                   5927: 
1.423     albertel 5928: =pod 
                   5929: 
                   5930: =item username_to_idmap
                   5931: 
1.556     weissno  5932:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  5933:     student username:domain. If a single ID occurs for more than one student,
                   5934:     the status of the student is checked, and if Active, the value in the hash
                   5935:     will be set to the Active student.
1.423     albertel 5936: 
                   5937:   Arguments:
                   5938: 
                   5939:     $classlist - reference to the class list hash. This is a hash
                   5940:                  keyed by student name:domain  whose elements are references
1.424     albertel 5941:                  to arrays containing various chunks of information
1.423     albertel 5942:                  about the student. (See loncoursedata for more info).
                   5943: 
                   5944:   Returns
                   5945:     %idmap - the constructed hash
                   5946: 
                   5947: =cut
                   5948: 
1.82      albertel 5949: sub username_to_idmap {
                   5950:     my ($classlist)= @_;
                   5951:     my %idmap;
                   5952:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  5953:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   5954:         unless ($id eq '') {
                   5955:             if (!exists($idmap{$id})) {
                   5956:                 $idmap{$id} = $student;
                   5957:             } else {
                   5958:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   5959:                 if ($status eq 'Active') {
                   5960:                     $idmap{$id} = $student;
                   5961:                 }
                   5962:             }
                   5963:         }
1.82      albertel 5964:     }
                   5965:     return %idmap;
                   5966: }
1.423     albertel 5967: 
                   5968: =pod
                   5969: 
1.424     albertel 5970: =item scantron_fixup_scanline
1.423     albertel 5971: 
                   5972:    Process a requested correction to a scanline.
                   5973: 
                   5974:   Arguments:
                   5975:     $scantron_config   - hash from &get_scantron_config()
                   5976:     $scan_data         - hash of correction information 
                   5977:                           (see &scantron_getfile())
                   5978:     $line              - existing scanline
                   5979:     $whichline         - line number of the passed in scanline
                   5980:     $field             - type of change to process 
                   5981:                          (either 
1.573     bisitz   5982:                           'ID'     -> correct the student/employee ID
1.423     albertel 5983:                           'CODE'   -> correct the CODE
                   5984:                           'answer' -> fixup the submitted answers)
                   5985:     
                   5986:    $args               - hash of additional info,
                   5987:                           - 'ID' 
                   5988:                                'newid' -> studentID to use in replacement
1.424     albertel 5989:                                           of existing one
1.423     albertel 5990:                           - 'CODE' 
                   5991:                                'CODE_ignore_dup' - set to true if duplicates
                   5992:                                                    should be ignored.
                   5993: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5994:                                         if the existing unfound code should
1.423     albertel 5995:                                         be used as is
                   5996:                           - 'answer'
                   5997:                                'response' - new answer or 'none' if blank
                   5998:                                'question' - the bubble line to change
1.503     raeburn  5999:                                'questionnum' - the question identifier,
                   6000:                                                may include subquestion. 
1.423     albertel 6001: 
                   6002:   Returns:
                   6003:     $line - the modified scanline
                   6004: 
                   6005:   Side effects: 
                   6006:     $scan_data - may be updated
                   6007: 
                   6008: =cut
                   6009: 
1.82      albertel 6010: 
1.157     albertel 6011: sub scantron_fixup_scanline {
                   6012:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6013:     if ($field eq 'ID') {
                   6014: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6015: 	    return ($line,1,'New value too large');
1.157     albertel 6016: 	}
                   6017: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6018: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6019: 				     $args->{'newid'});
                   6020: 	}
                   6021: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6022: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6023: 	if ($args->{'newid'}=~/^\s*$/) {
                   6024: 	    &scan_data($scan_data,"$whichline.user",
                   6025: 		       $args->{'username'}.':'.$args->{'domain'});
                   6026: 	}
1.186     albertel 6027:     } elsif ($field eq 'CODE') {
1.192     albertel 6028: 	if ($args->{'CODE_ignore_dup'}) {
                   6029: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6030: 	}
                   6031: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6032: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6033: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6034: 		return ($line,1,'New CODE value too large');
                   6035: 	    }
                   6036: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6037: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6038: 	    }
                   6039: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6040: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6041: 	}
1.157     albertel 6042:     } elsif ($field eq 'answer') {
1.497     foxr     6043: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6044: 	my $off=$scantron_config->{'Qoff'};
                   6045: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6046: 	my $answer=${off}x$length;
                   6047: 	if ($args->{'response'} eq 'none') {
                   6048: 	    &scan_data($scan_data,
1.503     raeburn  6049: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6050: 	} else {
                   6051: 	    if ($on eq 'letter') {
                   6052: 		my @alphabet=('A'..'Z');
                   6053: 		$answer=$alphabet[$args->{'response'}];
                   6054: 	    } elsif ($on eq 'number') {
                   6055: 		$answer=$args->{'response'}+1;
                   6056: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6057: 	    } else {
1.497     foxr     6058: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6059: 	    }
1.497     foxr     6060: 	    &scan_data($scan_data,
1.503     raeburn  6061: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6062: 	}
1.497     foxr     6063: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6064: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6065:     }
                   6066:     return $line;
                   6067: }
1.423     albertel 6068: 
                   6069: =pod
                   6070: 
                   6071: =item scan_data
                   6072: 
                   6073:     Edit or look up  an item in the scan_data hash.
                   6074: 
                   6075:   Arguments:
                   6076:     $scan_data  - The hash (see scantron_getfile)
                   6077:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6078:                   scantronfilename_key).
1.423     albertel 6079:     $data        - New value of the hash entry.
                   6080:     $delete      - If true, the entry is removed from the hash.
                   6081: 
                   6082:   Returns:
                   6083:     The new value of the hash table field (undefined if deleted).
                   6084: 
                   6085: =cut
                   6086: 
                   6087: 
1.157     albertel 6088: sub scan_data {
                   6089:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6090:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6091:     if (defined($value)) {
                   6092: 	$scan_data->{$filename.'_'.$key} = $value;
                   6093:     }
                   6094:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6095:     return $scan_data->{$filename.'_'.$key};
                   6096: }
1.423     albertel 6097: 
1.495     albertel 6098: # ----- These first few routines are general use routines.----
                   6099: 
                   6100: # Return the number of occurences of a pattern in a string.
                   6101: 
                   6102: sub occurence_count {
                   6103:     my ($string, $pattern) = @_;
                   6104: 
                   6105:     my @matches = ($string =~ /$pattern/g);
                   6106: 
                   6107:     return scalar(@matches);
                   6108: }
                   6109: 
                   6110: 
                   6111: # Take a string known to have digits and convert all the
                   6112: # digits into letters in the range J,A..I.
                   6113: 
                   6114: sub digits_to_letters {
                   6115:     my ($input) = @_;
                   6116: 
                   6117:     my @alphabet = ('J', 'A'..'I');
                   6118: 
                   6119:     my @input    = split(//, $input);
                   6120:     my $output ='';
                   6121:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6122: 	if ($input[$i] =~ /\d/) {
                   6123: 	    $output .= $alphabet[$input[$i]];
                   6124: 	} else {
                   6125: 	    $output .= $input[$i];
                   6126: 	}
                   6127:     }
                   6128:     return $output;
                   6129: }
                   6130: 
1.423     albertel 6131: =pod 
                   6132: 
                   6133: =item scantron_parse_scanline
                   6134: 
1.711     bisitz   6135:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6136: 
                   6137:  Arguments:
1.711     bisitz   6138:     line             - The text of the bubblesheet file line to process
1.423     albertel 6139:     whichline        - Line number
1.711     bisitz   6140:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6141:     scan_data        - Hash of extra information about the scanline
                   6142:                        (see scantron_getfile for more information)
                   6143:     just_header      - True if should not process question answers but only
                   6144:                        the stuff to the left of the answers.
1.691     raeburn  6145:     randomorder      - True if randomorder in use
                   6146:     randompick       - True if randompick in use
                   6147:     sequence         - Exam folder URL
                   6148:     master_seq       - Ref to array containing symbs in exam folder
                   6149:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6150:                        (corresponding values are resource objects)
                   6151:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6152:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6153:                        are refs to an array of resource objects, ordered
                   6154:                        according to order used for CODE, when randomorder
                   6155:                        and or randompick are in use.
                   6156:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6157:                        for current line to question number used for same question
                   6158:                         in "Master Sequence" (as seen by Course Coordinator).
                   6159:     startline        - Ref to hash where key is question number (0 is first)
                   6160:                        and value is number of first bubble line for current 
                   6161:                        student or code-based randompick and/or randomorder.
                   6162:     totalref         - Ref of scalar used to score total number of bubble
                   6163:                        lines needed for responses in a scan line (used when
                   6164:                        randompick in use. 
                   6165:     
1.423     albertel 6166:  Returns:
                   6167:    Hash containing the result of parsing the scanline
                   6168: 
                   6169:    Keys are all proceeded by the string 'scantron.'
                   6170: 
                   6171:        CODE    - the CODE in use for this scanline
                   6172:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6173:                  by the operator
                   6174:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6175:                             CODEs were selected, but the usage has been
                   6176:                             forced by the operator
1.556     weissno  6177:        ID  - student/employee ID
1.423     albertel 6178:        PaperID - if used, the ID number printed on the sheet when the 
                   6179:                  paper was scanned
                   6180:        FirstName - first name from the sheet
                   6181:        LastName  - last name from the sheet
                   6182: 
                   6183:      if just_header was not true these key may also exist
                   6184: 
1.447     foxr     6185:        missingerror - a list of bubble ranges that are considered to be answers
                   6186:                       to a single question that don't have any bubbles filled in.
                   6187:                       Of the form questionnumber:firstbubblenumber:count.
                   6188:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6189:                       to a single question that have more than one bubble filled in.
                   6190:                       Of the form questionnumber::firstbubblenumber:count
                   6191:    
                   6192:                 In the above, count is the number of bubble responses in the
                   6193:                 input line needed to represent the possible answers to the question.
                   6194:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6195:                 per line would have count = 2.
                   6196: 
1.423     albertel 6197:        maxquest     - the number of the last bubble line that was parsed
                   6198: 
                   6199:        (<number> starts at 1)
                   6200:        <number>.answer - zero or more letters representing the selected
                   6201:                          letters from the scanline for the bubble line 
                   6202:                          <number>.
                   6203:                          if blank there was either no bubble or there where
                   6204:                          multiple bubbles, (consult the keys missingerror and
                   6205:                          doubleerror if this is an error condition)
                   6206: 
                   6207: =cut
                   6208: 
1.82      albertel 6209: sub scantron_parse_scanline {
1.691     raeburn  6210:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6211:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6212:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6213: 
1.82      albertel 6214:     my %record;
1.691     raeburn  6215:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6216:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6217: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6218: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6219: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6220: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6221: 	    $record{'scantron.CODE'}=substr($data,
                   6222: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6223: 					    $$scantron_config{'CODElength'});
1.191     albertel 6224: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6225: 		$record{'scantron.useCODE'}=1;
                   6226: 	    }
1.192     albertel 6227: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6228: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6229: 	    }
1.82      albertel 6230: 	} else {
                   6231: 	    #FIXME interpret first N questions
                   6232: 	}
                   6233:     }
1.83      albertel 6234:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6235: 				  $$scantron_config{'IDlength'});
1.157     albertel 6236:     $record{'scantron.PaperID'}=
                   6237: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6238: 	       $$scantron_config{'PaperIDlength'});
                   6239:     $record{'scantron.FirstName'}=
                   6240: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6241: 	       $$scantron_config{'FirstNamelength'});
                   6242:     $record{'scantron.LastName'}=
                   6243: 	substr($data,$$scantron_config{'LastName'}-1,
                   6244: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6245:     if ($just_header) { return \%record; }
1.194     albertel 6246: 
1.82      albertel 6247:     my @alphabet=('A'..'Z');
                   6248:     my $questnum=0;
1.447     foxr     6249:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6250: 
1.691     raeburn  6251:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6252:     if ($randompick || $randomorder) {
                   6253:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6254:                                          $master_seq,$symb_to_resource,
                   6255:                                          $partids_by_symb,$orderedforcode,
                   6256:                                          $respnumlookup,$startline);
                   6257:         if ($total) {
                   6258:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6259:         }
                   6260:         if (ref($totalref)) {
                   6261:             $$totalref = $total;
                   6262:         }
                   6263:     }
                   6264:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6265:     chomp($questions);		# Get rid of any trailing \n.
                   6266:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6267:     while (length($questions)) {
1.691     raeburn  6268:         my $answers_needed;
                   6269:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6270:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6271:         } else {
                   6272: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6273:         }
1.503     raeburn  6274:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6275:                              || 1;
                   6276:         $questnum++;
                   6277:         my $quest_id = $questnum;
                   6278:         my $currentquest = substr($questions,0,$answer_length);
                   6279:         $questions       = substr($questions,$answer_length);
                   6280:         if (length($currentquest) < $answer_length) { next; }
                   6281: 
1.691     raeburn  6282:         my $subdivided;
                   6283:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6284:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6285:         } else {
                   6286:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6287:         }
                   6288:         if ($subdivided =~ /,/) {
1.503     raeburn  6289:             my $subquestnum = 1;
                   6290:             my $subquestions = $currentquest;
1.691     raeburn  6291:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6292:             foreach my $subans (@subanswers_needed) {
                   6293:                 my $subans_length =
                   6294:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6295:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6296:                 $subquestions   = substr($subquestions,$subans_length);
                   6297:                 $quest_id = "$questnum.$subquestnum";
                   6298:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6299:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6300:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6301:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6302:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6303:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6304:                 } else {
                   6305:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6306:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6307:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6308:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6309:                 }
                   6310:                 $subquestnum ++;
                   6311:             }
                   6312:         } else {
                   6313:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6314:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6315:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6316:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6317:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6318:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6319:             } else {
                   6320:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6321:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6322:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6323:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6324:             }
                   6325:         }
                   6326:     }
                   6327:     $record{'scantron.maxquest'}=$questnum;
                   6328:     return \%record;
                   6329: }
1.447     foxr     6330: 
1.691     raeburn  6331: sub get_master_seq {
                   6332:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6333:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6334:                    (ref($symb_to_resource) eq 'HASH'));
                   6335:     my $resource_error;
                   6336:     foreach my $resource (@{$resources}) {
                   6337:         my $ressymb;
                   6338:         if (ref($resource)) {
                   6339:             $ressymb = $resource->symb();
                   6340:             push(@{$master_seq},$ressymb);
                   6341:             $symb_to_resource->{$ressymb} = $resource;
                   6342:         } else {
                   6343:             $resource_error = 1;
                   6344:             last;
                   6345:         }
                   6346:     }
                   6347:     return $resource_error;
                   6348: }
                   6349: 
                   6350: sub get_respnum_lookups {
                   6351:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6352:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6353:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6354:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6355:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6356:                    (ref($startline) eq 'HASH'));
                   6357:     my ($user,$scancode);
                   6358:     if ((exists($record->{'scantron.CODE'})) &&
                   6359:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6360:         $scancode = $record->{'scantron.CODE'};
                   6361:     } else {
                   6362:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6363:     }
                   6364:     my @mapresources =
                   6365:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6366:                      $orderedforcode);
                   6367:     my $total = 0;
                   6368:     my $count = 0;
                   6369:     foreach my $resource (@mapresources) {
                   6370:         my $id = $resource->id();
                   6371:         my $symb = $resource->symb();
                   6372:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6373:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6374:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6375:                 if ($respnum ne '') {
                   6376:                     $respnumlookup->{$count} = $respnum;
                   6377:                     $startline->{$count} = $total;
                   6378:                     $total += $bubble_lines_per_response{$respnum};
                   6379:                     $count ++;
                   6380:                 }
                   6381:             }
                   6382:         }
                   6383:     }
                   6384:     return $total;
                   6385: }
                   6386: 
1.503     raeburn  6387: sub scantron_validator_lettnum {
                   6388:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6389:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6390:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6391: 
                   6392:     # Qon 'letter' implies for each slot in currquest we have:
                   6393:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6394:     #    about anything else (esp. a value of Qoff) for missing
                   6395:     #    bubbles.
                   6396:     #
                   6397:     # Qon 'number' implies each slot gives a digit that indexes the
                   6398:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6399:     #    and * or ? for double bubbles on a single line.
                   6400:     #
1.447     foxr     6401: 
1.503     raeburn  6402:     my $matchon;
                   6403:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6404:         $matchon = '[A-Z]';
                   6405:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6406:         $matchon = '\d';
                   6407:     }
                   6408:     my $occurrences = 0;
1.691     raeburn  6409:     my $responsenum = $questnum-1;
                   6410:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6411:        $responsenum = $respnumlookup->{$questnum-1} 
                   6412:     }
                   6413:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6414:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6415:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6416:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6417:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6418:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6419:         my @singlelines = split('',$currquest);
                   6420:         foreach my $entry (@singlelines) {
                   6421:             $occurrences = &occurence_count($entry,$matchon);
                   6422:             if ($occurrences > 1) {
                   6423:                 last;
                   6424:             }
1.691     raeburn  6425:         }
1.503     raeburn  6426:     } else {
                   6427:         $occurrences = &occurence_count($currquest,$matchon); 
                   6428:     }
                   6429:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6430:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6431:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6432:             my $bubble = substr($currquest,$ans,1);
                   6433:             if ($bubble =~ /$matchon/ ) {
                   6434:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6435:                     if ($bubble == 0) {
                   6436:                         $bubble = 10; 
                   6437:                     }
                   6438:                     $record->{"scantron.$ansnum.answer"} = 
                   6439:                         $alphabet->[$bubble-1];
                   6440:                 } else {
                   6441:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6442:                 }
                   6443:             } else {
                   6444:                 $record->{"scantron.$ansnum.answer"}='';
                   6445:             }
                   6446:             $ansnum++;
                   6447:         }
                   6448:     } elsif (!defined($currquest)
                   6449:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6450:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6451:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6452:             $record->{"scantron.$ansnum.answer"}='';
                   6453:             $ansnum++;
                   6454:         }
                   6455:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6456:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6457:         }
                   6458:     } else {
                   6459:         if ($$scantron_config{'Qon'} eq 'number') {
                   6460:             $currquest = &digits_to_letters($currquest);            
                   6461:         }
                   6462:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6463:             my $bubble = substr($currquest,$ans,1);
                   6464:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6465:             $ansnum++;
                   6466:         }
                   6467:     }
                   6468:     return $ansnum;
                   6469: }
1.447     foxr     6470: 
1.503     raeburn  6471: sub scantron_validator_positional {
                   6472:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6473:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6474:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6475: 
1.503     raeburn  6476:     # Otherwise there's a positional notation;
                   6477:     # each bubble line requires Qlength items, and there are filled in
                   6478:     # bubbles for each case where there 'Qon' characters.
                   6479:     #
1.447     foxr     6480: 
1.503     raeburn  6481:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6482: 
1.503     raeburn  6483:     # If the split only gives us one element.. the full length of the
                   6484:     # answer string, no bubbles are filled in:
1.447     foxr     6485: 
1.507     raeburn  6486:     if ($answers_needed eq '') {
                   6487:         return;
                   6488:     }
                   6489: 
1.503     raeburn  6490:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6491:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6492:             $record->{"scantron.$ansnum.answer"}='';
                   6493:             $ansnum++;
                   6494:         }
                   6495:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6496:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6497:         }
                   6498:     } elsif (scalar(@array) == 2) {
                   6499:         my $location = length($array[0]);
                   6500:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6501:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6502:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6503:             if ($ans eq $line_num) {
                   6504:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6505:             } else {
                   6506:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6507:             }
                   6508:             $ansnum++;
                   6509:          }
                   6510:     } else {
                   6511:         #  If there's more than one instance of a bubble character
                   6512:         #  That's a double bubble; with positional notation we can
                   6513:         #  record all the bubbles filled in as well as the
                   6514:         #  fact this response consists of multiple bubbles.
                   6515:         #
1.691     raeburn  6516:         my $responsenum = $questnum-1;
                   6517:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6518:             $responsenum = $respnumlookup->{$questnum-1}
                   6519:         }
                   6520:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6521:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6522:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6523:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6524:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6525:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6526:             my $doubleerror = 0;
                   6527:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6528:                    (!$doubleerror)) {
                   6529:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6530:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6531:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6532:                if (length(@currarray) > 2) {
                   6533:                    $doubleerror = 1;
                   6534:                } 
                   6535:             }
                   6536:             if ($doubleerror) {
                   6537:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6538:             }
                   6539:         } else {
                   6540:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6541:         }
                   6542:         my $item = $ansnum;
                   6543:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6544:             $record->{"scantron.$item.answer"} = '';
                   6545:             $item ++;
                   6546:         }
1.447     foxr     6547: 
1.503     raeburn  6548:         my @ans=@array;
                   6549:         my $i=0;
                   6550:         my $increment = 0;
                   6551:         while ($#ans) {
                   6552:             $i+=length($ans[0]) + $increment;
                   6553:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6554:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6555:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6556:             shift(@ans);
                   6557:             $increment = 1;
                   6558:         }
                   6559:         $ansnum += $answers_needed;
1.82      albertel 6560:     }
1.503     raeburn  6561:     return $ansnum;
1.82      albertel 6562: }
                   6563: 
1.423     albertel 6564: =pod
                   6565: 
                   6566: =item scantron_add_delay
                   6567: 
                   6568:    Adds an error message that occurred during the grading phase to a
                   6569:    queue of messages to be shown after grading pass is complete
                   6570: 
                   6571:  Arguments:
1.424     albertel 6572:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6573:    $scanline    - the scanline that caused the error
                   6574:    $errormesage - the error message
                   6575:    $errorcode   - a numeric code for the error
                   6576: 
                   6577:  Side Effects:
1.424     albertel 6578:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6579: 
                   6580: =cut
                   6581: 
1.82      albertel 6582: sub scantron_add_delay {
1.140     albertel 6583:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6584:     push(@$delayqueue,
                   6585: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6586: 	  'ecode' => $errorcode }
                   6587: 	 );
1.82      albertel 6588: }
                   6589: 
1.423     albertel 6590: =pod
                   6591: 
                   6592: =item scantron_find_student
                   6593: 
1.424     albertel 6594:    Finds the username for the current scanline
                   6595: 
                   6596:   Arguments:
                   6597:    $scantron_record - hash result from scantron_parse_scanline
                   6598:    $scan_data       - hash of correction information 
                   6599:                       (see &scantron_getfile() form more information)
                   6600:    $idmap           - hash from &username_to_idmap()
                   6601:    $line            - number of current scanline
                   6602:  
                   6603:   Returns:
                   6604:    Either 'username:domain' or undef if unknown
                   6605: 
1.423     albertel 6606: =cut
                   6607: 
1.82      albertel 6608: sub scantron_find_student {
1.157     albertel 6609:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6610:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6611:     if ($scanID =~ /^\s*$/) {
                   6612:  	return &scan_data($scan_data,"$line.user");
                   6613:     }
1.83      albertel 6614:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6615:  	if (lc($id) eq lc($scanID)) {
                   6616:  	    return $$idmap{$id};
                   6617:  	}
1.83      albertel 6618:     }
                   6619:     return undef;
                   6620: }
                   6621: 
1.423     albertel 6622: =pod
                   6623: 
                   6624: =item scantron_filter
                   6625: 
1.424     albertel 6626:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6627:    hidden resources was selected
                   6628: 
1.423     albertel 6629: =cut
                   6630: 
1.83      albertel 6631: sub scantron_filter {
                   6632:     my ($curres)=@_;
1.331     albertel 6633: 
                   6634:     if (ref($curres) && $curres->is_problem()) {
                   6635: 	# if the user has asked to not have either hidden
                   6636: 	# or 'randomout' controlled resources to be graded
                   6637: 	# don't include them
                   6638: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6639: 	    && $curres->randomout) {
                   6640: 	    return 0;
                   6641: 	}
1.83      albertel 6642: 	return 1;
                   6643:     }
                   6644:     return 0;
1.82      albertel 6645: }
                   6646: 
1.423     albertel 6647: =pod
                   6648: 
                   6649: =item scantron_process_corrections
                   6650: 
1.424     albertel 6651:    Gets correction information out of submitted form data and corrects
                   6652:    the scanline
                   6653: 
1.423     albertel 6654: =cut
                   6655: 
1.157     albertel 6656: sub scantron_process_corrections {
                   6657:     my ($r) = @_;
1.257     albertel 6658:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6659:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6660:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6661:     my $which=$env{'form.scantron_line'};
1.200     albertel 6662:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6663:     my ($skip,$err,$errmsg);
1.257     albertel 6664:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6665: 	$skip=1;
1.257     albertel 6666:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6667: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6668: 	    $env{'form.scantron_domain'};
1.157     albertel 6669: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6670: 	($line,$err,$errmsg)=
                   6671: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6672: 				     'ID',{'newid'=>$newid,
1.257     albertel 6673: 				    'username'=>$env{'form.scantron_username'},
                   6674: 				    'domain'=>$env{'form.scantron_domain'}});
                   6675:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6676: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6677: 	my $newCODE;
1.192     albertel 6678: 	my %args;
1.190     albertel 6679: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6680: 	    $newCODE='use_unfound';
1.190     albertel 6681: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6682: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6683: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6684: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6685: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6686: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6687: 	}
1.257     albertel 6688: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6689: 	    $args{'CODE_ignore_dup'}=1;
                   6690: 	}
                   6691: 	$args{'CODE'}=$newCODE;
1.186     albertel 6692: 	($line,$err,$errmsg)=
                   6693: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6694: 				     'CODE',\%args);
1.257     albertel 6695:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6696: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6697: 	    ($line,$err,$errmsg)=
                   6698: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6699: 					 $which,'answer',
                   6700: 					 { 'question'=>$question,
1.503     raeburn  6701: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6702:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6703: 	    if ($err) { last; }
                   6704: 	}
                   6705:     }
                   6706:     if ($err) {
1.703     bisitz   6707:         $r->print(
                   6708:             '<p class="LC_error">'
                   6709:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6710:                 $errmsg)
1.704     raeburn  6711:            .'</p>');
1.157     albertel 6712:     } else {
1.200     albertel 6713: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6714: 	&scantron_putfile($scanlines,$scan_data);
                   6715:     }
                   6716: }
                   6717: 
1.423     albertel 6718: =pod
                   6719: 
                   6720: =item reset_skipping_status
                   6721: 
1.424     albertel 6722:    Forgets the current set of remember skipped scanlines (and thus
                   6723:    reverts back to considering all lines in the
                   6724:    scantron_skipped_<filename> file)
                   6725: 
1.423     albertel 6726: =cut
                   6727: 
1.200     albertel 6728: sub reset_skipping_status {
                   6729:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6730:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6731:     &scantron_putfile(undef,$scan_data);
                   6732: }
                   6733: 
1.423     albertel 6734: =pod
                   6735: 
                   6736: =item start_skipping
                   6737: 
1.424     albertel 6738:    Marks a scanline to be skipped. 
                   6739: 
1.423     albertel 6740: =cut
                   6741: 
1.376     albertel 6742: sub start_skipping {
1.200     albertel 6743:     my ($scan_data,$i)=@_;
                   6744:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6745:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6746: 	$remembered{$i}=2;
                   6747:     } else {
                   6748: 	$remembered{$i}=1;
                   6749:     }
1.200     albertel 6750:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6751: }
                   6752: 
1.423     albertel 6753: =pod
                   6754: 
                   6755: =item should_be_skipped
                   6756: 
1.424     albertel 6757:    Checks whether a scanline should be skipped.
                   6758: 
1.423     albertel 6759: =cut
                   6760: 
1.200     albertel 6761: sub should_be_skipped {
1.376     albertel 6762:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6763:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6764: 	# not redoing old skips
1.376     albertel 6765: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6766: 	return 0;
                   6767:     }
                   6768:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6769: 
                   6770:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6771: 	return 0;
                   6772:     }
1.200     albertel 6773:     return 1;
                   6774: }
                   6775: 
1.423     albertel 6776: =pod
                   6777: 
                   6778: =item remember_current_skipped
                   6779: 
1.424     albertel 6780:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6781:    file and remembers them into scan_data for later use.
                   6782: 
1.423     albertel 6783: =cut
                   6784: 
1.200     albertel 6785: sub remember_current_skipped {
                   6786:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6787:     my %to_remember;
                   6788:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6789: 	if ($scanlines->{'skipped'}[$i]) {
                   6790: 	    $to_remember{$i}=1;
                   6791: 	}
                   6792:     }
1.376     albertel 6793: 
1.200     albertel 6794:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6795:     &scantron_putfile(undef,$scan_data);
                   6796: }
                   6797: 
1.423     albertel 6798: =pod
                   6799: 
                   6800: =item check_for_error
                   6801: 
1.424     albertel 6802:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6803:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6804:     something went wrong.
                   6805: 
1.423     albertel 6806: =cut
                   6807: 
1.200     albertel 6808: sub check_for_error {
                   6809:     my ($r,$result)=@_;
                   6810:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6811: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6812:     }
                   6813: }
1.157     albertel 6814: 
1.423     albertel 6815: =pod
                   6816: 
                   6817: =item scantron_warning_screen
                   6818: 
1.424     albertel 6819:    Interstitial screen to make sure the operator has selected the
                   6820:    correct options before we start the validation phase.
                   6821: 
1.423     albertel 6822: =cut
                   6823: 
1.203     albertel 6824: sub scantron_warning_screen {
1.650     raeburn  6825:     my ($button_text,$symb)=@_;
1.257     albertel 6826:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6827:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6828:     my $CODElist;
1.284     albertel 6829:     if ($scantron_config{'CODElocation'} &&
                   6830: 	$scantron_config{'CODEstart'} &&
                   6831: 	$scantron_config{'CODElength'}) {
                   6832: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6833: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6834: 	$CODElist=
1.492     albertel 6835: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6836: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6837:     }
1.663     raeburn  6838:     my $lastbubblepoints;
                   6839:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6840:         $lastbubblepoints =
                   6841:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6842:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6843:     }
1.492     albertel 6844:     return ('
1.203     albertel 6845: <p>
1.492     albertel 6846: <span class="LC_warning">
1.705     raeburn  6847: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6848: </p>
                   6849: <table>
1.492     albertel 6850: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6851: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6852: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6853: </table>
1.680     raeburn  6854: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6855: '.&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 6856: 
                   6857: <br />
1.492     albertel 6858: ');
1.203     albertel 6859: }
                   6860: 
1.423     albertel 6861: =pod
                   6862: 
                   6863: =item scantron_do_warning
                   6864: 
1.424     albertel 6865:    Check if the operator has picked something for all required
                   6866:    fields. Error out if something is missing.
                   6867: 
1.423     albertel 6868: =cut
                   6869: 
1.203     albertel 6870: sub scantron_do_warning {
1.608     www      6871:     my ($r,$symb)=@_;
1.203     albertel 6872:     if (!$symb) {return '';}
1.324     albertel 6873:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6874:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6875:     if ( $env{'form.selectpage'} eq '' ||
                   6876: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6877: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6878: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6879: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6880: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6881: 	} 
1.257     albertel 6882: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6883: 	    $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 6884: 	} 
1.257     albertel 6885: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6886: 	    $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 6887: 	} 
                   6888:     } else {
1.650     raeburn  6889: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6890:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6891: 	$r->print('
1.663     raeburn  6892: '.$warning.$bubbledbyhand.'
1.492     albertel 6893: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6894: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6895: ');
1.237     albertel 6896:     }
1.614     www      6897:     $r->print("</form><br />");
1.203     albertel 6898:     return '';
                   6899: }
                   6900: 
1.423     albertel 6901: =pod
                   6902: 
                   6903: =item scantron_form_start
                   6904: 
1.424     albertel 6905:     html hidden input for remembering all selected grading options
                   6906: 
1.423     albertel 6907: =cut
                   6908: 
1.203     albertel 6909: sub scantron_form_start {
                   6910:     my ($max_bubble)=@_;
                   6911:     my $result= <<SCANTRONFORM;
                   6912: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6913:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6914:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6915:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6916:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6917:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6918:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6919:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6920:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6921:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6922: SCANTRONFORM
1.447     foxr     6923: 
                   6924:   my $line = 0;
                   6925:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6926:        my $chunk =
                   6927: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6928:        $chunk .=
                   6929: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6930:        $chunk .= 
                   6931:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6932:        $chunk .=
                   6933:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6934:        $chunk .=
                   6935:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6936:        $result .= $chunk;
                   6937:        $line++;
1.691     raeburn  6938:     }
1.203     albertel 6939:     return $result;
                   6940: }
                   6941: 
1.423     albertel 6942: =pod
                   6943: 
                   6944: =item scantron_validate_file
                   6945: 
1.659     raeburn  6946:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6947: 
                   6948:     Also processes any necessary information resets that need to
                   6949:     occur before validation begins (ignore previous corrections,
                   6950:     restarting the skipped records processing)
                   6951: 
1.423     albertel 6952: =cut
                   6953: 
1.157     albertel 6954: sub scantron_validate_file {
1.608     www      6955:     my ($r,$symb) = @_;
1.157     albertel 6956:     if (!$symb) {return '';}
1.324     albertel 6957:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6958:     
1.703     bisitz   6959:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6960:     # them when doing the corrections reset
1.257     albertel 6961:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6962: 	&reset_skipping_status();
                   6963:     }
1.257     albertel 6964:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6965: 	&remember_current_skipped();
1.257     albertel 6966: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6967:     }
                   6968: 
1.257     albertel 6969:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6970: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6971: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6972: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6973: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6974:     }
1.200     albertel 6975: 
1.257     albertel 6976:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6977: 	&scantron_process_corrections($r);
                   6978:     }
1.503     raeburn  6979:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6980:     #get the student pick code ready
                   6981:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6982:     my $nav_error;
1.649     raeburn  6983:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6984:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6985:     if ($nav_error) {
                   6986:         $r->print(&navmap_errormsg());
                   6987:         return '';
                   6988:     }
1.203     albertel 6989:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6990:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6991:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6992:     }
1.157     albertel 6993:     $r->print($result);
                   6994:     
1.334     albertel 6995:     my @validate_phases=( 'sequence',
                   6996: 			  'ID',
1.157     albertel 6997: 			  'CODE',
                   6998: 			  'doublebubble',
                   6999: 			  'missingbubbles');
1.257     albertel 7000:     if (!$env{'form.validatepass'}) {
                   7001: 	$env{'form.validatepass'} = 0;
1.157     albertel 7002:     }
1.257     albertel 7003:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7004: 
1.448     foxr     7005: 
1.157     albertel 7006:     my $stop=0;
                   7007:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7008: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7009: 	$r->rflush();
1.691     raeburn  7010:      
1.157     albertel 7011: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7012: 	{
                   7013: 	    no strict 'refs';
                   7014: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7015: 	}
                   7016:     }
                   7017:     if (!$stop) {
1.650     raeburn  7018: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7019: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7020:                   $warning.
                   7021:                   &mt('Perform verification for each student after storage of submissions?').
                   7022:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7023:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7024:                   ('&nbsp;'x3).'<label>'.
                   7025:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7026:                   '</label></span><br />'.
                   7027:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7028:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7029:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7030:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7031:     } else {
                   7032: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7033: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7034:     }
                   7035:     if ($stop) {
1.334     albertel 7036: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7037: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7038: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7039: 
1.650     raeburn  7040: 	    $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 7041: 	} else {
1.503     raeburn  7042:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7043: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7044:             } else {
1.539     riegler  7045:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7046:             }
1.492     albertel 7047: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7048: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7049: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7050: 	}
1.157     albertel 7051:     }
1.614     www      7052:     $r->print(" </form><br />");
1.157     albertel 7053:     return '';
                   7054: }
                   7055: 
1.423     albertel 7056: 
                   7057: =pod
                   7058: 
                   7059: =item scantron_remove_file
                   7060: 
1.659     raeburn  7061:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7062:    scantron_original_<filename> is never removed
                   7063: 
                   7064: 
1.423     albertel 7065: =cut
                   7066: 
1.200     albertel 7067: sub scantron_remove_file {
1.192     albertel 7068:     my ($which)=@_;
1.257     albertel 7069:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7070:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7071:     my $file='scantron_';
1.200     albertel 7072:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7073: 	$file.=$which.'_';
1.192     albertel 7074:     } else {
                   7075: 	return 'refused';
                   7076:     }
1.257     albertel 7077:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7078:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7079: }
                   7080: 
1.423     albertel 7081: 
                   7082: =pod
                   7083: 
                   7084: =item scantron_remove_scan_data
                   7085: 
1.659     raeburn  7086:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7087:    data file.  (In the case that both the are doing skipped records we need
                   7088:    to remember the old skipped lines for the time being so that element
                   7089:    persists for a while.)
                   7090: 
1.423     albertel 7091: =cut
                   7092: 
1.200     albertel 7093: sub scantron_remove_scan_data {
1.257     albertel 7094:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7095:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7096:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7097:     my @todelete;
1.257     albertel 7098:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7099:     foreach my $key (@keys) {
                   7100: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7101: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7102: 		$key=~/remember_skipping/) {
                   7103: 		next;
                   7104: 	    }
1.192     albertel 7105: 	    push(@todelete,$key);
                   7106: 	}
                   7107:     }
1.200     albertel 7108:     my $result;
1.192     albertel 7109:     if (@todelete) {
1.491     albertel 7110: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7111: 				       \@todelete,$cdom,$cname);
                   7112:     } else {
                   7113: 	$result = 'ok';
1.192     albertel 7114:     }
                   7115:     return $result;
                   7116: }
                   7117: 
1.423     albertel 7118: 
                   7119: =pod
                   7120: 
                   7121: =item scantron_getfile
                   7122: 
1.659     raeburn  7123:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7124:     the scan_data hash
                   7125:   
                   7126:   Arguments:
                   7127:     None
                   7128: 
                   7129:   Returns:
                   7130:     2 hash references
                   7131: 
                   7132:      - first one has 
                   7133:          orig      -
                   7134:          corrected -
                   7135:          skipped   -  each of which points to an array ref of the specified
                   7136:                       file broken up into individual lines
                   7137:          count     - number of scanlines
                   7138:  
                   7139:      - second is the scan_data hash possible keys are
1.425     albertel 7140:        ($number refers to scanline numbered $number and thus the key affects
                   7141:         only that scanline
                   7142:         $bubline refers to the specific bubble line element and the aspects
                   7143:         refers to that specific bubble line element)
                   7144: 
                   7145:        $number.user - username:domain to use
                   7146:        $number.CODE_ignore_dup 
                   7147:                     - ignore the duplicate CODE error 
                   7148:        $number.useCODE
                   7149:                     - use the CODE in the scanline as is
                   7150:        $number.no_bubble.$bubline
                   7151:                     - it is valid that there is no bubbled in bubble
                   7152:                       at $number $bubline
                   7153:        remember_skipping
                   7154:                     - a frozen hash containing keys of $number and values
                   7155:                       of either 
                   7156:                         1 - we are on a 'do skipped records pass' and plan
                   7157:                             on processing this line
                   7158:                         2 - we are on a 'do skipped records pass' and this
                   7159:                             scanline has been marked to skip yet again
1.424     albertel 7160: 
1.423     albertel 7161: =cut
                   7162: 
1.157     albertel 7163: sub scantron_getfile {
1.200     albertel 7164:     #FIXME really would prefer a scantron directory
1.257     albertel 7165:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7166:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7167:     my $lines;
                   7168:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7169: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7170:     my %scanlines;
                   7171:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7172:     my $temp=$scanlines{'orig'};
                   7173:     $scanlines{'count'}=$#$temp;
                   7174: 
                   7175:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7176: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7177:     if ($lines eq '-1') {
                   7178: 	$scanlines{'corrected'}=[];
                   7179:     } else {
                   7180: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7181:     }
                   7182:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7183: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7184:     if ($lines eq '-1') {
                   7185: 	$scanlines{'skipped'}=[];
                   7186:     } else {
                   7187: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7188:     }
1.175     albertel 7189:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7190:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7191:     my %scan_data = @tmp;
                   7192:     return (\%scanlines,\%scan_data);
                   7193: }
                   7194: 
1.423     albertel 7195: =pod
                   7196: 
                   7197: =item lonnet_putfile
                   7198: 
1.424     albertel 7199:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7200: 
                   7201:  Arguments:
                   7202:    $contents - data to store
                   7203:    $filename - filename to store $contents into
                   7204: 
                   7205:  Returns:
                   7206:    result value from &Apache::lonnet::finishuserfileupload
                   7207: 
1.423     albertel 7208: =cut
                   7209: 
1.157     albertel 7210: sub lonnet_putfile {
                   7211:     my ($contents,$filename)=@_;
1.257     albertel 7212:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7213:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7214:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7215:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7216: 
                   7217: }
                   7218: 
1.423     albertel 7219: =pod
                   7220: 
                   7221: =item scantron_putfile
                   7222: 
1.659     raeburn  7223:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7224:     scan_data hash. (Does not modify the original version only the
                   7225:     corrected and skipped versions.
                   7226: 
                   7227:  Arguments:
                   7228:     $scanlines - hash ref that looks like the first return value from
                   7229:                  &scantron_getfile()
                   7230:     $scan_data - hash ref that looks like the second return value from
                   7231:                  &scantron_getfile()
                   7232: 
1.423     albertel 7233: =cut
                   7234: 
1.157     albertel 7235: sub scantron_putfile {
                   7236:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7237:     #FIXME really would prefer a scantron directory
1.257     albertel 7238:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7239:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7240:     if ($scanlines) {
                   7241: 	my $prefix='scantron_';
1.157     albertel 7242: # no need to update orig, shouldn't change
                   7243: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7244: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7245: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7246: 			$prefix.'corrected_'.
1.257     albertel 7247: 			$env{'form.scantron_selectfile'});
1.200     albertel 7248: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7249: 			$prefix.'skipped_'.
1.257     albertel 7250: 			$env{'form.scantron_selectfile'});
1.200     albertel 7251:     }
1.175     albertel 7252:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7253: }
                   7254: 
1.423     albertel 7255: =pod
                   7256: 
                   7257: =item scantron_get_line
                   7258: 
1.424     albertel 7259:    Returns the correct version of the scanline
                   7260: 
                   7261:  Arguments:
                   7262:     $scanlines - hash ref that looks like the first return value from
                   7263:                  &scantron_getfile()
                   7264:     $scan_data - hash ref that looks like the second return value from
                   7265:                  &scantron_getfile()
                   7266:     $i         - number of the requested line (starts at 0)
                   7267: 
                   7268:  Returns:
                   7269:    A scanline, (either the original or the corrected one if it
                   7270:    exists), or undef if the requested scanline should be
                   7271:    skipped. (Either because it's an skipped scanline, or it's an
                   7272:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7273:    pass.
                   7274: 
1.423     albertel 7275: =cut
                   7276: 
1.157     albertel 7277: sub scantron_get_line {
1.200     albertel 7278:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7279:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7280:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7281:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7282:     return $scanlines->{'orig'}[$i]; 
                   7283: }
                   7284: 
1.423     albertel 7285: =pod
                   7286: 
                   7287: =item scantron_todo_count
                   7288: 
1.424     albertel 7289:     Counts the number of scanlines that need processing.
                   7290: 
                   7291:  Arguments:
                   7292:     $scanlines - hash ref that looks like the first return value from
                   7293:                  &scantron_getfile()
                   7294:     $scan_data - hash ref that looks like the second return value from
                   7295:                  &scantron_getfile()
                   7296: 
                   7297:  Returns:
                   7298:     $count - number of scanlines to process
                   7299: 
1.423     albertel 7300: =cut
                   7301: 
1.200     albertel 7302: sub get_todo_count {
                   7303:     my ($scanlines,$scan_data)=@_;
                   7304:     my $count=0;
                   7305:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7306: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7307: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7308: 	$count++;
                   7309:     }
                   7310:     return $count;
                   7311: }
                   7312: 
1.423     albertel 7313: =pod
                   7314: 
                   7315: =item scantron_put_line
                   7316: 
1.659     raeburn  7317:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7318:     data file.
                   7319: 
                   7320:  Arguments:
                   7321:     $scanlines - hash ref that looks like the first return value from
                   7322:                  &scantron_getfile()
                   7323:     $scan_data - hash ref that looks like the second return value from
                   7324:                  &scantron_getfile()
                   7325:     $i         - line number to update
                   7326:     $newline   - contents of the updated scanline
                   7327:     $skip      - if true make the line for skipping and update the
                   7328:                  'skipped' file
                   7329: 
1.423     albertel 7330: =cut
                   7331: 
1.157     albertel 7332: sub scantron_put_line {
1.200     albertel 7333:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7334:     if ($skip) {
                   7335: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7336: 	&start_skipping($scan_data,$i);
1.157     albertel 7337: 	return;
                   7338:     }
                   7339:     $scanlines->{'corrected'}[$i]=$newline;
                   7340: }
                   7341: 
1.423     albertel 7342: =pod
                   7343: 
                   7344: =item scantron_clear_skip
                   7345: 
1.424     albertel 7346:    Remove a line from the 'skipped' file
                   7347: 
                   7348:  Arguments:
                   7349:     $scanlines - hash ref that looks like the first return value from
                   7350:                  &scantron_getfile()
                   7351:     $scan_data - hash ref that looks like the second return value from
                   7352:                  &scantron_getfile()
                   7353:     $i         - line number to update
                   7354: 
1.423     albertel 7355: =cut
                   7356: 
1.376     albertel 7357: sub scantron_clear_skip {
                   7358:     my ($scanlines,$scan_data,$i)=@_;
                   7359:     if (exists($scanlines->{'skipped'}[$i])) {
                   7360: 	undef($scanlines->{'skipped'}[$i]);
                   7361: 	return 1;
                   7362:     }
                   7363:     return 0;
                   7364: }
                   7365: 
1.423     albertel 7366: =pod
                   7367: 
                   7368: =item scantron_filter_not_exam
                   7369: 
1.424     albertel 7370:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7371:    filter out resources that are not marked as 'exam' mode
                   7372: 
1.423     albertel 7373: =cut
                   7374: 
1.334     albertel 7375: sub scantron_filter_not_exam {
                   7376:     my ($curres)=@_;
                   7377:     
                   7378:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7379: 	# if the user has asked to not have either hidden
                   7380: 	# or 'randomout' controlled resources to be graded
                   7381: 	# don't include them
                   7382: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7383: 	    && $curres->randomout) {
                   7384: 	    return 0;
                   7385: 	}
                   7386: 	return 1;
                   7387:     }
                   7388:     return 0;
                   7389: }
                   7390: 
1.423     albertel 7391: =pod
                   7392: 
                   7393: =item scantron_validate_sequence
                   7394: 
1.424     albertel 7395:     Validates the selected sequence, checking for resource that are
                   7396:     not set to exam mode.
                   7397: 
1.423     albertel 7398: =cut
                   7399: 
1.334     albertel 7400: sub scantron_validate_sequence {
                   7401:     my ($r,$currentphase) = @_;
                   7402: 
                   7403:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7404:     unless (ref($navmap)) {
                   7405:         $r->print(&navmap_errormsg());
                   7406:         return (1,$currentphase);
                   7407:     }
1.334     albertel 7408:     my (undef,undef,$sequence)=
                   7409: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7410: 
                   7411:     my $map=$navmap->getResourceByUrl($sequence);
                   7412: 
                   7413:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7414:                                     value="ignore" />');
                   7415:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7416: 	my @resources=
                   7417: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7418: 	if (@resources) {
1.675     bisitz   7419: 	    $r->print(
                   7420:                 '<p class="LC_warning">'
                   7421:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7422:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7423:                    .' work correctly.')
                   7424:                .'</p>'
                   7425:             );
1.334     albertel 7426: 	    return (1,$currentphase);
                   7427: 	}
                   7428:     }
                   7429: 
                   7430:     return (0,$currentphase+1);
                   7431: }
                   7432: 
1.423     albertel 7433: 
                   7434: 
1.157     albertel 7435: sub scantron_validate_ID {
                   7436:     my ($r,$currentphase) = @_;
                   7437:     
                   7438:     #get student info
                   7439:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7440:     my %idmap=&username_to_idmap($classlist);
                   7441: 
                   7442:     #get scantron line setup
1.257     albertel 7443:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7444:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7445: 
                   7446:     my $nav_error;
1.649     raeburn  7447:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7448:     if ($nav_error) {
                   7449:         $r->print(&navmap_errormsg());
                   7450:         return(1,$currentphase);
                   7451:     }
1.157     albertel 7452: 
                   7453:     my %found=('ids'=>{},'usernames'=>{});
                   7454:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7455: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7456: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7457: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7458: 						 $scan_data);
                   7459: 	my $id=$$scan_record{'scantron.ID'};
                   7460: 	my $found;
                   7461: 	foreach my $checkid (keys(%idmap)) {
                   7462: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7463: 	}
                   7464: 	if ($found) {
                   7465: 	    my $username=$idmap{$found};
                   7466: 	    if ($found{'ids'}{$found}) {
                   7467: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7468: 					 $line,'duplicateID',$found);
1.194     albertel 7469: 		return(1,$currentphase);
1.157     albertel 7470: 	    } elsif ($found{'usernames'}{$username}) {
                   7471: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7472: 					 $line,'duplicateID',$username);
1.194     albertel 7473: 		return(1,$currentphase);
1.157     albertel 7474: 	    }
1.186     albertel 7475: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7476: 	    $found{'ids'}{$found}++;
                   7477: 	    $found{'usernames'}{$username}++;
                   7478: 	} else {
                   7479: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7480: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7481: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7482: 		    &scantron_get_correction($r,$i,$scan_record,
                   7483: 					     \%scantron_config,
                   7484: 					     $line,'duplicateID',$username);
1.194     albertel 7485: 		    return(1,$currentphase);
1.157     albertel 7486: 		} elsif (!defined($username)) {
                   7487: 		    &scantron_get_correction($r,$i,$scan_record,
                   7488: 					     \%scantron_config,
                   7489: 					     $line,'incorrectID');
1.194     albertel 7490: 		    return(1,$currentphase);
1.157     albertel 7491: 		}
                   7492: 		$found{'usernames'}{$username}++;
                   7493: 	    } else {
                   7494: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7495: 					 $line,'incorrectID');
1.194     albertel 7496: 		return(1,$currentphase);
1.157     albertel 7497: 	    }
                   7498: 	}
                   7499:     }
                   7500: 
                   7501:     return (0,$currentphase+1);
                   7502: }
                   7503: 
1.423     albertel 7504: 
1.157     albertel 7505: sub scantron_get_correction {
1.691     raeburn  7506:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7507:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7508: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7509: #to show both the current line and the previous one and allow skipping
                   7510: #the previous one or the current one
                   7511: 
1.333     albertel 7512:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7513:         $r->print(
                   7514:             '<p class="LC_warning">'
                   7515:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7516:                 "<b>$error</b>",
                   7517:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7518:            ."</p> \n");
1.157     albertel 7519:     } else {
1.658     bisitz   7520:         $r->print(
                   7521:             '<p class="LC_warning">'
                   7522:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7523:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7524:            ."</p> \n");
                   7525:     }
                   7526:     my $message =
                   7527:         '<p>'
                   7528:        .&mt('The ID on the form is [_1]',
                   7529:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7530:        .'<br />'
1.665     raeburn  7531:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7532:             $$scan_record{'scantron.LastName'},
                   7533:             $$scan_record{'scantron.FirstName'})
                   7534:        .'</p>';
1.242     albertel 7535: 
1.157     albertel 7536:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7537:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7538:                            # Array populated for doublebubble or
                   7539:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7540:                            # to validate radio button checking   
                   7541: 
1.157     albertel 7542:     if ($error =~ /ID$/) {
1.186     albertel 7543: 	if ($error eq 'incorrectID') {
1.658     bisitz   7544:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7545: 		      "</p>\n");
1.157     albertel 7546: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7547:             $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 7548: 	}
1.242     albertel 7549: 	$r->print($message);
1.492     albertel 7550: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7551: 	$r->print("\n<ul><li> ");
                   7552: 	#FIXME it would be nice if this sent back the user ID and
                   7553: 	#could do partial userID matches
                   7554: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7555: 				       'scantron_username','scantron_domain'));
                   7556: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7557: 	$r->print("\n:\n".
1.257     albertel 7558: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7559: 
                   7560: 	$r->print('</li>');
1.186     albertel 7561:     } elsif ($error =~ /CODE$/) {
                   7562: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7563: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7564: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7565: 	    $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 7566: 	}
1.658     bisitz   7567: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7568: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7569:                  ."</p>\n");
1.242     albertel 7570: 	$r->print($message);
1.658     bisitz   7571: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7572: 	$r->print("\n<br /> ");
1.194     albertel 7573: 	my $i=0;
1.273     albertel 7574: 	if ($error eq 'incorrectCODE' 
                   7575: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7576: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7577: 	    if ($closest > 0) {
                   7578: 		foreach my $testcode (@{$closest}) {
                   7579: 		    my $checked='';
1.569     bisitz   7580: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7581: 		    $r->print("
                   7582:    <label>
1.569     bisitz   7583:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7584:        ".&mt("Use the similar CODE [_1] instead.",
                   7585: 	    "<b><tt>".$testcode."</tt></b>")."
                   7586:     </label>
                   7587:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7588: 		    $r->print("\n<br />");
                   7589: 		    $i++;
                   7590: 		}
1.194     albertel 7591: 	    }
                   7592: 	}
1.273     albertel 7593: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7594: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7595: 	    $r->print("
                   7596:     <label>
1.569     bisitz   7597:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7598:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7599: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7600:     </label>");
1.273     albertel 7601: 	    $r->print("\n<br />");
                   7602: 	}
1.194     albertel 7603: 
1.597     wenzelju 7604: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7605: function change_radio(field) {
1.190     albertel 7606:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7607:     var i;
                   7608:     for (i=0;i<slct.length;i++) {
                   7609:         if (slct[i].value==field) { slct[i].checked=true; }
                   7610:     }
                   7611: }
                   7612: ENDSCRIPT
1.187     albertel 7613: 	my $href="/adm/pickcode?".
1.359     www      7614: 	   "form=".&escape("scantronupload").
                   7615: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7616: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7617: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7618: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7619: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7620: 	    $r->print("
                   7621:     <label>
                   7622:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7623:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7624: 	     "<a target='_blank' href='$href'>","</a>")."
                   7625:     </label> 
1.558     bisitz   7626:     ".&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 7627: 	    $r->print("\n<br />");
                   7628: 	}
1.492     albertel 7629: 	$r->print("
                   7630:     <label>
                   7631:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7632:        ".&mt("Use [_1] as the CODE.",
                   7633: 	     "</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 7634: 	$r->print("\n<br /><br />");
1.157     albertel 7635:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7636: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7637: 
                   7638: 	# The form field scantron_questions is acutally a list of line numbers.
                   7639: 	# represented by this form so:
                   7640: 
1.691     raeburn  7641: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7642:                                                 $respnumlookup,$startline);
1.497     foxr     7643: 
1.157     albertel 7644: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7645: 		  $line_list.'" />');
1.242     albertel 7646: 	$r->print($message);
1.492     albertel 7647: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7648: 	foreach my $question (@{$arg}) {
1.503     raeburn  7649: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7650:                                                    $scan_record, $error,
                   7651:                                                    $randomorder,$randompick,
                   7652:                                                    $respnumlookup,$startline);
1.524     raeburn  7653:             push(@lines_to_correct,@linenums);
1.157     albertel 7654: 	}
1.503     raeburn  7655:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7656:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7657: 	$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 7658: 	$r->print($message);
1.492     albertel 7659: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7660: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7661: 
1.503     raeburn  7662: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7663: 	# a list of question numbers. Therefore:
                   7664: 	#
1.691     raeburn  7665: 
                   7666: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7667:                                                 $respnumlookup,$startline);
1.497     foxr     7668: 
1.157     albertel 7669: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7670: 		  $line_list.'" />');
1.157     albertel 7671: 	foreach my $question (@{$arg}) {
1.503     raeburn  7672: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7673:                                                    $scan_record, $error,
                   7674:                                                    $randomorder,$randompick,
                   7675:                                                    $respnumlookup,$startline);
1.524     raeburn  7676:             push(@lines_to_correct,@linenums);
1.157     albertel 7677: 	}
1.503     raeburn  7678:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7679:     } else {
                   7680: 	$r->print("\n<ul>");
                   7681:     }
                   7682:     $r->print("\n</li></ul>");
1.497     foxr     7683: }
                   7684: 
1.503     raeburn  7685: sub verify_bubbles_checked {
                   7686:     my (@ansnums) = @_;
                   7687:     my $ansnumstr = join('","',@ansnums);
                   7688:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7689:     &js_escape(\$warning);
1.597     wenzelju 7690:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7691: function verify_bubble_radio(form) {
                   7692:     var ansnumArray = new Array ("$ansnumstr");
                   7693:     var need_bubble_count = 0;
                   7694:     for (var i=0; i<ansnumArray.length; i++) {
                   7695:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7696:             var bubble_picked = 0; 
                   7697:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7698:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7699:                     bubble_picked = 1;
                   7700:                 }
                   7701:             }
                   7702:             if (bubble_picked == 0) {
                   7703:                 need_bubble_count ++;
                   7704:             }
                   7705:         }
                   7706:     }
                   7707:     if (need_bubble_count) {
                   7708:         alert("$warning");
                   7709:         return;
                   7710:     }
                   7711:     form.submit(); 
                   7712: }
                   7713: ENDSCRIPT
                   7714:     return $output;
                   7715: }
                   7716: 
1.497     foxr     7717: =pod
                   7718: 
                   7719: =item  questions_to_line_list
1.157     albertel 7720: 
1.497     foxr     7721: Converts a list of questions into a string of comma separated
                   7722: line numbers in the answer sheet used by the questions.  This is
                   7723: used to fill in the scantron_questions form field.
                   7724: 
                   7725:   Arguments:
                   7726:      questions    - Reference to an array of questions.
1.691     raeburn  7727:      randomorder  - True if randomorder in use.
                   7728:      randompick   - True if randompick in use.
                   7729:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7730:                      for current line to question number used for same question
                   7731:                      in "Master Seqence" (as seen by Course Coordinator).
                   7732:      startline    - Reference to hash where key is question number (0 is first)
                   7733:                     and key is number of first bubble line for current student
                   7734:                     or code-based randompick and/or randomorder.
1.693     raeburn  7735: 
1.497     foxr     7736: =cut
                   7737: 
                   7738: 
                   7739: sub questions_to_line_list {
1.691     raeburn  7740:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7741:     my @lines;
                   7742: 
1.503     raeburn  7743:     foreach my $item (@{$questions}) {
                   7744:         my $question = $item;
                   7745:         my ($first,$count,$last);
                   7746:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7747:             $question = $1;
                   7748:             my $subquestion = $2;
1.691     raeburn  7749:             my $responsenum = $question-1;
                   7750:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7751:                 $responsenum = $respnumlookup->{$question-1};
                   7752:                 if (ref($startline) eq 'HASH') {
                   7753:                     $first = $startline->{$question-1} + 1;
                   7754:                 }
                   7755:             } else {
                   7756:                 $first = $first_bubble_line{$responsenum} + 1;
                   7757:             }
                   7758:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7759:             my $subcount = 1;
                   7760:             while ($subcount<$subquestion) {
                   7761:                 $first += $subans[$subcount-1];
                   7762:                 $subcount ++;
                   7763:             }
                   7764:             $count = $subans[$subquestion-1];
                   7765:         } else {
1.691     raeburn  7766:             my $responsenum = $question-1;
                   7767:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7768:                 $responsenum = $respnumlookup->{$question-1};
                   7769:                 if (ref($startline) eq 'HASH') {
                   7770:                     $first = $startline->{$question-1} + 1;
                   7771:                 }
                   7772:             } else {
                   7773:                 $first = $first_bubble_line{$responsenum} + 1;
                   7774:             }
                   7775: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7776:         }
1.506     raeburn  7777:         $last = $first+$count-1;
1.503     raeburn  7778:         push(@lines, ($first..$last));
1.497     foxr     7779:     }
                   7780:     return join(',', @lines);
                   7781: }
                   7782: 
                   7783: =pod 
                   7784: 
                   7785: =item prompt_for_corrections
                   7786: 
                   7787: Prompts for a potentially multiline correction to the
                   7788: user's bubbling (factors out common code from scantron_get_correction
                   7789: for multi and missing bubble cases).
                   7790: 
                   7791:  Arguments:
                   7792:    $r           - Apache request object.
                   7793:    $question    - The question number to prompt for.
                   7794:    $scan_config - The scantron file configuration hash.
                   7795:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7796:    $error       - Type of error
1.691     raeburn  7797:    $randomorder - True if randomorder in use.
                   7798:    $randompick  - True if randompick in use.
                   7799:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7800:                     for current line to question number used for same question
                   7801:                     in "Master Seqence" (as seen by Course Coordinator).
                   7802:    $startline   - Reference to hash where key is question number (0 is first)
                   7803:                   and value is number of first bubble line for current student
                   7804:                   or code-based randompick and/or randomorder.
                   7805: 
1.497     foxr     7806: 
                   7807:  Implicit inputs:
                   7808:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7809:                                   Numbered from 0 (but question numbers are from
                   7810:                                   1.
                   7811:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7812:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7813:                                   type problems render as separate sub-questions, 
1.503     raeburn  7814:                                   in exam mode. This hash contains a 
                   7815:                                   comma-separated list of the lines per 
                   7816:                                   sub-question.
1.510     raeburn  7817:    %responsetype_per_response   - essayresponse, formularesponse,
                   7818:                                   stringresponse, imageresponse, reactionresponse,
                   7819:                                   and organicresponse type problem parts can have
1.503     raeburn  7820:                                   multiple lines per response if the weight
                   7821:                                   assigned exceeds 10.  In this case, only
                   7822:                                   one bubble per line is permitted, but more 
                   7823:                                   than one line might contain bubbles, e.g.
                   7824:                                   bubbling of: line 1 - J, line 2 - J, 
                   7825:                                   line 3 - B would assign 22 points.  
1.497     foxr     7826: 
                   7827: =cut
                   7828: 
                   7829: sub prompt_for_corrections {
1.691     raeburn  7830:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7831:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7832:     my ($current_line,$lines);
                   7833:     my @linenums;
                   7834:     my $questionnum = $question;
1.691     raeburn  7835:     my ($first,$responsenum);
1.503     raeburn  7836:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7837:         $question = $1;
                   7838:         my $subquestion = $2;
1.691     raeburn  7839:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7840:             $responsenum = $respnumlookup->{$question-1};
                   7841:             if (ref($startline) eq 'HASH') {
                   7842:                 $first = $startline->{$question-1};
                   7843:             }
                   7844:         } else {
                   7845:             $responsenum = $question-1;
1.714     raeburn  7846:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7847:         }
                   7848:         $current_line = $first + 1 ;
                   7849:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7850:         my $subcount = 1;
                   7851:         while ($subcount<$subquestion) {
                   7852:             $current_line += $subans[$subcount-1];
                   7853:             $subcount ++;
                   7854:         }
                   7855:         $lines = $subans[$subquestion-1];
                   7856:     } else {
1.691     raeburn  7857:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7858:             $responsenum = $respnumlookup->{$question-1};
                   7859:             if (ref($startline) eq 'HASH') { 
                   7860:                 $first = $startline->{$question-1};
                   7861:             }
                   7862:         } else {
                   7863:             $responsenum = $question-1;
                   7864:             $first = $first_bubble_line{$responsenum};
                   7865:         }
                   7866:         $current_line = $first + 1;
                   7867:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7868:     }
1.497     foxr     7869:     if ($lines > 1) {
1.503     raeburn  7870:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7871:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7872:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7873:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7874:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7875:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7876:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7877:             $r->print(
                   7878:                 &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)
                   7879:                .'<br /><br />'
                   7880:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7881:                .'<br />'
                   7882:                .&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.')
                   7883:                .'<br />'
                   7884:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7885:                .'<br /><br />'
                   7886:             );
1.503     raeburn  7887:         } else {
                   7888:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7889:         }
1.497     foxr     7890:     }
                   7891:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7892:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7893: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7894: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7895:         push(@linenums,$current_line);
1.497     foxr     7896: 	$current_line++;
                   7897:     }
                   7898:     if ($lines > 1) {
                   7899: 	$r->print("<hr /><br />");
                   7900:     }
1.503     raeburn  7901:     return @linenums;
1.157     albertel 7902: }
1.423     albertel 7903: 
                   7904: =pod
                   7905: 
                   7906: =item scantron_bubble_selector
                   7907:   
                   7908:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7909:    possibly showing the existing the selected bubbles if known
1.423     albertel 7910: 
                   7911:  Arguments:
                   7912:     $r           - Apache request object
                   7913:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7914:     $line        - Number of the line being displayed.
1.503     raeburn  7915:     $questionnum - Question number (may include subquestion)
                   7916:     $error       - Type of error.
1.497     foxr     7917:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7918: 
                   7919: =cut
                   7920: 
1.157     albertel 7921: sub scantron_bubble_selector {
1.503     raeburn  7922:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7923:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7924: 
                   7925:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7926:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7927:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7928:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7929:             $max=$$scan_config{'BubblesPerRow'};
                   7930:             if (($scmode eq 'number') && ($max > 10)) {
                   7931:                 $max = 10;
                   7932:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7933:                 $max = 26;
                   7934:             }
                   7935:         } else {
                   7936:             $max = 10;
                   7937:         }
                   7938:     }
1.274     albertel 7939: 
1.157     albertel 7940:     my @alphabet=('A'..'Z');
1.503     raeburn  7941:     $r->print(&Apache::loncommon::start_data_table().
                   7942:               &Apache::loncommon::start_data_table_row());
                   7943:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7944:     for (my $i=0;$i<$max+1;$i++) {
                   7945: 	$r->print("\n".'<td align="center">');
                   7946: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7947: 	else { $r->print('&nbsp;'); }
                   7948: 	$r->print('</td>');
                   7949:     }
1.503     raeburn  7950:     $r->print(&Apache::loncommon::end_data_table_row().
                   7951:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7952:     for (my $i=0;$i<$max;$i++) {
                   7953: 	$r->print("\n".
                   7954: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7955: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7956:     }
1.503     raeburn  7957:     my $nobub_checked = ' ';
                   7958:     if ($error eq 'missingbubble') {
                   7959:         $nobub_checked = ' checked = "checked" ';
                   7960:     }
                   7961:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7962: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7963:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7964:               $line.'" value="'.$questionnum.'" /></td>');
                   7965:     $r->print(&Apache::loncommon::end_data_table_row().
                   7966:               &Apache::loncommon::end_data_table());
1.157     albertel 7967: }
                   7968: 
1.423     albertel 7969: =pod
                   7970: 
                   7971: =item num_matches
                   7972: 
1.424     albertel 7973:    Counts the number of characters that are the same between the two arguments.
                   7974: 
                   7975:  Arguments:
                   7976:    $orig - CODE from the scanline
                   7977:    $code - CODE to match against
                   7978: 
                   7979:  Returns:
                   7980:    $count - integer count of the number of same characters between the
                   7981:             two arguments
                   7982: 
1.423     albertel 7983: =cut
                   7984: 
1.194     albertel 7985: sub num_matches {
                   7986:     my ($orig,$code) = @_;
                   7987:     my @code=split(//,$code);
                   7988:     my @orig=split(//,$orig);
                   7989:     my $same=0;
                   7990:     for (my $i=0;$i<scalar(@code);$i++) {
                   7991: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7992:     }
                   7993:     return $same;
                   7994: }
                   7995: 
1.423     albertel 7996: =pod
                   7997: 
                   7998: =item scantron_get_closely_matching_CODEs
                   7999: 
1.424     albertel 8000:    Cycles through all CODEs and finds the set that has the greatest
                   8001:    number of same characters as the provided CODE
                   8002: 
                   8003:  Arguments:
                   8004:    $allcodes - hash ref returned by &get_codes()
                   8005:    $CODE     - CODE from the current scanline
                   8006: 
                   8007:  Returns:
                   8008:    2 element list
                   8009:     - first elements is number of how closely matching the best fit is 
                   8010:       (5 means best set has 5 matching characters)
                   8011:     - second element is an arrary ref containing the set of valid CODEs
                   8012:       that best fit the passed in CODE
                   8013: 
1.423     albertel 8014: =cut
                   8015: 
1.194     albertel 8016: sub scantron_get_closely_matching_CODEs {
                   8017:     my ($allcodes,$CODE)=@_;
                   8018:     my @CODEs;
                   8019:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8020: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8021:     }
                   8022: 
                   8023:     return ($#CODEs,$CODEs[-1]);
                   8024: }
                   8025: 
1.423     albertel 8026: =pod
                   8027: 
                   8028: =item get_codes
                   8029: 
1.424     albertel 8030:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8031:    set of remembered CODEs.
                   8032: 
                   8033:  Arguments:
                   8034:   $old_name - name of the set of remembered CODEs
                   8035:   $cdom     - domain of the course
                   8036:   $cnum     - internal course name
                   8037: 
                   8038:  Returns:
                   8039:   %allcodes - keys are the valid CODEs, values are all 1
                   8040: 
1.423     albertel 8041: =cut
                   8042: 
1.194     albertel 8043: sub get_codes {
1.280     foxr     8044:     my ($old_name, $cdom, $cnum) = @_;
                   8045:     if (!$old_name) {
                   8046: 	$old_name=$env{'form.scantron_CODElist'};
                   8047:     }
                   8048:     if (!$cdom) {
                   8049: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8050:     }
                   8051:     if (!$cnum) {
                   8052: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8053:     }
1.278     albertel 8054:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8055: 				    $cdom,$cnum);
                   8056:     my %allcodes;
                   8057:     if ($result{"type\0$old_name"} eq 'number') {
                   8058: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8059:     } else {
                   8060: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8061:     }
1.194     albertel 8062:     return %allcodes;
                   8063: }
                   8064: 
1.423     albertel 8065: =pod
                   8066: 
                   8067: =item scantron_validate_CODE
                   8068: 
1.424     albertel 8069:    Validates all scanlines in the selected file to not have any
                   8070:    invalid or underspecified CODEs and that none of the codes are
                   8071:    duplicated if this was requested.
                   8072: 
1.423     albertel 8073: =cut
                   8074: 
1.157     albertel 8075: sub scantron_validate_CODE {
                   8076:     my ($r,$currentphase) = @_;
1.257     albertel 8077:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8078:     if ($scantron_config{'CODElocation'} &&
                   8079: 	$scantron_config{'CODEstart'} &&
                   8080: 	$scantron_config{'CODElength'}) {
1.257     albertel 8081: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8082: 	    &FIXME_blow_up()
                   8083: 	}
                   8084:     } else {
                   8085: 	return (0,$currentphase+1);
                   8086:     }
                   8087:     
                   8088:     my %usedCODEs;
                   8089: 
1.194     albertel 8090:     my %allcodes=&get_codes();
1.186     albertel 8091: 
1.582     raeburn  8092:     my $nav_error;
1.649     raeburn  8093:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8094:     if ($nav_error) {
                   8095:         $r->print(&navmap_errormsg());
                   8096:         return(1,$currentphase);
                   8097:     }
1.447     foxr     8098: 
1.186     albertel 8099:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8100:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8101: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8102: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8103: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8104: 						 $scan_data);
                   8105: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8106: 	my $error=0;
1.224     albertel 8107: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8108: 	    &scantron_get_correction($r,$i,$scan_record,
                   8109: 				     \%scantron_config,
                   8110: 				     $line,'incorrectCODE',\%allcodes);
                   8111: 	    return(1,$currentphase);
                   8112: 	}
1.221     albertel 8113: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8114: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8115: 	    &scantron_get_correction($r,$i,$scan_record,
                   8116: 				     \%scantron_config,
1.194     albertel 8117: 				     $line,'incorrectCODE',\%allcodes);
                   8118: 	    return(1,$currentphase);
1.186     albertel 8119: 	}
1.214     albertel 8120: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8121: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8122: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8123: 	    &scantron_get_correction($r,$i,$scan_record,
                   8124: 				     \%scantron_config,
1.194     albertel 8125: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8126: 	    return(1,$currentphase);
1.186     albertel 8127: 	}
1.524     raeburn  8128: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8129:     }
1.157     albertel 8130:     return (0,$currentphase+1);
                   8131: }
                   8132: 
1.423     albertel 8133: =pod
                   8134: 
                   8135: =item scantron_validate_doublebubble
                   8136: 
1.424     albertel 8137:    Validates all scanlines in the selected file to not have any
                   8138:    bubble lines with multiple bubbles marked.
                   8139: 
1.423     albertel 8140: =cut
                   8141: 
1.157     albertel 8142: sub scantron_validate_doublebubble {
                   8143:     my ($r,$currentphase) = @_;
                   8144:     #get student info
                   8145:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8146:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8147:     my (undef,undef,$sequence)=
                   8148:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8149: 
                   8150:     #get scantron line setup
1.257     albertel 8151:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8152:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8153: 
                   8154:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8155:     unless (ref($navmap)) {
                   8156:         $r->print(&navmap_errormsg());
                   8157:         return(1,$currentphase);
                   8158:     }
                   8159:     my $map=$navmap->getResourceByUrl($sequence);
                   8160:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8161:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8162:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8163:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8164: 
1.583     raeburn  8165:     my $nav_error;
1.691     raeburn  8166:     if (ref($map)) {
                   8167:         $randomorder = $map->randomorder();
                   8168:         $randompick = $map->randompick();
                   8169:         if ($randomorder || $randompick) {
                   8170:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8171:             if ($nav_error) {
                   8172:                 $r->print(&navmap_errormsg());
                   8173:                 return(1,$currentphase);
                   8174:             }
                   8175:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8176:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8177:         }
                   8178:     } else {
                   8179:         $r->print(&navmap_errormsg());
                   8180:         return(1,$currentphase);
                   8181:     }
                   8182: 
1.649     raeburn  8183:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8184:     if ($nav_error) {
                   8185:         $r->print(&navmap_errormsg());
                   8186:         return(1,$currentphase);
                   8187:     }
1.447     foxr     8188: 
1.157     albertel 8189:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8190: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8191: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8192: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8193: 						 $scan_data,undef,\%idmap,$randomorder,
                   8194:                                                  $randompick,$sequence,\@master_seq,
                   8195:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8196:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8197: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8198: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8199: 				 'doublebubble',
1.691     raeburn  8200: 				 $$scan_record{'scantron.doubleerror'},
                   8201:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8202:     	return (1,$currentphase);
                   8203:     }
                   8204:     return (0,$currentphase+1);
                   8205: }
                   8206: 
1.423     albertel 8207: 
1.503     raeburn  8208: sub scantron_get_maxbubble {
1.649     raeburn  8209:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8210:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8211: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8212: 	&restore_bubble_lines();
1.257     albertel 8213: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8214:     }
1.330     albertel 8215: 
1.447     foxr     8216:     my (undef, undef, $sequence) =
1.257     albertel 8217: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8218: 
1.447     foxr     8219:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8220:     unless (ref($navmap)) {
                   8221:         if (ref($nav_error)) {
                   8222:             $$nav_error = 1;
                   8223:         }
1.591     raeburn  8224:         return;
1.582     raeburn  8225:     }
1.191     albertel 8226:     my $map=$navmap->getResourceByUrl($sequence);
                   8227:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8228:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8229: 
                   8230:     &Apache::lonxml::clear_problem_counter();
                   8231: 
1.557     raeburn  8232:     my $uname       = $env{'user.name'};
                   8233:     my $udom        = $env{'user.domain'};
1.435     foxr     8234:     my $cid         = $env{'request.course.id'};
                   8235:     my $total_lines = 0;
                   8236:     %bubble_lines_per_response = ();
1.447     foxr     8237:     %first_bubble_line         = ();
1.503     raeburn  8238:     %subdivided_bubble_lines   = ();
                   8239:     %responsetype_per_response = ();
1.691     raeburn  8240:     %masterseq_id_responsenum  = ();
1.554     raeburn  8241: 
1.447     foxr     8242:     my $response_number = 0;
                   8243:     my $bubble_line     = 0;
1.191     albertel 8244:     foreach my $resource (@resources) {
1.691     raeburn  8245:         my $resid = $resource->id(); 
1.672     raeburn  8246:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8247:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8248:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8249: 	    foreach my $part_id (@{$parts}) {
                   8250:                 my $lines;
                   8251: 
                   8252: 	        # TODO - make this a persistent hash not an array.
                   8253: 
                   8254:                 # optionresponse, matchresponse and rankresponse type items 
                   8255:                 # render as separate sub-questions in exam mode.
                   8256:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8257:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8258:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8259:                     my ($numbub,$numshown);
                   8260:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8261:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8262:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8263:                         }
                   8264:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8265:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8266:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8267:                         }
                   8268:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8269:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8270:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8271:                         }
                   8272:                     }
                   8273:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8274:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8275:                     }
1.649     raeburn  8276:                     my $bubbles_per_row =
                   8277:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8278:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8279:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8280:                         $inner_bubble_lines++;
                   8281:                     }
                   8282:                     for (my $i=0; $i<$numshown; $i++) {
                   8283:                         $subdivided_bubble_lines{$response_number} .= 
                   8284:                             $inner_bubble_lines.',';
                   8285:                     }
                   8286:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8287:                     $lines = $numshown * $inner_bubble_lines;
                   8288:                 } else {
                   8289:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8290:                 }
1.542     raeburn  8291: 
                   8292:                 $first_bubble_line{$response_number} = $bubble_line;
                   8293: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8294:                 $responsetype_per_response{$response_number} = 
                   8295:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8296:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8297: 	        $response_number++;
                   8298: 
                   8299: 	        $bubble_line +=  $lines;
                   8300: 	        $total_lines +=  $lines;
                   8301: 	    }
                   8302:         }
                   8303:     }
1.552     raeburn  8304:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8305: 
                   8306:     &save_bubble_lines();
                   8307:     $env{'form.scantron_maxbubble'} =
                   8308: 	$total_lines;
                   8309:     return $env{'form.scantron_maxbubble'};
                   8310: }
1.523     raeburn  8311: 
1.649     raeburn  8312: sub bubblesheet_bubbles_per_row {
                   8313:     my ($scantron_config) = @_;
                   8314:     my $bubbles_per_row;
                   8315:     if (ref($scantron_config) eq 'HASH') {
                   8316:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8317:     }
                   8318:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8319:         $bubbles_per_row = 10;
                   8320:     }
                   8321:     return $bubbles_per_row;
                   8322: }
                   8323: 
1.157     albertel 8324: sub scantron_validate_missingbubbles {
                   8325:     my ($r,$currentphase) = @_;
                   8326:     #get student info
                   8327:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8328:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8329:     my (undef,undef,$sequence)=
                   8330:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8331: 
                   8332:     #get scantron line setup
1.257     albertel 8333:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8334:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8335: 
                   8336:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8337:     unless (ref($navmap)) {
                   8338:         $r->print(&navmap_errormsg());
                   8339:         return(1,$currentphase);
                   8340:     }
                   8341: 
                   8342:     my $map=$navmap->getResourceByUrl($sequence);
                   8343:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8344:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8345:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8346:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8347: 
1.582     raeburn  8348:     my $nav_error;
1.691     raeburn  8349:     if (ref($map)) {
                   8350:         $randomorder = $map->randomorder();
                   8351:         $randompick = $map->randompick();
                   8352:         if ($randomorder || $randompick) {
                   8353:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8354:             if ($nav_error) {
                   8355:                 $r->print(&navmap_errormsg());
                   8356:                 return(1,$currentphase);
                   8357:             }
                   8358:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8359:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8360:         }
                   8361:     } else {
                   8362:         $r->print(&navmap_errormsg());
                   8363:         return(1,$currentphase);
                   8364:     }
                   8365: 
                   8366: 
1.649     raeburn  8367:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8368:     if ($nav_error) {
1.691     raeburn  8369:         $r->print(&navmap_errormsg());
1.693     raeburn  8370:         return(1,$currentphase);
1.582     raeburn  8371:     }
1.691     raeburn  8372: 
1.157     albertel 8373:     if (!$max_bubble) { $max_bubble=2**31; }
                   8374:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8375: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8376: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8377: 	my $scan_record =
                   8378:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8379: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8380:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8381:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8382: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8383: 	my @to_correct;
1.470     foxr     8384: 	
                   8385: 	# Probably here's where the error is...
                   8386: 
1.157     albertel 8387: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8388:             my $lastbubble;
                   8389:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8390:                my $question = $1;
                   8391:                my $subquestion = $2;
1.691     raeburn  8392:                my ($first,$responsenum);
                   8393:                if ($randomorder || $randompick) {
                   8394:                    $responsenum = $respnumlookup{$question-1};
                   8395:                    $first = $startline{$question-1};
                   8396:                } else {
                   8397:                    $responsenum = $question-1; 
                   8398:                    $first = $first_bubble_line{$responsenum};
                   8399:                }
                   8400:                if (!defined($first)) { next; }
                   8401:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8402:                my $subcount = 1;
                   8403:                while ($subcount<$subquestion) {
                   8404:                    $first += $subans[$subcount-1];
                   8405:                    $subcount ++;
                   8406:                }
                   8407:                my $count = $subans[$subquestion-1];
                   8408:                $lastbubble = $first + $count;
                   8409:             } else {
1.691     raeburn  8410:                my ($first,$responsenum);
                   8411:                if ($randomorder || $randompick) {
                   8412:                    $responsenum = $respnumlookup{$missing-1};
                   8413:                    $first = $startline{$missing-1};
                   8414:                } else {
                   8415:                    $responsenum = $missing-1;
                   8416:                    $first = $first_bubble_line{$responsenum};
                   8417:                }
                   8418:                if (!defined($first)) { next; }
                   8419:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8420:             }
                   8421:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8422: 	    push(@to_correct,$missing);
                   8423: 	}
                   8424: 	if (@to_correct) {
                   8425: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8426: 				     $line,'missingbubble',\@to_correct,
                   8427:                                      $randomorder,$randompick,\%respnumlookup,
                   8428:                                      \%startline);
1.157     albertel 8429: 	    return (1,$currentphase);
                   8430: 	}
                   8431: 
                   8432:     }
                   8433:     return (0,$currentphase+1);
                   8434: }
                   8435: 
1.663     raeburn  8436: sub hand_bubble_option {
                   8437:     my (undef, undef, $sequence) =
                   8438:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8439:     return if ($sequence eq '');
                   8440:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8441:     unless (ref($navmap)) {
                   8442:         return;
                   8443:     }
                   8444:     my $needs_hand_bubbles;
                   8445:     my $map=$navmap->getResourceByUrl($sequence);
                   8446:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8447:     foreach my $res (@resources) {
                   8448:         if (ref($res)) {
                   8449:             if ($res->is_problem()) {
                   8450:                 my $partlist = $res->parts();
                   8451:                 foreach my $part (@{ $partlist }) {
                   8452:                     my @types = $res->responseType($part);
                   8453:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8454:                         $needs_hand_bubbles = 1;
                   8455:                         last;
                   8456:                     }
                   8457:                 }
                   8458:             }
                   8459:         }
                   8460:     }
                   8461:     if ($needs_hand_bubbles) {
                   8462:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8463:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8464:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8465:                &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 />').
                   8466:                '<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  8467:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8468:     }
                   8469:     return;
                   8470: }
1.423     albertel 8471: 
1.82      albertel 8472: sub scantron_process_students {
1.608     www      8473:     my ($r,$symb) = @_;
1.513     foxr     8474: 
1.257     albertel 8475:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8476:     if (!$symb) {
                   8477: 	return '';
                   8478:     }
1.324     albertel 8479:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8480: 
1.257     albertel 8481:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8482:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8483:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8484:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8485:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8486:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8487:     unless (ref($navmap)) {
                   8488:         $r->print(&navmap_errormsg());
                   8489:         return '';
1.691     raeburn  8490:     }
1.83      albertel 8491:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8492:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8493:         %grader_randomlists_by_symb);
1.677     raeburn  8494:     if (ref($map)) {
                   8495:         $randomorder = $map->randomorder();
1.689     raeburn  8496:         $randompick = $map->randompick();
1.691     raeburn  8497:     } else {
                   8498:         $r->print(&navmap_errormsg());
                   8499:         return '';
1.677     raeburn  8500:     }
1.691     raeburn  8501:     my $nav_error;
1.83      albertel 8502:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8503:     if ($randomorder || $randompick) {
                   8504:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8505:         if ($nav_error) {
                   8506:             $r->print(&navmap_errormsg());
                   8507:             return '';
                   8508:         }
                   8509:     }
1.557     raeburn  8510:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8511:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8512: 
1.554     raeburn  8513:     my ($uname,$udom);
1.82      albertel 8514:     my $result= <<SCANTRONFORM;
1.81      albertel 8515: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8516:   <input type="hidden" name="command" value="scantron_configphase" />
                   8517:   $default_form_data
                   8518: SCANTRONFORM
1.82      albertel 8519:     $r->print($result);
                   8520: 
                   8521:     my @delayqueue;
1.542     raeburn  8522:     my (%completedstudents,%scandata);
1.140     albertel 8523:     
1.520     www      8524:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8525:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8526:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8527:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8528:     $r->print('<br />');
1.140     albertel 8529:     my $start=&Time::HiRes::time();
1.158     albertel 8530:     my $i=-1;
1.542     raeburn  8531:     my $started;
1.447     foxr     8532: 
1.649     raeburn  8533:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8534:     if ($nav_error) {
                   8535:         $r->print(&navmap_errormsg());
                   8536:         return '';
                   8537:     }
                   8538: 
1.513     foxr     8539:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8540:     # the user and return.
                   8541: 
                   8542:     if ($ssi_error) {
                   8543: 	$r->print("</form>");
                   8544: 	&ssi_print_error($r);
1.520     www      8545:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8546: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8547:     }
1.447     foxr     8548: 
1.542     raeburn  8549:     my %lettdig = &letter_to_digits();
                   8550:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8551:     my %orderedforcode;
1.542     raeburn  8552: 
1.157     albertel 8553:     while ($i<$scanlines->{'count'}) {
                   8554:  	($uname,$udom)=('','');
                   8555:  	$i++;
1.200     albertel 8556:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8557:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8558: 	if ($started) {
1.667     www      8559: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8560: 	}
                   8561: 	$started=1;
1.691     raeburn  8562:         my %respnumlookup = ();
                   8563:         my %startline = ();
                   8564:         my $total;
1.157     albertel 8565:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8566:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8567:                                                  $randompick,$sequence,\@master_seq,
                   8568:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8569:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8570:                                                  \$total);
1.157     albertel 8571:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8572:  					      \%idmap,$i)) {
                   8573:   	    &scantron_add_delay(\@delayqueue,$line,
                   8574:  				'Unable to find a student that matches',1);
                   8575:  	    next;
                   8576:   	}
                   8577:  	if (exists $completedstudents{$uname}) {
                   8578:  	    &scantron_add_delay(\@delayqueue,$line,
                   8579:  				'Student '.$uname.' has multiple sheets',2);
                   8580:  	    next;
                   8581:  	}
1.677     raeburn  8582:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8583:         my $user = $uname.':'.$usec;
1.157     albertel 8584:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8585: 
1.677     raeburn  8586:         my $scancode;
                   8587:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8588:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8589:             $scancode = $scan_record->{'scantron.CODE'};
                   8590:         } else {
                   8591:             $scancode = '';
                   8592:         }
                   8593: 
                   8594:         my @mapresources = @resources;
1.689     raeburn  8595:         if ($randomorder || $randompick) {
1.678     raeburn  8596:             @mapresources = 
1.691     raeburn  8597:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8598:                              \%orderedforcode);
1.677     raeburn  8599:         }
1.586     raeburn  8600:         my (%partids_by_symb,$res_error);
1.677     raeburn  8601:         foreach my $resource (@mapresources) {
1.586     raeburn  8602:             my $ressymb;
                   8603:             if (ref($resource)) {
                   8604:                 $ressymb = $resource->symb();
                   8605:             } else {
                   8606:                 $res_error = 1;
                   8607:                 last;
                   8608:             }
1.557     raeburn  8609:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8610:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741   ! raeburn  8611:                 my $currcode;
        !          8612:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
        !          8613:                     $currcode = $scancode;
        !          8614:                 }
1.557     raeburn  8615:                 my ($analysis,$parts) =
1.672     raeburn  8616:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741   ! raeburn  8617:                                               $uname,$udom,undef,$bubbles_per_row,
        !          8618:                                               $currcode);
1.557     raeburn  8619:                 $partids_by_symb{$ressymb} = $parts;
                   8620:             } else {
                   8621:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8622:             }
1.554     raeburn  8623:         }
                   8624: 
1.586     raeburn  8625:         if ($res_error) {
                   8626:             &scantron_add_delay(\@delayqueue,$line,
                   8627:                                 'An error occurred while grading student '.$uname,2);
                   8628:             next;
                   8629:         }
                   8630: 
1.330     albertel 8631: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8632:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8633: 
                   8634: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8635: 	    &scantron_putfile($scanlines,$scan_data);
                   8636: 	}
1.161     albertel 8637: 	
1.542     raeburn  8638:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8639:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8640:                                    $bubbles_per_row,$randomorder,$randompick,
                   8641:                                    \%respnumlookup,\%startline) 
                   8642:             eq 'ssi_error') {
1.542     raeburn  8643:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8644:             $r->print("</form>");
                   8645:             &ssi_print_error($r);
                   8646:             &Apache::lonnet::remove_lock($lock);
                   8647:             return '';      # Why return ''?  Beats me.
                   8648:         }
1.513     foxr     8649: 
1.692     raeburn  8650:         if (($scancode) && ($randomorder || $randompick)) {
                   8651:             my $parmresult =
                   8652:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8653:                                                        '0_examcode',2,$scancode,
                   8654:                                                        'string_examcode',$uname,
                   8655:                                                        $udom);
                   8656:         }
1.140     albertel 8657: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8658:         if ($env{'form.verifyrecord'}) {
                   8659:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8660:             if ($randompick) {
                   8661:                 if ($total) {
                   8662:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8663:                 }
                   8664:             }
                   8665: 
1.542     raeburn  8666:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8667:             chomp($studentdata);
                   8668:             $studentdata =~ s/\r$//;
                   8669:             my $studentrecord = '';
                   8670:             my $counter = -1;
1.677     raeburn  8671:             foreach my $resource (@mapresources) {
1.554     raeburn  8672:                 my $ressymb = $resource->symb();
1.542     raeburn  8673:                 ($counter,my $recording) =
                   8674:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8675:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8676:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8677:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8678:                 $studentrecord .= $recording;
                   8679:             }
                   8680:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8681:                 &Apache::lonxml::clear_problem_counter();
                   8682:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8683:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8684:                                            $bubbles_per_row,$randomorder,$randompick,
                   8685:                                            \%respnumlookup,\%startline) 
                   8686:                     eq 'ssi_error') {
1.554     raeburn  8687:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8688:                     $r->print("</form>");
                   8689:                     &ssi_print_error($r);
                   8690:                     &Apache::lonnet::remove_lock($lock);
                   8691:                     delete($completedstudents{$uname});
                   8692:                     return '';
                   8693:                 }
1.542     raeburn  8694:                 $counter = -1;
                   8695:                 $studentrecord = '';
1.677     raeburn  8696:                 foreach my $resource (@mapresources) {
1.554     raeburn  8697:                     my $ressymb = $resource->symb();
1.542     raeburn  8698:                     ($counter,my $recording) =
                   8699:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8700:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8701:                                                  \%scantron_config,\%lettdig,$numletts,
                   8702:                                                  $randomorder,$randompick,\%respnumlookup,
                   8703:                                                  \%startline);
1.542     raeburn  8704:                     $studentrecord .= $recording;
                   8705:                 }
                   8706:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8707:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8708:                     if ($scancode eq '') {
1.658     bisitz   8709:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8710:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8711:                     } else {
1.658     bisitz   8712:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8713:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8714:                     }
                   8715:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8716:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8717:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8718:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8719:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8720:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8721:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8722:                               &Apache::loncommon::end_data_table_row().
                   8723:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8724:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8725:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8726:                               &Apache::loncommon::end_data_table_row().
                   8727:                               &Apache::loncommon::end_data_table().'</p>');
                   8728:                 } else {
                   8729:                     $r->print('<br /><span class="LC_warning">'.
                   8730:                              &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 />'.
                   8731:                              &mt("As a consequence, this user's submission history records two tries.").
                   8732:                                  '</span><br />');
                   8733:                 }
                   8734:             }
                   8735:         }
1.543     raeburn  8736:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8737:     } continue {
1.330     albertel 8738: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8739: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8740:     }
1.140     albertel 8741:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8742:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8743: #    my $lasttime = &Time::HiRes::time()-$start;
                   8744: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8745: 
1.200     albertel 8746:     $r->print("</form>");
1.157     albertel 8747:     return '';
1.75      albertel 8748: }
1.157     albertel 8749: 
1.557     raeburn  8750: sub graders_resources_pass {
1.649     raeburn  8751:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8752:         $bubbles_per_row) = @_;
1.557     raeburn  8753:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8754:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8755:         foreach my $resource (@{$resources}) {
                   8756:             my $ressymb = $resource->symb();
                   8757:             my ($analysis,$parts) =
                   8758:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8759:                                           $env{'user.name'},$env{'user.domain'},
                   8760:                                           1,$bubbles_per_row);
1.557     raeburn  8761:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8762:             if (ref($analysis) eq 'HASH') {
                   8763:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8764:                     $grader_randomlists_by_symb->{$ressymb} =
                   8765:                         $analysis->{'parts_withrandomlist'};
                   8766:                 }
                   8767:             }
                   8768:         }
                   8769:     }
                   8770:     return;
                   8771: }
                   8772: 
1.678     raeburn  8773: =pod
                   8774: 
                   8775: =item users_order
                   8776: 
                   8777:   Returns array of resources in current map, ordered based on either CODE,
                   8778:   if this is a CODEd exam, or based on student's identity if this is a 
                   8779:   "NAMEd" exam.
                   8780: 
1.691     raeburn  8781:   Should be used when randomorder and/or randompick applied when the 
                   8782:   corresponding exam was printed, prior to students completing bubblesheets 
                   8783:   for the version of the exam the student received.
1.678     raeburn  8784: 
                   8785: =cut
                   8786: 
                   8787: sub users_order  {
1.691     raeburn  8788:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8789:     my @mapresources;
1.691     raeburn  8790:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8791:         return @mapresources;
1.691     raeburn  8792:     }
                   8793:     if ($scancode) {
                   8794:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8795:             @mapresources = @{$orderedforcode->{$scancode}};
                   8796:         } else {
                   8797:             $env{'form.CODE'} = $scancode;
                   8798:             my $actual_seq =
                   8799:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8800:                                                                $master_seq,
                   8801:                                                                $user,$scancode,1);
                   8802:             if (ref($actual_seq) eq 'ARRAY') {
                   8803:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8804:                 if (ref($orderedforcode) eq 'HASH') {
                   8805:                     if (@mapresources > 0) { 
                   8806:                         $orderedforcode->{$scancode} = \@mapresources;
                   8807:                     }
                   8808:                 }
                   8809:             }
                   8810:             delete($env{'form.CODE'});
1.678     raeburn  8811:         }
                   8812:     } else {
                   8813:         my $actual_seq =
                   8814:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8815:                                                            $master_seq,
1.688     raeburn  8816:                                                            $user,undef,1);
1.678     raeburn  8817:         if (ref($actual_seq) eq 'ARRAY') {
                   8818:             @mapresources = 
                   8819:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8820:         }
1.691     raeburn  8821:     }
                   8822:     return @mapresources;
1.678     raeburn  8823: }
                   8824: 
1.542     raeburn  8825: sub grade_student_bubbles {
1.691     raeburn  8826:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8827:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8828:     my $uselookup = 0;
                   8829:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8830:         (ref($startline) eq 'HASH')) {
                   8831:         $uselookup = 1;
                   8832:     }
                   8833: 
1.554     raeburn  8834:     if (ref($resources) eq 'ARRAY') {
                   8835:         my $count = 0;
                   8836:         foreach my $resource (@{$resources}) {
                   8837:             my $ressymb = $resource->symb();
                   8838:             my %form = ('submitted'      => 'scantron',
                   8839:                         'grade_target'   => 'grade',
                   8840:                         'grade_username' => $uname,
                   8841:                         'grade_domain'   => $udom,
                   8842:                         'grade_courseid' => $env{'request.course.id'},
                   8843:                         'grade_symb'     => $ressymb,
                   8844:                         'CODE'           => $scancode
                   8845:                        );
1.649     raeburn  8846:             if ($bubbles_per_row ne '') {
                   8847:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8848:             }
1.663     raeburn  8849:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8850:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8851:             }
1.554     raeburn  8852:             if (ref($parts) eq 'HASH') {
                   8853:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8854:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8855:                         if ($uselookup) {
                   8856:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8857:                         } else {
                   8858:                             $form{'scantron_questnum_start.'.$part} =
                   8859:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8860:                         }
1.554     raeburn  8861:                         $count++;
                   8862:                     }
                   8863:                 }
                   8864:             }
                   8865:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8866:             return 'ssi_error' if ($ssi_error);
                   8867:             last if (&Apache::loncommon::connection_aborted($r));
                   8868:         }
1.542     raeburn  8869:     }
                   8870:     return;
                   8871: }
                   8872: 
1.157     albertel 8873: sub scantron_upload_scantron_data {
1.608     www      8874:     my ($r,$symb)=@_;
1.565     raeburn  8875:     my $dom = $env{'request.role.domain'};
                   8876:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8877:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8878:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8879: 							  'domainid',
1.565     raeburn  8880: 							  'coursename',$dom);
                   8881:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8882:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8883:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8884:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  8885:     &js_escape(\$nofile_alert);
1.579     raeburn  8886:     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  8887:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 8888:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8889:     function checkUpload(formname) {
                   8890: 	if (formname.upfile.value == "") {
1.579     raeburn  8891: 	    alert("'.$nofile_alert.'");
1.157     albertel 8892: 	    return false;
                   8893: 	}
1.565     raeburn  8894:         if (formname.courseid.value == "") {
1.579     raeburn  8895:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8896:             return false;
                   8897:         }
1.157     albertel 8898: 	formname.submit();
                   8899:     }
1.565     raeburn  8900: 
                   8901:     function ToSyllabus() {
                   8902:         var cdom = '."'$dom'".';
                   8903:         var cnum = document.rules.courseid.value;
                   8904:         if (cdom == "" || cdom == null) {
                   8905:             return;
                   8906:         }
                   8907:         if (cnum == "" || cnum == null) {
                   8908:            return;
                   8909:         }
                   8910:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8911:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8912:         return;
                   8913:     }
                   8914: 
1.597     wenzelju 8915: '));
                   8916:     $r->print('
1.648     bisitz   8917: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8918: 
1.492     albertel 8919: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8920: '.$default_form_data.
                   8921:   &Apache::lonhtmlcommon::start_pick_box().
                   8922:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8923:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8924:   &Apache::lonhtmlcommon::row_closure().
                   8925:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8926:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8927:   &Apache::lonhtmlcommon::row_closure().
                   8928:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8929:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8930:   &Apache::lonhtmlcommon::row_closure().
                   8931:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8932:   '<input type="file" name="upfile" size="50" />'.
                   8933:   &Apache::lonhtmlcommon::row_closure(1).
                   8934:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8935: 
1.492     albertel 8936: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8937: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8938: </form>
1.492     albertel 8939: ');
1.157     albertel 8940:     return '';
                   8941: }
                   8942: 
1.423     albertel 8943: 
1.157     albertel 8944: sub scantron_upload_scantron_data_save {
1.608     www      8945:     my($r,$symb)=@_;
1.182     albertel 8946:     my $doanotherupload=
                   8947: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8948: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8949: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8950: 	'</form>'."\n";
1.257     albertel 8951:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8952: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8953: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8954: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8955: 	unless ($symb) {
1.182     albertel 8956: 	    $r->print($doanotherupload);
                   8957: 	}
1.162     albertel 8958: 	return '';
                   8959:     }
1.257     albertel 8960:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8961:     my $uploadedfile;
1.710     bisitz   8962:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8963:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8964:         $r->print(
                   8965:             &Apache::lonhtmlcommon::confirm_success(
                   8966:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8967:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8968:     } else {
1.568     raeburn  8969:         my $result = 
                   8970:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8971:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8972:         if ($result =~ m{^/uploaded/}) {
                   8973:             $r->print(
                   8974:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8975:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8976:                         (length($env{'form.upfile'})-1),
                   8977:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8978:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8979:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8980:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8981:         } else {
                   8982:             $r->print(
                   8983:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8984:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8985:                           $result,
1.568     raeburn  8986: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8987: 	}
                   8988:     }
1.174     albertel 8989:     if ($symb) {
1.612     www      8990: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8991:     } else {
1.182     albertel 8992: 	$r->print($doanotherupload);
1.174     albertel 8993:     }
1.157     albertel 8994:     return '';
                   8995: }
                   8996: 
1.567     raeburn  8997: sub validate_uploaded_scantron_file {
                   8998:     my ($cdom,$cname,$fname) = @_;
                   8999:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9000:     my @lines;
                   9001:     if ($scanlines ne '-1') {
                   9002:         @lines=split("\n",$scanlines,-1);
                   9003:     }
                   9004:     my $output;
                   9005:     if (@lines) {
                   9006:         my (%counts,$max_match_format);
1.710     bisitz   9007:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9008:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9009:         my %idmap = &username_to_idmap($classlist);
                   9010:         foreach my $key (keys(%idmap)) {
                   9011:             my $lckey = lc($key);
                   9012:             $idmap{$lckey} = $idmap{$key};
                   9013:         }
                   9014:         my %unique_formats;
                   9015:         my @formatlines = &get_scantronformat_file();
                   9016:         foreach my $line (@formatlines) {
                   9017:             chomp($line);
                   9018:             my @config = split(/:/,$line);
                   9019:             my $idstart = $config[5];
                   9020:             my $idlength = $config[6];
                   9021:             if (($idstart ne '') && ($idlength > 0)) {
                   9022:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9023:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9024:                 } else {
                   9025:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9026:                 }
                   9027:             }
                   9028:         }
                   9029:         foreach my $key (keys(%unique_formats)) {
                   9030:             my ($idstart,$idlength) = split(':',$key);
                   9031:             %{$counts{$key}} = (
                   9032:                                'found'   => 0,
                   9033:                                'total'   => 0,
                   9034:                               );
                   9035:             foreach my $line (@lines) {
                   9036:                 next if ($line =~ /^#/);
                   9037:                 next if ($line =~ /^[\s\cz]*$/);
                   9038:                 my $id = substr($line,$idstart-1,$idlength);
                   9039:                 $id = lc($id);
                   9040:                 if (exists($idmap{$id})) {
                   9041:                     $counts{$key}{'found'} ++;
                   9042:                 }
                   9043:                 $counts{$key}{'total'} ++;
                   9044:             }
                   9045:             if ($counts{$key}{'total'}) {
                   9046:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9047:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9048:                     $max_match_pct = $percent_match;
                   9049:                     $max_match_format = $key;
1.710     bisitz   9050:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9051:                     $max_match_count = $counts{$key}{'total'};
                   9052:                 }
                   9053:             }
                   9054:         }
                   9055:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9056:             my $format_descs;
                   9057:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9058:             for (my $i=0; $i<$numwithformat; $i++) {
                   9059:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9060:                 if ($i<$numwithformat-2) {
                   9061:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9062:                 } elsif ($i==$numwithformat-2) {
                   9063:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9064:                 } elsif ($i==$numwithformat-1) {
                   9065:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9066:                 }
                   9067:             }
                   9068:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9069:             $output .= '<br />';
                   9070:             if ($found_match_count == $max_match_count) {
                   9071:                 # 100% matching entries
                   9072:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9073:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9074:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9075:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9076:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9077:                     ' in the file (for the format defined for [_3]).',
                   9078:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9079:             } else {
                   9080:                 # Not all entries matching? -> Show warning and additional info
                   9081:                 $output .=
                   9082:                     &Apache::lonhtmlcommon::confirm_success(
                   9083:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9084:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9085:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9086:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9087:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9088:                         ' in the file (for the format defined for [_3]).',
                   9089:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9090:                     '<p class="LC_info">'.
                   9091:                     &mt('A low percentage of matches results from one of the following:').
                   9092:                     '</p><ul>'.
                   9093:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9094:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9095:                                '<i>'.$cdom.'</i>').'</li>'.
                   9096:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9097:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9098:                     '</ul>';
                   9099:             }
1.567     raeburn  9100:         }
                   9101:     } else {
1.710     bisitz   9102:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9103:     }
                   9104:     return $output;
                   9105: }
                   9106: 
1.202     albertel 9107: sub valid_file {
                   9108:     my ($requested_file)=@_;
                   9109:     foreach my $filename (sort(&scantron_filenames())) {
                   9110: 	if ($requested_file eq $filename) { return 1; }
                   9111:     }
                   9112:     return 0;
                   9113: }
                   9114: 
                   9115: sub scantron_download_scantron_data {
1.608     www      9116:     my ($r,$symb)=@_;
                   9117:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9118:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9119:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9120:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9121:     if (! &valid_file($file)) {
1.492     albertel 9122: 	$r->print('
1.202     albertel 9123: 	<p>
1.686     bisitz   9124: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9125:         </p>
1.492     albertel 9126: ');
1.202     albertel 9127: 	return;
                   9128:     }
                   9129:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9130:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9131:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9132:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9133:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9134:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9135:     $r->print('
1.202     albertel 9136:     <p>
1.723     raeburn  9137: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9138: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9139:     </p>
                   9140:     <p>
1.492     albertel 9141: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9142: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9143:     </p>
                   9144:     <p>
1.492     albertel 9145: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9146: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9147:     </p>
1.492     albertel 9148: ');
1.202     albertel 9149:     return '';
                   9150: }
1.157     albertel 9151: 
1.523     raeburn  9152: sub checkscantron_results {
1.608     www      9153:     my ($r,$symb) = @_;
1.523     raeburn  9154:     if (!$symb) {return '';}
                   9155:     my $cid = $env{'request.course.id'};
1.542     raeburn  9156:     my %lettdig = &letter_to_digits();
1.523     raeburn  9157:     my $numletts = scalar(keys(%lettdig));
                   9158:     my $cnum = $env{'course.'.$cid.'.num'};
                   9159:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9160:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9161:     my %record;
                   9162:     my %scantron_config =
                   9163:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9164:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9165:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9166:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9167:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9168:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9169:     unless (ref($navmap)) {
                   9170:         $r->print(&navmap_errormsg());
                   9171:         return '';
                   9172:     }
1.523     raeburn  9173:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9174:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9175:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9176:     if (ref($map)) { 
                   9177:         $randomorder=$map->randomorder();
1.689     raeburn  9178:         $randompick=$map->randompick();
1.677     raeburn  9179:     }
1.557     raeburn  9180:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9181:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9182:     if ($nav_error) {
                   9183:         $r->print(&navmap_errormsg());
                   9184:         return '';
1.678     raeburn  9185:     }
1.673     raeburn  9186:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9187:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9188:     my ($uname,$udom);
1.523     raeburn  9189:     my (%scandata,%lastname,%bylast);
                   9190:     $r->print('
                   9191: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9192: 
                   9193:     my @delayqueue;
                   9194:     my %completedstudents;
                   9195: 
1.691     raeburn  9196:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9197:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9198:     my ($username,$domain,$started);
1.649     raeburn  9199:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9200:     if ($nav_error) {
                   9201:         $r->print(&navmap_errormsg());
                   9202:         return '';
                   9203:     }
1.523     raeburn  9204: 
1.667     www      9205:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9206:     my $start=&Time::HiRes::time();
                   9207:     my $i=-1;
                   9208: 
                   9209:     while ($i<$scanlines->{'count'}) {
                   9210:         ($username,$domain,$uname)=('','','');
                   9211:         $i++;
                   9212:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9213:         if ($line=~/^[\s\cz]*$/) { next; }
                   9214:         if ($started) {
1.667     www      9215:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9216:         }
                   9217:         $started=1;
                   9218:         my $scan_record=
                   9219:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9220:                                                      $scan_data);
1.693     raeburn  9221:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9222:                                               \%idmap,$i)) {
1.523     raeburn  9223:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9224:                                 'Unable to find a student that matches',1);
                   9225:             next;
                   9226:         }
                   9227:         if (exists $completedstudents{$uname}) {
                   9228:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9229:                                 'Student '.$uname.' has multiple sheets',2);
                   9230:             next;
                   9231:         }
                   9232:         my $pid = $scan_record->{'scantron.ID'};
                   9233:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9234:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9235:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9236:         my $user = $uname.':'.$usec;
1.523     raeburn  9237:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9238: 
1.678     raeburn  9239:         my $scancode;
1.677     raeburn  9240:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9241:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9242:             $scancode = $scan_record->{'scantron.CODE'};
                   9243:         } else {
                   9244:             $scancode = '';
                   9245:         }
                   9246: 
                   9247:         my @mapresources = @resources;
1.691     raeburn  9248:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9249:         my %respnumlookup=();
                   9250:         my %startline=();
1.689     raeburn  9251:         if ($randomorder || $randompick) {
1.678     raeburn  9252:             @mapresources =
1.691     raeburn  9253:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9254:                              \%orderedforcode);
                   9255:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9256:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9257:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9258:                                              \%respnumlookup,\%startline);
                   9259:             if ($randompick && $total) {
                   9260:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9261:             }
1.677     raeburn  9262:         }
1.691     raeburn  9263:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9264:         chomp($scandata{$pid});
                   9265:         $scandata{$pid} =~ s/\r$//;
                   9266: 
1.523     raeburn  9267:         my $counter = -1;
1.677     raeburn  9268:         foreach my $resource (@mapresources) {
1.557     raeburn  9269:             my $parts;
1.554     raeburn  9270:             my $ressymb = $resource->symb();
1.557     raeburn  9271:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9272:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741   ! raeburn  9273:                 my $currcode;
        !          9274:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
        !          9275:                     $currcode = $scancode;
        !          9276:                 }
1.557     raeburn  9277:                 (my $analysis,$parts) =
1.672     raeburn  9278:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9279:                                               $username,$domain,undef,
1.741   ! raeburn  9280:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9281:             } else {
                   9282:                 $parts = $grader_partids_by_symb{$ressymb};
                   9283:             }
1.542     raeburn  9284:             ($counter,my $recording) =
                   9285:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9286:                                          $scandata{$pid},$parts,
1.691     raeburn  9287:                                          \%scantron_config,\%lettdig,$numletts,
                   9288:                                          $randomorder,$randompick,
                   9289:                                          \%respnumlookup,\%startline);
1.542     raeburn  9290:             $record{$pid} .= $recording;
1.523     raeburn  9291:         }
                   9292:     }
                   9293:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9294:     $r->print('<br />');
                   9295:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9296:     $passed = 0;
                   9297:     $failed = 0;
                   9298:     $numstudents = 0;
                   9299:     foreach my $last (sort(keys(%bylast))) {
                   9300:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9301:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9302:                 my $showscandata = $scandata{$pid};
                   9303:                 my $showrecord = $record{$pid};
                   9304:                 $showscandata =~ s/\s/&nbsp;/g;
                   9305:                 $showrecord =~ s/\s/&nbsp;/g;
                   9306:                 if ($scandata{$pid} eq $record{$pid}) {
                   9307:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9308:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9309: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9310: '</tr>'."\n".
                   9311: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9312: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9313:                     $passed ++;
                   9314:                 } else {
                   9315:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9316:                     $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  9317: '</tr>'."\n".
                   9318: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9319: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9320: '</tr>'."\n";
                   9321:                     $failed ++;
                   9322:                 }
                   9323:                 $numstudents ++;
                   9324:             }
                   9325:         }
                   9326:     }
1.648     bisitz   9327:     $r->print(
                   9328:         '<p>'
                   9329:        .&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).',
                   9330:             '<b>',
                   9331:             $numstudents,
                   9332:             '</b>',
                   9333:             $env{'form.scantron_maxbubble'})
                   9334:        .'</p>'
                   9335:     );
1.682     raeburn  9336:     $r->print('<p>'
1.683     raeburn  9337:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9338:              .'<br />'
                   9339:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9340:              .'</p>'
                   9341:     );
1.523     raeburn  9342:     if ($passed) {
1.572     www      9343:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9344:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9345:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9346:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9347:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9348:                  $okstudents."\n".
                   9349:                  &Apache::loncommon::end_data_table().'<br />');
                   9350:     }
                   9351:     if ($failed) {
1.572     www      9352:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9353:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9354:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9355:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9356:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9357:                  $badstudents."\n".
                   9358:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9359:                  &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  9360:     }
1.614     www      9361:     $r->print('</form><br />');
1.523     raeburn  9362:     return;
                   9363: }
                   9364: 
1.542     raeburn  9365: sub verify_scantron_grading {
1.554     raeburn  9366:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9367:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9368:         $respnumlookup,$startline) = @_;
1.542     raeburn  9369:     my ($record,%expected,%startpos);
                   9370:     return ($counter,$record) if (!ref($resource));
                   9371:     return ($counter,$record) if (!$resource->is_problem());
                   9372:     my $symb = $resource->symb();
1.554     raeburn  9373:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9374:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9375:         $counter ++;
                   9376:         $expected{$part_id} = 0;
1.691     raeburn  9377:         my $respnum = $counter;
                   9378:         if ($randomorder || $randompick) {
                   9379:             $respnum = $respnumlookup->{$counter};
                   9380:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9381:         } else {
                   9382:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9383:         }
                   9384:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9385:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9386:             foreach my $item (@sub_lines) {
                   9387:                 $expected{$part_id} += $item;
                   9388:             }
                   9389:         } else {
1.691     raeburn  9390:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9391:         }
                   9392:     }
                   9393:     if ($symb) {
                   9394:         my %recorded;
                   9395:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9396:         if ($returnhash{'version'}) {
                   9397:             my %lasthash=();
                   9398:             my $version;
                   9399:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9400:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9401:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9402:                 }
                   9403:             }
                   9404:             foreach my $key (keys(%lasthash)) {
                   9405:                 if ($key =~ /\.scantron$/) {
                   9406:                     my $value = &unescape($lasthash{$key});
                   9407:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9408:                     if ($value eq '') {
                   9409:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9410:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9411:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9412:                             }
                   9413:                         }
                   9414:                     } else {
                   9415:                         my @tocheck;
                   9416:                         my @items = split(//,$value);
                   9417:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9418:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9419:                             if (@items < $expected{$part_id}) {
                   9420:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9421:                                 my @singles = split(//,$fragment);
                   9422:                                 foreach my $pos (@singles) {
                   9423:                                     if ($pos eq ' ') {
                   9424:                                         push(@tocheck,$pos);
                   9425:                                     } else {
                   9426:                                         my $next = shift(@items);
                   9427:                                         push(@tocheck,$next);
                   9428:                                     }
                   9429:                                 }
                   9430:                             } else {
                   9431:                                 @tocheck = @items;
                   9432:                             }
                   9433:                             foreach my $letter (@tocheck) {
                   9434:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9435:                                     if ($letter !~ /^[A-J]$/) {
                   9436:                                         $letter = $scantron_config->{'Qoff'};
                   9437:                                     }
                   9438:                                     $recorded{$part_id} .= $letter;
                   9439:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9440:                                     my $digit;
                   9441:                                     if ($letter !~ /^[A-J]$/) {
                   9442:                                         $digit = $scantron_config->{'Qoff'};
                   9443:                                     } else {
                   9444:                                         $digit = $lettdig->{$letter};
                   9445:                                     }
                   9446:                                     $recorded{$part_id} .= $digit;
                   9447:                                 }
                   9448:                             }
                   9449:                         } else {
                   9450:                             @tocheck = @items;
                   9451:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9452:                                 my $curr_sub = shift(@tocheck);
                   9453:                                 my $digit;
                   9454:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9455:                                     $digit = $lettdig->{$curr_sub}-1;
                   9456:                                 }
                   9457:                                 if ($curr_sub eq 'J') {
                   9458:                                     $digit += scalar($numletts);
                   9459:                                 }
                   9460:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9461:                                     if ($j == $digit) {
                   9462:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9463:                                     } else {
                   9464:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9465:                                     }
                   9466:                                 }
                   9467:                             }
                   9468:                         }
                   9469:                     }
                   9470:                 }
                   9471:             }
                   9472:         }
1.554     raeburn  9473:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9474:             if ($recorded{$part_id} eq '') {
                   9475:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9476:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9477:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9478:                     }
                   9479:                 }
                   9480:             }
                   9481:             $record .= $recorded{$part_id};
                   9482:         }
                   9483:     }
                   9484:     return ($counter,$record);
                   9485: }
                   9486: 
1.691     raeburn  9487: sub letter_to_digits {
1.542     raeburn  9488:     my %lettdig = (
                   9489:                     A => 1,
                   9490:                     B => 2,
                   9491:                     C => 3,
                   9492:                     D => 4,
                   9493:                     E => 5,
                   9494:                     F => 6,
                   9495:                     G => 7,
                   9496:                     H => 8,
                   9497:                     I => 9,
                   9498:                     J => 0,
                   9499:                   );
                   9500:     return %lettdig;
                   9501: }
                   9502: 
1.423     albertel 9503: 
1.75      albertel 9504: #-------- end of section for handling grading scantron forms -------
                   9505: #
                   9506: #-------------------------------------------------------------------
                   9507: 
1.72      ng       9508: #-------------------------- Menu interface -------------------------
                   9509: #
1.614     www      9510: #--- Href with symb and command ---
                   9511: 
                   9512: sub href_symb_cmd {
                   9513:     my ($symb,$cmd)=@_;
1.669     raeburn  9514:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9515: }
                   9516: 
1.443     banghart 9517: sub grading_menu {
1.608     www      9518:     my ($request,$symb) = @_;
1.443     banghart 9519:     if (!$symb) {return '';}
                   9520: 
                   9521:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9522:                   'command'=>'individual');
1.538     schulted 9523:     
1.598     www      9524:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9525: 
                   9526:     $fields{'command'}='ungraded';
                   9527:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9528: 
                   9529:     $fields{'command'}='table';
                   9530:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9531: 
                   9532:     $fields{'command'}='all_for_one';
                   9533:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9534: 
1.621     www      9535:     $fields{'command'}='downloadfilesselect';
                   9536:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9537: 
1.443     banghart 9538:     $fields{'command'} = 'csvform';
1.538     schulted 9539:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9540:     
1.443     banghart 9541:     $fields{'command'} = 'processclicker';
1.538     schulted 9542:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9543:     
1.443     banghart 9544:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9545:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9546: 
                   9547:     $fields{'command'} = 'initialverifyreceipt';
                   9548:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9549:     
1.598     www      9550:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9551:             items =>[
1.598     www      9552:                         {	linktext => 'Select individual students to grade',
                   9553:                     		url => $url1a,
1.538     schulted 9554:                     		permission => 'F',
1.636     wenzelju 9555:                     		icon => 'grade_students.png',
1.598     www      9556:                     		linktitle => 'Grade current resource for a selection of students.'
                   9557:                         }, 
                   9558:                         {       linktext => 'Grade ungraded submissions.',
                   9559:                                 url => $url1b,
                   9560:                                 permission => 'F',
1.636     wenzelju 9561:                                 icon => 'ungrade_sub.png',
1.598     www      9562:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9563:                         },
1.598     www      9564: 
                   9565:                         {       linktext => 'Grading table',
                   9566:                                 url => $url1c,
                   9567:                                 permission => 'F',
1.636     wenzelju 9568:                                 icon => 'grading_table.png',
1.598     www      9569:                                 linktitle => 'Grade current resource for all students.'
                   9570:                         },
1.615     www      9571:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9572:                                 url => $url1d,
                   9573:                                 permission => 'F',
1.636     wenzelju 9574:                                 icon => 'grade_PageFolder.png',
1.598     www      9575:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9576:                         },
                   9577:                         {       linktext => 'Download submissions',
                   9578:                                 url => $url1e,
                   9579:                                 permission => 'F',
1.636     wenzelju 9580:                                 icon => 'download_sub.png',
1.621     www      9581:                                 linktitle => 'Download all students submissions.'
1.598     www      9582:                         }]},
                   9583:                          { categorytitle=>'Automated Grading',
                   9584:                items =>[
                   9585: 
1.538     schulted 9586:                 	    {	linktext => 'Upload Scores',
                   9587:                     		url => $url2,
                   9588:                     		permission => 'F',
                   9589:                     		icon => 'uploadscores.png',
                   9590:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9591:                 	    },
                   9592:                 	    {	linktext => 'Process Clicker',
                   9593:                     		url => $url3,
                   9594:                     		permission => 'F',
                   9595:                     		icon => 'addClickerInfoFile.png',
                   9596:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9597:                 	    },
1.587     raeburn  9598:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9599:                     		url => $url4,
                   9600:                     		permission => 'F',
1.636     wenzelju 9601:                     		icon => 'bubblesheet.png',
1.648     bisitz   9602:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9603:                 	    },
1.616     www      9604:                             {   linktext => 'Verify Receipt Number',
1.602     www      9605:                                 url => $url5,
                   9606:                                 permission => 'F',
1.636     wenzelju 9607:                                 icon => 'receipt_number.png',
1.602     www      9608:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9609:                             }
                   9610: 
1.538     schulted 9611:                     ]
                   9612:             });
                   9613: 
1.443     banghart 9614:     # Create the menu
                   9615:     my $Str;
1.445     banghart 9616:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9617:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9618:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9619: 
1.602     www      9620:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9621:     return $Str;    
                   9622: }
                   9623: 
1.598     www      9624: 
                   9625: sub ungraded {
                   9626:     my ($request)=@_;
                   9627:     &submit_options($request);
                   9628: }
                   9629: 
1.599     www      9630: sub submit_options_sequence {
1.608     www      9631:     my ($request,$symb) = @_;
1.599     www      9632:     if (!$symb) {return '';}
1.600     www      9633:     &commonJSfunctions($request);
                   9634:     my $result;
1.599     www      9635: 
1.600     www      9636:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9637:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9638:     $result.=&selectfield(0).
1.601     www      9639:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9640:             <div>
                   9641:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9642:             </div>
                   9643:         </div>
                   9644:   </form>';
                   9645:     return $result;
                   9646: }
                   9647: 
                   9648: sub submit_options_table {
1.608     www      9649:     my ($request,$symb) = @_;
1.600     www      9650:     if (!$symb) {return '';}
1.599     www      9651:     &commonJSfunctions($request);
                   9652:     my $result;
                   9653: 
                   9654:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9655:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9656: 
1.738     raeburn  9657:     $result.=&selectfield(1).
1.601     www      9658:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9659:             <div>
                   9660:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9661:             </div>
                   9662:         </div>
                   9663:   </form>';
                   9664:     return $result;
                   9665: }
1.443     banghart 9666: 
1.621     www      9667: sub submit_options_download {
                   9668:     my ($request,$symb) = @_;
                   9669:     if (!$symb) {return '';}
                   9670: 
                   9671:     &commonJSfunctions($request);
                   9672: 
                   9673:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9674:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9675:     $result.='
                   9676: <h2>
                   9677:   '.&mt('Select Students for Which to Download Submissions').'
                   9678: </h2>'.&selectfield(1).'
                   9679:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9680:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9681:             </div>
                   9682:           </div>
1.600     www      9683: 
                   9684: 
1.621     www      9685:   </form>';
                   9686:     return $result;
                   9687: }
                   9688: 
1.443     banghart 9689: #--- Displays the submissions first page -------
                   9690: sub submit_options {
1.608     www      9691:     my ($request,$symb) = @_;
1.72      ng       9692:     if (!$symb) {return '';}
                   9693: 
1.118     ng       9694:     &commonJSfunctions($request);
1.473     albertel 9695:     my $result;
1.533     bisitz   9696: 
1.72      ng       9697:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9698: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9699:     $result.=&selectfield(1).'
1.601     www      9700:                 <input type="hidden" name="command" value="submission" /> 
                   9701: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9702:             </div>
                   9703:           </div>
                   9704: 
                   9705: 
                   9706:   </form>';
                   9707:     return $result;
                   9708: }
1.533     bisitz   9709: 
1.601     www      9710: sub selectfield {
                   9711:    my ($full)=@_;
1.635     raeburn  9712:    my %options = 
1.738     raeburn  9713:           (&substatus_options,
                   9714:            'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9715:    my $result='<div class="LC_columnSection">
1.537     harmsja  9716:   
1.533     bisitz   9717:     <fieldset>
                   9718:       <legend>
                   9719:        '.&mt('Sections').'
                   9720:       </legend>
1.601     www      9721:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9722:     </fieldset>
1.537     harmsja  9723:   
1.533     bisitz   9724:     <fieldset>
                   9725:       <legend>
                   9726:         '.&mt('Groups').'
                   9727:       </legend>
                   9728:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9729:     </fieldset>
1.537     harmsja  9730:   
1.533     bisitz   9731:     <fieldset>
                   9732:       <legend>
                   9733:         '.&mt('Access Status').'
                   9734:       </legend>
1.601     www      9735:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9736:     </fieldset>';
                   9737:     if ($full) {
                   9738:        $result.='
1.533     bisitz   9739:     <fieldset>
                   9740:       <legend>
                   9741:         '.&mt('Submission Status').'
1.601     www      9742:       </legend>'.
1.635     raeburn  9743:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9744:    '</fieldset>';
                   9745:     }
                   9746:     $result.='</div><br />';
1.44      ng       9747:     return $result;
1.2       albertel 9748: }
                   9749: 
1.738     raeburn  9750: sub substatus_options {
                   9751:     return &Apache::lonlocal::texthash(
                   9752:                                       'yes'       => 'with submissions',
                   9753:                                       'queued'    => 'in grading queue',
                   9754:                                       'graded'    => 'with ungraded submissions',
                   9755:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  9756:                                       'all'       => 'with any status',
                   9757:                                       );
1.738     raeburn  9758: }
                   9759: 
1.285     albertel 9760: sub reset_perm {
                   9761:     undef(%perm);
                   9762: }
                   9763: 
                   9764: sub init_perm {
                   9765:     &reset_perm();
1.300     albertel 9766:     foreach my $test_perm ('vgr','mgr','opa') {
                   9767: 
                   9768: 	my $scope = $env{'request.course.id'};
                   9769: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9770: 
                   9771: 	    $scope .= '/'.$env{'request.course.sec'};
                   9772: 	    if ( $perm{$test_perm}=
                   9773: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9774: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9775: 	    } else {
                   9776: 		delete($perm{$test_perm});
                   9777: 	    }
1.285     albertel 9778: 	}
                   9779:     }
                   9780: }
                   9781: 
1.674     raeburn  9782: sub init_old_essays {
                   9783:     my ($symb,$apath,$adom,$aname) = @_;
                   9784:     if ($symb ne '') {
                   9785:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9786:         if (keys(%essays) > 0) {
                   9787:             $old_essays{$symb} = \%essays;
                   9788:         }
                   9789:     }
                   9790:     return;
                   9791: }
                   9792: 
                   9793: sub reset_old_essays {
                   9794:     undef(%old_essays);
                   9795: }
                   9796: 
1.400     www      9797: sub gather_clicker_ids {
1.408     albertel 9798:     my %clicker_ids;
1.400     www      9799: 
                   9800:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9801: 
                   9802:     # Set up a couple variables.
1.407     albertel 9803:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9804:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9805:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9806: 
1.407     albertel 9807:     foreach my $student (keys(%$classlist)) {
1.438     www      9808:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9809:         my $username = $classlist->{$student}->[$username_idx];
                   9810:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9811:         my $clickers =
1.408     albertel 9812: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9813:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9814:             $id=~s/^[\#0]+//;
1.421     www      9815:             $id=~s/[\-\:]//g;
1.407     albertel 9816:             if (exists($clicker_ids{$id})) {
1.408     albertel 9817: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9818:             } else {
1.408     albertel 9819: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9820:             }
                   9821:         }
                   9822:     }
1.407     albertel 9823:     return %clicker_ids;
1.400     www      9824: }
                   9825: 
1.402     www      9826: sub gather_adv_clicker_ids {
1.408     albertel 9827:     my %clicker_ids;
1.402     www      9828:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9829:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9830:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9831:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9832:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9833:             my ($puname,$pudom)=split(/\:/,$person);
                   9834:             my $clickers =
1.408     albertel 9835: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9836:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9837: 		$id=~s/^[\#0]+//;
1.421     www      9838:                 $id=~s/[\-\:]//g;
1.408     albertel 9839: 		if (exists($clicker_ids{$id})) {
                   9840: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9841: 		} else {
                   9842: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9843: 		}
1.405     www      9844:             }
1.402     www      9845:         }
                   9846:     }
1.407     albertel 9847:     return %clicker_ids;
1.402     www      9848: }
                   9849: 
1.413     www      9850: sub clicker_grading_parameters {
                   9851:     return ('gradingmechanism' => 'scalar',
                   9852:             'upfiletype' => 'scalar',
                   9853:             'specificid' => 'scalar',
                   9854:             'pcorrect' => 'scalar',
                   9855:             'pincorrect' => 'scalar');
                   9856: }
                   9857: 
1.400     www      9858: sub process_clicker {
1.608     www      9859:     my ($r,$symb)=@_;
1.400     www      9860:     if (!$symb) {return '';}
                   9861:     my $result=&checkforfile_js();
1.632     www      9862:     $result.=&Apache::loncommon::start_data_table().
                   9863:              &Apache::loncommon::start_data_table_header_row().
                   9864:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9865:              &Apache::loncommon::end_data_table_header_row().
                   9866:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9867: # Attempt to restore parameters from last session, set defaults if not present
                   9868:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9869:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9870:                                                  \%Saveable_Parameters);
                   9871:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9872:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9873:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9874:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9875: 
                   9876:     my %checked;
1.521     www      9877:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9878:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9879:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9880:        }
                   9881:     }
                   9882: 
1.632     www      9883:     my $upload=&mt("Evaluate File");
1.400     www      9884:     my $type=&mt("Type");
1.402     www      9885:     my $attendance=&mt("Award points just for participation");
                   9886:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9887:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9888:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9889:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9890:     my $pcorrect=&mt("Percentage points for correct solution");
                   9891:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9892:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9893: 						   {'iclicker' => 'i>clicker',
1.666     www      9894:                                                     'interwrite' => 'interwrite PRS',
                   9895:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9896:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9897:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9898: function sanitycheck() {
                   9899: // Accept only integer percentages
                   9900:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9901:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9902: // Find out grading choice
                   9903:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9904:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9905:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9906:       }
                   9907:    }
                   9908: // By default, new choice equals user selection
                   9909:    newgradingchoice=gradingchoice;
                   9910: // Not good to give more points for false answers than correct ones
                   9911:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9912:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9913:    }
                   9914: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9915:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9916:       document.forms.gradesupload.pcorrect.value=100;
                   9917:       document.forms.gradesupload.pincorrect.value=100;
                   9918:    }
                   9919: // If the values are different, cannot be attendance only
                   9920:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9921:        (gradingchoice=='attendance')) {
                   9922:        newgradingchoice='personnel';
                   9923:    }
                   9924: // Change grading choice to new one
                   9925:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9926:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9927:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9928:       } else {
                   9929:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9930:       }
                   9931:    }
                   9932: // Remember the old state
                   9933:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9934: }
1.597     wenzelju 9935: ENDUPFORM
                   9936:     $result.= <<ENDUPFORM;
1.400     www      9937: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9938: <input type="hidden" name="symb" value="$symb" />
                   9939: <input type="hidden" name="command" value="processclickerfile" />
                   9940: <input type="file" name="upfile" size="50" />
                   9941: <br /><label>$type: $selectform</label>
1.632     www      9942: ENDUPFORM
                   9943:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9944:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9945:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9946: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9947: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9948: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9949: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9950: <br />&nbsp;&nbsp;&nbsp;
                   9951: <input type="text" name="givenanswer" size="50" />
1.413     www      9952: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9953: ENDGRADINGFORM
                   9954:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9955:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9956:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9957: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9958: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9959: </form>'
1.632     www      9960: ENDPERCFORM
                   9961:     $result.='</td>'.
                   9962:              &Apache::loncommon::end_data_table_row().
                   9963:              &Apache::loncommon::end_data_table();
1.400     www      9964:     return $result;
                   9965: }
                   9966: 
                   9967: sub process_clicker_file {
1.608     www      9968:     my ($r,$symb)=@_;
1.400     www      9969:     if (!$symb) {return '';}
1.413     www      9970: 
                   9971:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9972:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9973:                                               \%Saveable_Parameters);
1.598     www      9974:     my $result='';
1.404     www      9975:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9976: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9977: 	return $result;
1.404     www      9978:     }
1.522     www      9979:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9980:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9981:         return $result;
1.521     www      9982:     }
1.522     www      9983:     my $foundgiven=0;
1.521     www      9984:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9985:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9986:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9987:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9988:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9989:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9990:         $foundgiven=$#answers+1;
1.521     www      9991:     }
1.407     albertel 9992:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9993:     my %correct_ids;
1.404     www      9994:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9995: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9996:     }
                   9997:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9998: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9999: 	   $correct_id=~tr/a-z/A-Z/;
                   10000: 	   $correct_id=~s/\s//gs;
                   10001: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10002:            $correct_id=~s/[\-\:]//g;
1.414     www      10003:            if ($correct_id) {
                   10004: 	      $correct_ids{$correct_id}='specified';
                   10005:            }
                   10006:         }
1.400     www      10007:     }
1.404     www      10008:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10009: 	$result.=&mt('Score based on attendance only');
1.521     www      10010:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10011:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10012:     } else {
1.408     albertel 10013: 	my $number=0;
1.411     www      10014: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10015: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10016: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10017: 	    if ($correct_ids{$id} eq 'specified') {
                   10018: 		$result.=&mt('specified');
                   10019: 	    } else {
                   10020: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10021: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10022: 	    }
                   10023: 	    $number++;
                   10024: 	}
1.411     www      10025:         $result.="</p>\n";
1.710     bisitz   10026:         if ($number==0) {
                   10027:             $result .=
                   10028:                  &Apache::lonhtmlcommon::confirm_success(
                   10029:                      &mt('No IDs found to determine correct answer'),1);
                   10030:             return $result;
                   10031:         }
1.404     www      10032:     }
1.405     www      10033:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10034:         $result .=
                   10035:             &Apache::lonhtmlcommon::confirm_success(
                   10036:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10037:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10038:         return $result;
1.405     www      10039:     }
1.410     www      10040: 
                   10041: # Were able to get all the info needed, now analyze the file
                   10042: 
1.411     www      10043:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10044:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10045:     $result.=&Apache::loncommon::start_data_table().
                   10046:              &Apache::loncommon::start_data_table_header_row().
                   10047:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10048:              &Apache::loncommon::end_data_table_header_row().
                   10049:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10050: <td>
1.410     www      10051: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10052: <input type="hidden" name="symb" value="$symb" />
                   10053: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10054: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10055: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10056: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10057: ENDHEADER
1.522     www      10058:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10059:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10060:     } 
1.408     albertel 10061:     my %responses;
                   10062:     my @questiontitles;
1.405     www      10063:     my $errormsg='';
                   10064:     my $number=0;
                   10065:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10066: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10067:     }
1.419     www      10068:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10069:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10070:     }
1.666     www      10071:     if ($env{'form.upfiletype'} eq 'turning') {
                   10072:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10073:     }
1.411     www      10074:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10075:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10076:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10077:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10078:              '<br />';
1.522     www      10079:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10080:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10081:        return $result;
1.522     www      10082:     } 
1.414     www      10083: # Remember Question Titles
                   10084: # FIXME: Possibly need delimiter other than ":"
                   10085:     for (my $i=0;$i<$number;$i++) {
                   10086:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10087:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10088:     }
1.411     www      10089:     my $correct_count=0;
                   10090:     my $student_count=0;
                   10091:     my $unknown_count=0;
1.414     www      10092: # Match answers with usernames
                   10093: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10094:     foreach my $id (keys(%responses)) {
1.410     www      10095:        if ($correct_ids{$id}) {
1.414     www      10096:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10097:           $correct_count++;
1.410     www      10098:        } elsif ($clicker_ids{$id}) {
1.437     www      10099:           if ($clicker_ids{$id}=~/\,/) {
                   10100: # More than one user with the same clicker!
1.632     www      10101:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10102:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10103:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10104:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10105:                            "<select name='multi".$id."'>";
                   10106:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10107:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10108:              }
                   10109:              $result.='</select>';
                   10110:              $unknown_count++;
                   10111:           } else {
                   10112: # Good: found one and only one user with the right clicker
                   10113:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10114:              $student_count++;
                   10115:           }
1.410     www      10116:        } else {
1.632     www      10117:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10118:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10119:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10120:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10121:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10122:                    "\n".&mt("Domain").": ".
                   10123:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      10124:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10125:           $unknown_count++;
1.410     www      10126:        }
1.405     www      10127:     }
1.412     www      10128:     $result.='<hr />'.
                   10129:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10130:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10131:        if ($correct_count==0) {
1.696     bisitz   10132:           $errormsg.="Found no correct answers for grading!";
1.412     www      10133:        } elsif ($correct_count>1) {
1.414     www      10134:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10135:        }
                   10136:     }
1.428     www      10137:     if ($number<1) {
                   10138:        $errormsg.="Found no questions.";
                   10139:     }
1.412     www      10140:     if ($errormsg) {
                   10141:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10142:     } else {
                   10143:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10144:     }
1.632     www      10145:     $result.='</form></td>'.
                   10146:              &Apache::loncommon::end_data_table_row().
                   10147:              &Apache::loncommon::end_data_table();
1.614     www      10148:     return $result;
1.400     www      10149: }
                   10150: 
1.405     www      10151: sub iclicker_eval {
1.406     www      10152:     my ($questiontitles,$responses)=@_;
1.405     www      10153:     my $number=0;
                   10154:     my $errormsg='';
                   10155:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10156:         my %components=&Apache::loncommon::record_sep($line);
                   10157:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10158: 	if ($entries[0] eq 'Question') {
                   10159: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10160: 		$$questiontitles[$number]=$entries[$i];
                   10161: 		$number++;
                   10162: 	    }
                   10163: 	}
                   10164: 	if ($entries[0]=~/^\#/) {
                   10165: 	    my $id=$entries[0];
                   10166: 	    my @idresponses;
                   10167: 	    $id=~s/^[\#0]+//;
                   10168: 	    for (my $i=0;$i<$number;$i++) {
                   10169: 		my $idx=3+$i*6;
1.644     www      10170:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10171: 		push(@idresponses,$entries[$idx]);
                   10172: 	    }
                   10173: 	    $$responses{$id}=join(',',@idresponses);
                   10174: 	}
1.405     www      10175:     }
                   10176:     return ($errormsg,$number);
                   10177: }
                   10178: 
1.419     www      10179: sub interwrite_eval {
                   10180:     my ($questiontitles,$responses)=@_;
                   10181:     my $number=0;
                   10182:     my $errormsg='';
1.420     www      10183:     my $skipline=1;
                   10184:     my $questionnumber=0;
                   10185:     my %idresponses=();
1.419     www      10186:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10187:         my %components=&Apache::loncommon::record_sep($line);
                   10188:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10189:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10190:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10191:         next if $skipline;
                   10192:         if ($entries[0]!=$questionnumber) {
                   10193:            $questionnumber=$entries[0];
                   10194:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10195:            $number++;
1.419     www      10196:         }
1.420     www      10197:         my $id=$entries[4];
                   10198:         $id=~s/^[\#0]+//;
1.421     www      10199:         $id=~s/^v\d*\://i;
                   10200:         $id=~s/[\-\:]//g;
1.420     www      10201:         $idresponses{$id}[$number]=$entries[6];
                   10202:     }
1.524     raeburn  10203:     foreach my $id (keys(%idresponses)) {
1.420     www      10204:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10205:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10206:     }
                   10207:     return ($errormsg,$number);
                   10208: }
                   10209: 
1.666     www      10210: sub turning_eval {
                   10211:     my ($questiontitles,$responses)=@_;
                   10212:     my $number=0;
                   10213:     my $errormsg='';
                   10214:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10215:         my %components=&Apache::loncommon::record_sep($line);
                   10216:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10217:         if ($#entries>$number) { $number=$#entries; }
                   10218:         my $id=$entries[0];
                   10219:         my @idresponses;
                   10220:         $id=~s/^[\#0]+//;
                   10221:         unless ($id) { next; }
                   10222:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10223:             $entries[$idx]=~s/\,/\;/g;
                   10224:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10225:             push(@idresponses,$entries[$idx]);
                   10226:         }
                   10227:         $$responses{$id}=join(',',@idresponses);
                   10228:     }
                   10229:     for (my $i=1; $i<=$number; $i++) {
                   10230:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10231:     }
                   10232:     return ($errormsg,$number);
                   10233: }
                   10234: 
                   10235: 
1.414     www      10236: sub assign_clicker_grades {
1.608     www      10237:     my ($r,$symb)=@_;
1.414     www      10238:     if (!$symb) {return '';}
1.416     www      10239: # See which part we are saving to
1.582     raeburn  10240:     my $res_error;
                   10241:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10242:     if ($res_error) {
                   10243:         return &navmap_errormsg();
                   10244:     }
1.416     www      10245: # FIXME: This should probably look for the first handgradeable part
                   10246:     my $part=$$partlist[0];
                   10247: # Start screen output
1.632     www      10248:     my $result=&Apache::loncommon::start_data_table().
                   10249:              &Apache::loncommon::start_data_table_header_row().
                   10250:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10251:              &Apache::loncommon::end_data_table_header_row().
                   10252:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10253: # Get correct result
                   10254: # FIXME: Possibly need delimiter other than ":"
                   10255:     my @correct=();
1.415     www      10256:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10257:     my $number=$env{'form.number'};
                   10258:     if ($gradingmechanism ne 'attendance') {
1.414     www      10259:        foreach my $key (keys(%env)) {
                   10260:           if ($key=~/^form\.correct\:/) {
                   10261:              my @input=split(/\,/,$env{$key});
                   10262:              for (my $i=0;$i<=$#input;$i++) {
                   10263:                  if (($correct[$i]) && ($input[$i]) &&
                   10264:                      ($correct[$i] ne $input[$i])) {
                   10265:                     $result.='<br /><span class="LC_warning">'.
                   10266:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10267:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10268:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10269:                     $correct[$i]=$input[$i];
                   10270:                  }
                   10271:              }
                   10272:           }
                   10273:        }
1.415     www      10274:        for (my $i=0;$i<$number;$i++) {
1.644     www      10275:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10276:              $result.='<br /><span class="LC_error">'.
                   10277:                       &mt('No correct result given for question "[_1]"!',
                   10278:                           $env{'form.question:'.$i}).'</span>';
                   10279:           }
                   10280:        }
1.644     www      10281:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10282:     }
                   10283: # Start grading
1.415     www      10284:     my $pcorrect=$env{'form.pcorrect'};
                   10285:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10286:     my $storecount=0;
1.632     www      10287:     my %users=();
1.415     www      10288:     foreach my $key (keys(%env)) {
1.420     www      10289:        my $user='';
1.415     www      10290:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10291:           $user=$1;
                   10292:        }
                   10293:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10294:           my $id=$1;
                   10295:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10296:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10297:           } elsif ($env{'form.multi'.$id}) {
                   10298:              $user=$env{'form.multi'.$id};
1.420     www      10299:           }
                   10300:        }
1.632     www      10301:        if ($user) {
                   10302:           if ($users{$user}) {
                   10303:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10304:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10305:                       '</span><br />';
                   10306:           }
                   10307:           $users{$user}=1; 
1.415     www      10308:           my @answer=split(/\,/,$env{$key});
                   10309:           my $sum=0;
1.522     www      10310:           my $realnumber=$number;
1.415     www      10311:           for (my $i=0;$i<$number;$i++) {
1.576     www      10312:              if  ($correct[$i] eq '-') {
                   10313:                 $realnumber--;
1.644     www      10314:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10315:                 if ($gradingmechanism eq 'attendance') {
                   10316:                    $sum+=$pcorrect;
1.576     www      10317:                 } elsif ($correct[$i] eq '*') {
1.522     www      10318:                    $sum+=$pcorrect;
1.415     www      10319:                 } else {
1.644     www      10320: # We actually grade if correct or not
                   10321:                    my $increment=$pincorrect;
                   10322: # Special case: numerical answer "0"
                   10323:                    if ($correct[$i] eq '0') {
                   10324:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10325:                          $increment=$pcorrect;
                   10326:                       }
                   10327: # General numerical answer, both evaluate to something non-zero
                   10328:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10329:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10330:                          $increment=$pcorrect;
                   10331:                       }
                   10332: # Must be just alphanumeric
                   10333:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10334:                       $increment=$pcorrect;
1.415     www      10335:                    }
1.644     www      10336:                    $sum+=$increment;
1.415     www      10337:                 }
                   10338:              }
                   10339:           }
1.522     www      10340:           my $ave=$sum/(100*$realnumber);
1.416     www      10341: # Store
                   10342:           my ($username,$domain)=split(/\:/,$user);
                   10343:           my %grades=();
                   10344:           $grades{"resource.$part.solved"}='correct_by_override';
                   10345:           $grades{"resource.$part.awarded"}=$ave;
                   10346:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10347:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10348:                                                  $env{'request.course.id'},
                   10349:                                                  $domain,$username);
                   10350:           if ($returncode ne 'ok') {
                   10351:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10352:           } else {
                   10353:              $storecount++;
                   10354:           }
1.415     www      10355:        }
                   10356:     }
                   10357: # We are done
1.549     hauer    10358:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10359:              '</td>'.
                   10360:              &Apache::loncommon::end_data_table_row().
                   10361:              &Apache::loncommon::end_data_table();
1.614     www      10362:     return $result;
1.414     www      10363: }
                   10364: 
1.582     raeburn  10365: sub navmap_errormsg {
                   10366:     return '<div class="LC_error">'.
                   10367:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10368:            &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  10369:            '</div>';
                   10370: }
1.607     droeschl 10371: 
1.609     www      10372: sub startpage {
1.671     raeburn  10373:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10374:     if ($nomenu) {
                   10375:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10376:     } else {
                   10377:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10378:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10379:                                                  {'bread_crumbs' => $crumbs}));
                   10380:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10381:     }
1.613     www      10382:     unless ($nodisplayflag) {
1.671     raeburn  10383:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10384:     }
1.607     droeschl 10385: }
1.582     raeburn  10386: 
1.622     www      10387: sub select_problem {
                   10388:     my ($r)=@_;
1.632     www      10389:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10390:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10391:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10392:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10393: }
                   10394: 
1.1       albertel 10395: sub handler {
1.41      ng       10396:     my $request=$_[0];
1.434     albertel 10397:     &reset_caches();
1.646     raeburn  10398:     if ($request->header_only) {
                   10399:         &Apache::loncommon::content_type($request,'text/html');
                   10400:         $request->send_http_header;
                   10401:         return OK;
                   10402:     }
                   10403:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10404: 
1.664     raeburn  10405: # see what command we need to execute
                   10406: 
                   10407:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10408:     my $command=$commands[0];
                   10409: 
1.646     raeburn  10410:     &init_perm();
                   10411:     if (!$env{'request.course.id'}) {
1.664     raeburn  10412:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10413:                 ($command =~ /^scantronupload/)) {
                   10414:             # Not in a course.
                   10415:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10416:             return HTTP_NOT_ACCEPTABLE;
                   10417:         }
1.646     raeburn  10418:     } elsif (!%perm) {
                   10419:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10420:         return OK;
1.41      ng       10421:     }
1.646     raeburn  10422:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10423:     $request->send_http_header;
1.646     raeburn  10424: 
1.160     albertel 10425:     if ($#commands > 0) {
                   10426: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10427:     }
1.608     www      10428: 
                   10429: # see what the symb is
                   10430: 
                   10431:     my $symb=$env{'form.symb'};
                   10432:     unless ($symb) {
                   10433:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10434:        $symb=&Apache::lonnet::symbread($url);
                   10435:     }
1.646     raeburn  10436:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10437: 
1.513     foxr     10438:     $ssi_error = 0;
1.637     www      10439:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10440: #
1.637     www      10441: # Not called from a resource, but inside a course
1.601     www      10442: #    
1.622     www      10443:         &startpage($request,undef,[],1,1);
                   10444:         &select_problem($request);
1.41      ng       10445:     } else {
1.104     albertel 10446: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10447:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10448:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10449:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10450:                     &choose_task_version_form($symb,$env{'form.student'},
                   10451:                                               $env{'form.userdom'});
                   10452:             }
                   10453:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10454:             if ($versionform) {
                   10455:                 $request->print($versionform);
                   10456:             }
                   10457:             $request->print('<br clear="all" />');
1.611     www      10458: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10459:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10460:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10461:                 &choose_task_version_form($symb,$env{'form.student'},
                   10462:                                           $env{'form.userdom'},
                   10463:                                           $env{'form.inhibitmenu'});
                   10464:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10465:             if ($versionform) {
                   10466:                 $request->print($versionform);
                   10467:             }
                   10468:             $request->print('<br clear="all" />');
                   10469:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10470: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10471:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10472:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10473: 	    &pickStudentPage($request,$symb);
1.103     albertel 10474: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10475:             &startpage($request,$symb,
                   10476:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10477:                                        {href=>'',text=>'Select student'},
                   10478:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10479: 	    &displayPage($request,$symb);
1.104     albertel 10480: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10481:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10482:                                        {href=>'',text=>'Select student'},
                   10483:                                        {href=>'',text=>'Grade student'},
                   10484:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10485: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10486: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10487:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10488:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10489: 	    &processGroup($request,$symb);
1.104     albertel 10490: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10491:             &startpage($request,$symb);
                   10492: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10493: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10494:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10495: 	    $request->print(&submit_options($request,$symb));
1.598     www      10496:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10497:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10498:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10499:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10500:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10501:             $request->print(&submit_options_table($request,$symb));
1.598     www      10502:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10503:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10504:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10505: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10506:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10507: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10508: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10509:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10510:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10511: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10512: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10513:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10514:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10515:                                                                              text=>"Modify grades"},
                   10516:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10517: 	    $request->print(&editgrades($request,$symb));
1.602     www      10518:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10519:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10520:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10521: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10522:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10523:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10524: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10525:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10526:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10527:             $request->print(&process_clicker($request,$symb));
1.400     www      10528:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10529:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10530:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10531:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10532:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10533:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10534:                                        {href=>'', text=>'Process clicker file'},
                   10535:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10536:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10537: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10538:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10539: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10540: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10541:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10542: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10543: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10544:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10545: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10546: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10547: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10548:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10549: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10550: 	    } else {
1.257     albertel 10551: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10552: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10553: 		} else {
1.257     albertel 10554: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10555: 		}
1.627     www      10556:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10557: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10558: 	    }
1.246     albertel 10559: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10560:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10561: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10562: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10563:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10564: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10565:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10566:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10567:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10568: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10569:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10570: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10571: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10572:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10573: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10574:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10575:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10576: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10577:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10578:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10579:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10580:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10581: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10582:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10583:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10584:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10585: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10586:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10587:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10588:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10589:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10590:             $request->print(&checkscantron_results($request,$symb));
                   10591:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10592:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10593:             $request->print(&submit_options_download($request,$symb));
                   10594:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10595:             &startpage($request,$symb,
                   10596:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10597:     {href=>'', text=>'Download submissions'}]);
                   10598:             &submit_download_link($request,$symb);
1.106     albertel 10599: 	} elsif ($command) {
1.620     www      10600:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10601: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10602: 	}
1.2       albertel 10603:     }
1.513     foxr     10604:     if ($ssi_error) {
                   10605: 	&ssi_print_error($request);
                   10606:     }
1.671     raeburn  10607:     if ($env{'form.inhibitmenu'}) {
                   10608:         $request->print(&Apache::loncommon::end_page());
                   10609:     } else {
                   10610:         &Apache::lonquickgrades::endGradeScreen($request);
                   10611:     }
1.434     albertel 10612:     &reset_caches();
1.646     raeburn  10613:     return OK;
1.44      ng       10614: }
                   10615: 
1.1       albertel 10616: 1;
                   10617: 
1.13      albertel 10618: __END__;
1.531     jms      10619: 
                   10620: 
                   10621: =head1 NAME
                   10622: 
                   10623: Apache::grades
                   10624: 
                   10625: =head1 SYNOPSIS
                   10626: 
                   10627: Handles the viewing of grades.
                   10628: 
                   10629: This is part of the LearningOnline Network with CAPA project
                   10630: described at http://www.lon-capa.org.
                   10631: 
                   10632: =head1 OVERVIEW
                   10633: 
                   10634: Do an ssi with retries:
1.715     bisitz   10635: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10636: 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
                   10637: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10638: 
                   10639: At least the logic that drives this has been pulled out into loncommon.
                   10640: 
                   10641: 
                   10642: 
                   10643: ssi_with_retries - Does the server side include of a resource.
                   10644:                      if the ssi call returns an error we'll retry it up to
                   10645:                      the number of times requested by the caller.
1.715     bisitz   10646:                      If we still have a problem, no text is appended to the
1.531     jms      10647:                      output and we set some global variables.
                   10648:                      to indicate to the caller an SSI error occurred.  
                   10649:                      All of this is supposed to deal with the issues described
1.715     bisitz   10650:                      in LON-CAPA BZ 5631 see:
1.531     jms      10651:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10652:                      by informing the user that this happened.
                   10653: 
                   10654: Parameters:
                   10655:   resource   - The resource to include.  This is passed directly, without
                   10656:                interpretation to lonnet::ssi.
                   10657:   form       - The form hash parameters that guide the interpretation of the resource
                   10658:                
                   10659:   retries    - Number of retries allowed before giving up completely.
                   10660: Returns:
                   10661:   On success, returns the rendered resource identified by the resource parameter.
                   10662: Side Effects:
                   10663:   The following global variables can be set:
                   10664:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10665:                               It is up to the caller to initialize this to false
                   10666:                               if desired.
                   10667:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10668:                               of the resource that could not be rendered by the ssi
                   10669:                               call.
                   10670:    ssi_error_message   - The error string fetched from the ssi response
                   10671:                               in the event of an error.
                   10672: 
                   10673: 
                   10674: =head1 HANDLER SUBROUTINE
                   10675: 
                   10676: ssi_with_retries()
                   10677: 
                   10678: =head1 SUBROUTINES
                   10679: 
                   10680: =over
                   10681: 
1.671     raeburn  10682: =head1 Routines to display previous version of a Task for a specific student
                   10683: 
                   10684: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10685: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10686: requires a proctor to check-in the student, a new version of the Task will
                   10687: be created when the student is checked in to the new opportunity.
                   10688: 
                   10689: If a particular student has tried two or more versions of a particular task,
                   10690: the submission screen provides a user with vgr privileges (e.g., a Course
                   10691: Coordinator) the ability to display a previous version worked on by the
                   10692: student.  By default, the current version is displayed. If a previous version
                   10693: has been selected for display, submission data are only shown that pertain
                   10694: to that particular version, and the interface to submit grades is not shown.
                   10695: 
                   10696: =over 4
                   10697: 
                   10698: =item show_previous_task_version()
                   10699: 
                   10700: Displays a specified version of a student's Task, as the student sees it.
                   10701: 
                   10702: Inputs: 2
                   10703:         request - request object
                   10704:         symb    - unique symb for current instance of resource
                   10705: 
                   10706: Output: None.
                   10707: 
                   10708: Side Effects: calls &show_problem() to print version of Task, with
                   10709:               version contained in form item: $env{'form.previousversion'}
                   10710: 
                   10711: =item choose_task_version_form()
                   10712: 
                   10713: Displays a web form used to select which version of a student's view of a
                   10714: Task should be displayed.  Either launches a pop-up window, or replaces
                   10715: content in existing pop-up, or replaces page in main window.
                   10716: 
                   10717: Inputs: 4
                   10718:         symb    - unique symb for current instance of resource
                   10719:         uname   - username of student
                   10720:         udom    - domain of student
                   10721:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10722:                   breadcrumbs etc., are displayed
                   10723: 
                   10724: Output: 4
                   10725:         current   - student's current version
                   10726:         displayed - student's version being displayed
                   10727:         result    - scalar containing HTML for web form used to switch to
                   10728:                     a different version (or a link to close window, if pop-up).
                   10729:         js        - javascript for processing selection in versions web form
                   10730: 
                   10731: Side Effects: None.
                   10732: 
                   10733: =item previous_display_javascript()
                   10734: 
                   10735: Inputs: 2
                   10736:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10737:                   breadcrumbs etc., are displayed.
                   10738:         current - student's current version number.
                   10739: 
                   10740: Output: 1
                   10741:         js      - javascript for processing selection in versions web form.
                   10742: 
                   10743: Side Effects: None.
                   10744: 
                   10745: =back
                   10746: 
                   10747: =head1 Routines to process bubblesheet data.
                   10748: 
                   10749: =over 4
                   10750: 
1.531     jms      10751: =item scantron_get_correction() : 
                   10752: 
                   10753:    Builds the interface screen to interact with the operator to fix a
                   10754:    specific error condition in a specific scanline
                   10755: 
                   10756:  Arguments:
                   10757:     $r           - Apache request object
                   10758:     $i           - number of the current scanline
                   10759:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10760:     $scan_config - hash ref as returned from &get_scantron_config()
                   10761:     $line        - full contents of the current scanline
                   10762:     $error       - error condition, valid values are
                   10763:                    'incorrectCODE', 'duplicateCODE',
                   10764:                    'doublebubble', 'missingbubble',
                   10765:                    'duplicateID', 'incorrectID'
                   10766:     $arg         - extra information needed
                   10767:        For errors:
                   10768:          - duplicateID   - paper number that this studentID was seen before on
                   10769:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10770:                            seen on before
                   10771:          - incorrectCODE - current incorrect CODE 
                   10772:          - doublebubble  - array ref of the bubble lines that have double
                   10773:                            bubble errors
                   10774:          - missingbubble - array ref of the bubble lines that have missing
                   10775:                            bubble errors
                   10776: 
1.691     raeburn  10777:    $randomorder - True if exam folder has randomorder set
                   10778:    $randompick  - True if exam folder has randompick set
                   10779:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10780:                      for current line to question number used for same question
                   10781:                      in "Master Seqence" (as seen by Course Coordinator).
                   10782:    $startline   - Reference to hash where key is question number (0 is first)
                   10783:                   and value is number of first bubble line for current student
                   10784:                   or code-based randompick and/or randomorder.
                   10785: 
                   10786: 
                   10787: 
1.531     jms      10788: =item  scantron_get_maxbubble() : 
                   10789: 
1.582     raeburn  10790:    Arguments:
                   10791:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10792:                       failure to retrieve a navmap object.
                   10793:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10794:        calling routine should trap the error condition and display the warning
                   10795:        found in &navmap_errormsg().
                   10796: 
1.649     raeburn  10797:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10798: 
1.531     jms      10799:    Returns the maximum number of bubble lines that are expected to
                   10800:    occur. Does this by walking the selected sequence rendering the
                   10801:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10802:    for what the current value of the problem counter is.
                   10803: 
                   10804:    Caches the results to $env{'form.scantron_maxbubble'},
                   10805:    $env{'form.scantron.bubble_lines.n'}, 
                   10806:    $env{'form.scantron.first_bubble_line.n'} and
                   10807:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10808:    which are the total number of bubble lines, the number of bubble
1.531     jms      10809:    lines for response n and number of the first bubble line for response n,
                   10810:    and a comma separated list of numbers of bubble lines for sub-questions
                   10811:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10812: 
                   10813: 
                   10814: =item  scantron_validate_missingbubbles() : 
                   10815: 
                   10816:    Validates all scanlines in the selected file to not have any
                   10817:     answers that don't have bubbles that have not been verified
                   10818:     to be bubble free.
                   10819: 
                   10820: =item  scantron_process_students() : 
                   10821: 
1.659     raeburn  10822:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10823: 
                   10824:    The parsed scanline hash is added to %env 
                   10825: 
                   10826:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10827:    foreach resource , with the form data of
                   10828: 
                   10829: 	'submitted'     =>'scantron' 
                   10830: 	'grade_target'  =>'grade',
                   10831: 	'grade_username'=> username of student
                   10832: 	'grade_domain'  => domain of student
                   10833: 	'grade_courseid'=> of course
                   10834: 	'grade_symb'    => symb of resource to grade
                   10835: 
                   10836:     This triggers a grading pass. The problem grading code takes care
                   10837:     of converting the bubbled letter information (now in %env) into a
                   10838:     valid submission.
                   10839: 
                   10840: =item  scantron_upload_scantron_data() :
                   10841: 
1.659     raeburn  10842:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10843: 
                   10844: =item  scantron_upload_scantron_data_save() : 
                   10845: 
                   10846:    Adds a provided bubble information data file to the course if user
                   10847:    has the correct privileges to do so. 
                   10848: 
                   10849: =item  valid_file() :
                   10850: 
                   10851:    Validates that the requested bubble data file exists in the course.
                   10852: 
                   10853: =item  scantron_download_scantron_data() : 
                   10854: 
                   10855:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10856:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10857:    course.
                   10858: 
                   10859: =item  scantron_validate_ID() : 
                   10860: 
                   10861:    Validates all scanlines in the selected file to not have any
1.556     weissno  10862:    invalid or underspecified student/employee IDs
1.531     jms      10863: 
1.582     raeburn  10864: =item navmap_errormsg() :
                   10865: 
                   10866:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10867:    Should be called whenever the request to instantiate a navmap object fails.
                   10868: 
                   10869: =back
1.582     raeburn  10870: 
1.531     jms      10871: =back
                   10872: 
                   10873: =cut

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