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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.596.2.12.2.  5(raebur    4:5): # $Id: grades.pm,v 1.596.2.12.2.34 2015/03/17 12:37:40 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.596.2.4  raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.596.2.4  raeburn    46: use Apache::bridgetask();
1.170     albertel   47: use String::Similarity;
1.359     www        48: use LONCAPA;
                     49: 
1.315     bowersj2   50: use POSIX qw(floor);
1.87      www        51: 
1.435     foxr       52: 
1.513     foxr       53: 
1.435     foxr       54: my %perm=();
1.596.2.12.2.  (raeburn   55:): my %old_essays=();
1.447     foxr       56: 
1.513     foxr       57: #  These variables are used to recover from ssi errors
                     58: 
                     59: my $ssi_retries = 5;
                     60: my $ssi_error;
                     61: my $ssi_error_resource;
                     62: my $ssi_error_message;
                     63: 
                     64: 
                     65: sub ssi_with_retries {
                     66:     my ($resource, $retries, %form) = @_;
                     67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     68:     if ($response->is_error) {
                     69: 	$ssi_error          = 1;
                     70: 	$ssi_error_resource = $resource;
                     71: 	$ssi_error_message  = $response->code . " " . $response->message;
                     72:     }
                     73: 
                     74:     return $content;
                     75: 
                     76: }
                     77: #
                     78: #  Prodcuces an ssi retry failure error message to the user:
                     79: #
                     80: 
                     81: sub ssi_print_error {
                     82:     my ($r) = @_;
1.516     raeburn    83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     84:     $r->print('
                     85: <br />
                     86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     87: <p>
                     88: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     90: '.&mt('Error:').' '.$ssi_error_message.'
                     91: </p>
                     92: <p>'.
                     93: &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 />'.
                     94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     95: '</p>');
                     96:     return;
1.513     foxr       97: }
                     98: 
1.44      ng         99: #
1.146     albertel  100: # --- Retrieve the parts from the metadata file.---
1.44      ng        101: sub getpartlist {
1.582     raeburn   102:     my ($symb,$errorref) = @_;
1.439     albertel  103: 
                    104:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   105:     unless (ref($navmap)) {
                    106:         if (ref($errorref)) { 
                    107:             $$errorref = 'navmap';
                    108:             return;
                    109:         }
                    110:     }
1.439     albertel  111:     my $res      = $navmap->getBySymb($symb);
                    112:     my $partlist = $res->parts();
                    113:     my $url      = $res->src();
                    114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    115: 
1.146     albertel  116:     my @stores;
1.439     albertel  117:     foreach my $part (@{ $partlist }) {
1.146     albertel  118: 	foreach my $key (@metakeys) {
                    119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    120: 	}
                    121:     }
                    122:     return @stores;
1.2       albertel  123: }
                    124: 
1.44      ng        125: # --- Get the symbolic name of a problem and the url
1.324     albertel  126: sub get_symb {
1.173     albertel  127:     my ($request,$silent) = @_;
1.596.2.12.2.  (raeburn  128:):     my $symb=$env{'form.symb'};
                    129:):     unless ($symb) {
                    130:):         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    131:):         $symb = &Apache::lonnet::symbread($url);
                    132:):         if ($symb eq '') { 
                    133:): 	    if (!$silent) {
                    134:):                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
                    135:): 	        return ();
                    136:): 	    }
                    137:):         }
1.173     albertel  138:     }
1.418     albertel  139:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  140:     return ($symb);
1.32      ng        141: }
                    142: 
1.129     ng        143: #--- Format fullname, username:domain if different for display
                    144: #--- Use anywhere where the student names are listed
                    145: sub nameUserString {
                    146:     my ($type,$fullname,$uname,$udom) = @_;
                    147:     if ($type eq 'header') {
1.485     albertel  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        149:     } else {
1.398     albertel  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        152:     }
                    153: }
                    154: 
1.44      ng        155: #--- Get the partlist and the response type for a given problem. ---
                    156: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        157: sub response_type {
1.582     raeburn   158:     my ($symb,$response_error) = @_;
1.377     albertel  159: 
                    160:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   161:     unless (ref($navmap)) {
                    162:         if (ref($response_error)) {
                    163:             $$response_error = 1;
                    164:         }
                    165:         return;
                    166:     }
1.377     albertel  167:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   168:     unless (ref($res)) {
                    169:         $$response_error = 1;
                    170:         return;
                    171:     }
1.377     albertel  172:     my $partlist = $res->parts();
1.392     albertel  173:     my %vPart = 
                    174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  175:     my (%response_types,%handgrade);
                    176:     foreach my $part (@{ $partlist }) {
1.392     albertel  177: 	next if (%vPart && !exists($vPart{$part}));
                    178: 
1.377     albertel  179: 	my @types = $res->responseType($part);
                    180: 	my @ids = $res->responseIds($part);
                    181: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    183: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    185: 				     '.handgrade',$symb);
1.41      ng        186: 	}
                    187:     }
1.377     albertel  188:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        189: }
                    190: 
1.375     albertel  191: sub flatten_responseType {
                    192:     my ($responseType) = @_;
                    193:     my @part_response_id =
                    194: 	map { 
                    195: 	    my $part = $_;
                    196: 	    map {
                    197: 		[$part,$_]
                    198: 		} sort(keys(%{ $responseType->{$part} }));
                    199: 	} sort(keys(%$responseType));
                    200:     return @part_response_id;
                    201: }
                    202: 
1.207     albertel  203: sub get_display_part {
1.324     albertel  204:     my ($partID,$symb)=@_;
1.207     albertel  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    206:     if (defined($display) and $display ne '') {
1.577     bisitz    207:         $display.= ' (<span class="LC_internal_info">'
                    208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  209:     } else {
                    210: 	$display=$partID;
                    211:     }
                    212:     return $display;
                    213: }
1.269     raeburn   214: 
1.118     ng        215: #--- Show resource title
                    216: #--- and parts and response type
                    217: sub showResourceInfo {
1.582     raeburn   218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    221:     if (ref($res_error)) {
                    222:         if ($$res_error) {
                    223:             return;
                    224:         }
                    225:     }
1.584     bisitz    226:     $result.=&Apache::loncommon::start_data_table()
                    227:             .&Apache::loncommon::start_data_table_header_row();
                    228:     if ($checkboxes) {
                    229:         $result.='<th>&nbsp;</th>';
                    230:     }
                    231:     $result.='<th>'.&mt('Problem Part').'</th>'
                    232:             .'<th>'.&mt('Res. ID').'</th>'
                    233:             .'<th>'.&mt('Type').'</th>'
                    234:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        235:     my %resptype = ();
1.122     ng        236:     my $hdgrade='no';
1.154     albertel  237:     my %partsseen;
1.524     raeburn   238:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    241:             my $responsetype = $responseType->{$partID}->{$resID};
                    242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    243:             $result.=&Apache::loncommon::start_data_table_row();
                    244:             if ($checkboxes) {
                    245:                 if (exists($partsseen{$partID})) {
                    246:                     $result.="<td>&nbsp;</td>";
                    247:                 } else {
                    248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    249:                 }
                    250:                 $partsseen{$partID}=1;
                    251:             }
                    252:             my $display_part=&get_display_part($partID,$symb);
                    253:             $result.='<td>'.$display_part.'</td>'
                    254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    255:                     .'<td>'.&mt($responsetype).'</td>'
1.596.2.12.2.  2(raebur  256:2): #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
1.584     bisitz    257:                     .&Apache::loncommon::end_data_table_row();
                    258:         }
1.118     ng        259:     }
1.584     bisitz    260:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        262: }
                    263: 
1.434     albertel  264: sub reset_caches {
                    265:     &reset_analyze_cache();
                    266:     &reset_perm();
1.596.2.12.2.  (raeburn  267:):     &reset_old_essays();
1.434     albertel  268: }
                    269: 
                    270: {
                    271:     my %analyze_cache;
1.557     raeburn   272:     my %analyze_cache_formkeys;
1.148     albertel  273: 
1.434     albertel  274:     sub reset_analyze_cache {
                    275: 	undef(%analyze_cache);
1.557     raeburn   276:         undef(%analyze_cache_formkeys);
1.434     albertel  277:     }
                    278: 
                    279:     sub get_analyze {
1.596.2.12.2.  (raeburn  280:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  281: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   282:         if ($type eq 'randomizetry') {
                    283:             if ($trial ne '') {
                    284:                 $key .= "\0".$trial;
                    285:             }
                    286:         }
1.557     raeburn   287: 	if (exists($analyze_cache{$key})) {
                    288:             my $getupdate = 0;
                    289:             if (ref($add_to_hash) eq 'HASH') {
                    290:                 foreach my $item (keys(%{$add_to_hash})) {
                    291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    293:                             $getupdate = 1;
                    294:                             last;
                    295:                         }
                    296:                     } else {
                    297:                         $getupdate = 1;
                    298:                     }
                    299:                 }
                    300:             }
                    301:             if (!$getupdate) {
                    302:                 return $analyze_cache{$key};
                    303:             }
                    304:         }
1.434     albertel  305: 
                    306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    307: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   308:         my %form = ('grade_target'      => 'analyze',
                    309:                     'grade_domain'      => $udom,
                    310:                     'grade_symb'        => $symb,
                    311:                     'grade_courseid'    =>  $env{'request.course.id'},
                    312:                     'grade_username'    => $uname,
                    313:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  314:):         if ($bubbles_per_row ne '') {
                    315:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    316:):         }
1.596.2.2  raeburn   317:         if ($type eq 'randomizetry') {
                    318:             $form{'grade_questiontype'} = $type;
                    319:             if ($rndseed ne '') {
                    320:                 $form{'grade_rndseed'} = $rndseed;
                    321:             }
                    322:         }
1.557     raeburn   323:         if (ref($add_to_hash)) {
                    324:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   325:         }
1.557     raeburn   326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   329:         if (ref($add_to_hash) eq 'HASH') {
                    330:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    331:         } else {
                    332:             $analyze_cache_formkeys{$key} = {};
                    333:         }
1.434     albertel  334: 	return $analyze_cache{$key} = \%analyze;
                    335:     }
                    336: 
                    337:     sub get_order {
1.596.2.2  raeburn   338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  340: 	return $analyze->{"$partid.$respid.shown"};
                    341:     }
                    342: 
                    343:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   347:         if (ref($foils) eq 'ARRAY') {
                    348: 	    foreach my $foil (@{$foils}) {
                    349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    350: 		    return $foil;
                    351: 	        }
1.434     albertel  352: 	    }
                    353: 	}
                    354:     }
1.554     raeburn   355: 
                    356:     sub scantron_partids_tograde {
1.596.2.12.2.  (raeburn  357:):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   358:         my (%analysis,@parts);
                    359:         if (ref($resource)) {
                    360:             my $symb = $resource->symb();
1.557     raeburn   361:             my $add_to_form;
                    362:             if ($check_for_randomlist) {
                    363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    364:             }
1.596.2.12.2.  (raeburn  365:):             my $analyze =
                    366:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    367:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   368:             if (ref($analyze) eq 'HASH') {
                    369:                 %analysis = %{$analyze};
                    370:             }
                    371:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    372:                 foreach my $part (@{$analysis{'parts'}}) {
                    373:                     my ($id,$respid) = split(/\./,$part);
                    374:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    375:                         push(@parts,$part);
                    376:                     }
                    377:                 }
                    378:             }
                    379:         }
                    380:         return (\%analysis,\@parts);
                    381:     }
                    382: 
1.148     albertel  383: }
1.434     albertel  384: 
1.118     ng        385: #--- Clean response type for display
1.335     albertel  386: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    387: #        response types only.
1.118     ng        388: sub cleanRecord {
1.336     albertel  389:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   390: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  391:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  392:     if ($response =~ /^(option|rank)$/) {
                    393: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  394:4):         my @answer = %answer;
                    395:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  396: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    397: 	my ($toprow,$bottomrow);
                    398: 	foreach my $foil (@$order) {
                    399: 	    if ($grading{$foil} == 1) {
                    400: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    401: 	    } else {
                    402: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    403: 	    }
1.398     albertel  404: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  405: 	}
                    406: 	return '<blockquote><table border="1">'.
1.466     albertel  407: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    408: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   409: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  410:     } elsif ($response eq 'match') {
                    411: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  412:4):         my @answer = %answer;
                    413:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  414: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    415: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    416: 	my ($toprow,$middlerow,$bottomrow);
                    417: 	foreach my $foil (@$order) {
                    418: 	    my $item=shift(@items);
                    419: 	    if ($grading{$foil} == 1) {
                    420: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  421: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  422: 	    } else {
                    423: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  424: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  425: 	    }
1.398     albertel  426: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        427: 	}
1.126     ng        428: 	return '<blockquote><table border="1">'.
1.466     albertel  429: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    430: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  431: 	    $middlerow.'</tr>'.
1.466     albertel  432: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   433: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  434:     } elsif ($response eq 'radiobutton') {
                    435: 	my %answer=&Apache::lonnet::str2hash($answer);
                    436: 	my ($toprow,$bottomrow);
1.434     albertel  437: 	my $correct = 
1.596.2.2  raeburn   438: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  439: 	foreach my $foil (@$order) {
1.148     albertel  440: 	    if (exists($answer{$foil})) {
1.434     albertel  441: 		if ($foil eq $correct) {
1.466     albertel  442: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  443: 		} else {
1.466     albertel  444: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  445: 		}
                    446: 	    } else {
1.466     albertel  447: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  448: 	    }
1.398     albertel  449: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  450: 	}
                    451: 	return '<blockquote><table border="1">'.
1.466     albertel  452: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    453: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   454: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  455:     } elsif ($response eq 'essay') {
1.257     albertel  456: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        457: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  458: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    459: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        460: 
1.257     albertel  461: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    462: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    463: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    464: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    465: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    466: 	    $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        467: 	}
1.596.2.12.2.  2(raebur  468:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  469:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  470:4):         my $result=&mt('Smile representation: [_1]',
                    471:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  472: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    473: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    474: 	return $result;
1.335     albertel  475:     } elsif ( $response eq 'Task') {
                    476: 	if ( $answer eq 'SUBMITTED') {
                    477: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  478: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  479: 	    return $result;
                    480: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    481: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    482: 			       keys(%{$record}));
                    483: 	    return join('<br />',($version,@matches));
                    484: 			       
                    485: 			       
                    486: 	} else {
                    487: 	    my $result =
                    488: 		'<p>'
                    489: 		.&mt('Overall result: [_1]',
                    490: 		     $record->{$version."resource.$respid.$partid.status"})
                    491: 		.'</p>';
                    492: 	    
                    493: 	    $result .= '<ul>';
                    494: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    495: 			     keys(%{$record}));
                    496: 	    foreach my $grade (sort(@grade)) {
                    497: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    498: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    499: 				     $dim, $record->{$grade}).
                    500: 			  '</li>';
                    501: 	    }
                    502: 	    $result.='</ul>';
                    503: 	    return $result;
                    504: 	}
1.596.2.12.2.  8(raebur  505:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    506:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  507: 	$answer = 
                    508: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    509: 							      $answer);
1.596.2.12.2.  8(raebur  510:4):         return $answer;
1.122     ng        511:     }
1.596.2.12.2.  8(raebur  512:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        513: }
                    514: 
                    515: #-- A couple of common js functions
                    516: sub commonJSfunctions {
                    517:     my $request = shift;
                    518:     $request->print(<<COMMONJSFUNCTIONS);
                    519: <script type="text/javascript" language="javascript">
                    520:     function radioSelection(radioButton) {
                    521: 	var selection=null;
                    522: 	if (radioButton.length > 1) {
                    523: 	    for (var i=0; i<radioButton.length; i++) {
                    524: 		if (radioButton[i].checked) {
                    525: 		    return radioButton[i].value;
                    526: 		}
                    527: 	    }
                    528: 	} else {
                    529: 	    if (radioButton.checked) return radioButton.value;
                    530: 	}
                    531: 	return selection;
                    532:     }
                    533: 
                    534:     function pullDownSelection(selectOne) {
                    535: 	var selection="";
                    536: 	if (selectOne.length > 1) {
                    537: 	    for (var i=0; i<selectOne.length; i++) {
                    538: 		if (selectOne[i].selected) {
                    539: 		    return selectOne[i].value;
                    540: 		}
                    541: 	    }
                    542: 	} else {
1.138     albertel  543:             // only one value it must be the selected one
                    544: 	    return selectOne.value;
1.118     ng        545: 	}
                    546:     }
                    547: </script>
                    548: COMMONJSFUNCTIONS
                    549: }
                    550: 
1.44      ng        551: #--- Dumps the class list with usernames,list of sections,
                    552: #--- section, ids and fullnames for each user.
                    553: sub getclasslist {
1.449     banghart  554:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  555:     my @getsec;
1.450     banghart  556:     my @getgroup;
1.442     banghart  557:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  558:     if (!ref($getsec)) {
                    559: 	if ($getsec ne '' && $getsec ne 'all') {
                    560: 	    @getsec=($getsec);
                    561: 	}
                    562:     } else {
                    563: 	@getsec=@{$getsec};
                    564:     }
                    565:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  566:     if (!ref($getgroup)) {
                    567: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    568: 	    @getgroup=($getgroup);
                    569: 	}
                    570:     } else {
                    571: 	@getgroup=@{$getgroup};
                    572:     }
                    573:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  574: 
1.449     banghart  575:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  576:     # Bail out if we were unable to get the classlist
1.56      matthew   577:     return if (! defined($classlist));
1.449     banghart  578:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   579:     #
                    580:     my %sections;
                    581:     my %fullnames;
1.205     matthew   582:     foreach my $student (keys(%$classlist)) {
                    583:         my $end      = 
                    584:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    585:         my $start    = 
                    586:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    587:         my $id       = 
                    588:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    589:         my $section  = 
                    590:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    591:         my $fullname = 
                    592:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    593:         my $status   = 
                    594:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  595:         my $group   = 
                    596:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        597: 	# filter students according to status selected
1.442     banghart  598: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    599: 	    if (!($stu_status =~ $status)) {
1.450     banghart  600: 		delete($classlist->{$student});
1.76      ng        601: 		next;
                    602: 	    }
                    603: 	}
1.450     banghart  604: 	# filter students according to groups selected
1.453     banghart  605: 	my @stu_groups = split(/,/,$group);
1.450     banghart  606: 	if (@getgroup) {
                    607: 	    my $exclude = 1;
1.454     banghart  608: 	    foreach my $grp (@getgroup) {
                    609: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  610: 	            if ($stu_group eq $grp) {
                    611: 	                $exclude = 0;
                    612:     	            } 
1.450     banghart  613: 	        }
1.453     banghart  614:     	        if (($grp eq 'none') && !$group) {
                    615:         	        $exclude = 0;
                    616:         	}
1.450     banghart  617: 	    }
                    618: 	    if ($exclude) {
                    619: 	        delete($classlist->{$student});
                    620: 	    }
                    621: 	}
1.205     matthew   622: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  623: 	if (&canview($section)) {
1.291     albertel  624: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  625: 		$sections{$section}++;
1.450     banghart  626: 		if ($classlist->{$student}) {
                    627: 		    $fullnames{$student}=$fullname;
                    628: 		}
1.103     albertel  629: 	    } else {
1.205     matthew   630: 		delete($classlist->{$student});
1.103     albertel  631: 	    }
                    632: 	} else {
1.205     matthew   633: 	    delete($classlist->{$student});
1.103     albertel  634: 	}
1.44      ng        635:     }
                    636:     my %seen = ();
1.56      matthew   637:     my @sections = sort(keys(%sections));
                    638:     return ($classlist,\@sections,\%fullnames);
1.44      ng        639: }
                    640: 
1.103     albertel  641: sub canmodify {
                    642:     my ($sec)=@_;
                    643:     if ($perm{'mgr'}) {
                    644: 	if (!defined($perm{'mgr_section'})) {
                    645: 	    # can modify whole class
                    646: 	    return 1;
                    647: 	} else {
                    648: 	    if ($sec eq $perm{'mgr_section'}) {
                    649: 		#can modify the requested section
                    650: 		return 1;
                    651: 	    } else {
                    652: 		# can't modify the request section
                    653: 		return 0;
                    654: 	    }
                    655: 	}
                    656:     }
                    657:     #can't modify
                    658:     return 0;
                    659: }
                    660: 
                    661: sub canview {
                    662:     my ($sec)=@_;
                    663:     if ($perm{'vgr'}) {
                    664: 	if (!defined($perm{'vgr_section'})) {
                    665: 	    # can modify whole class
                    666: 	    return 1;
                    667: 	} else {
                    668: 	    if ($sec eq $perm{'vgr_section'}) {
                    669: 		#can modify the requested section
                    670: 		return 1;
                    671: 	    } else {
                    672: 		# can't modify the request section
                    673: 		return 0;
                    674: 	    }
                    675: 	}
                    676:     }
                    677:     #can't modify
                    678:     return 0;
                    679: }
                    680: 
1.44      ng        681: #--- Retrieve the grade status of a student for all the parts
                    682: sub student_gradeStatus {
1.324     albertel  683:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  684:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        685:     my %partstatus = ();
                    686:     foreach (@$partlist) {
1.128     ng        687: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        688: 	$status              = 'nothing' if ($status eq '');
                    689: 	$partstatus{$_}      = $status;
                    690: 	my $subkey           = "resource.$_.submitted_by";
                    691: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    692:     }
                    693:     return %partstatus;
                    694: }
                    695: 
1.45      ng        696: # hidden form and javascript that calls the form
                    697: # Use by verifyscript and viewgrades
                    698: # Shows a student's view of problem and submission
                    699: sub jscriptNform {
1.324     albertel  700:     my ($symb) = @_;
1.442     banghart  701:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        702:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    703: 	'    function viewOneStudent(user,domain) {'."\n".
                    704: 	'	document.onestudent.student.value = user;'."\n".
                    705: 	'	document.onestudent.userdom.value = domain;'."\n".
                    706: 	'	document.onestudent.submit();'."\n".
                    707: 	'    }'."\n".
                    708: 	'</script>'."\n";
                    709:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  710: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  711: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    712: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  713: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        714: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    715: 	'<input type="hidden" name="student" value="" />'."\n".
                    716: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    717: 	'</form>'."\n";
                    718:     return $jscript;
                    719: }
1.39      ng        720: 
1.447     foxr      721: 
                    722: 
1.315     bowersj2  723: # Given the score (as a number [0-1] and the weight) what is the final
                    724: # point value? This function will round to the nearest tenth, third,
                    725: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  726: sub compute_points {
1.315     bowersj2  727:     my ($score, $weight) = @_;
                    728:     
                    729:     my $tolerance = .00001;
                    730:     my $points = $score * $weight;
                    731: 
                    732:     # Check for nearness to 1/x.
                    733:     my $check_for_nearness = sub {
                    734:         my ($factor) = @_;
                    735:         my $num = ($points * $factor) + $tolerance;
                    736:         my $floored_num = floor($num);
1.316     albertel  737:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  738:             return $floored_num / $factor;
                    739:         }
                    740:         return $points;
                    741:     };
                    742: 
                    743:     $points = $check_for_nearness->(10);
                    744:     $points = $check_for_nearness->(3);
                    745:     $points = $check_for_nearness->(4);
                    746:     
                    747:     return $points;
                    748: }
                    749: 
1.44      ng        750: #------------------ End of general use routines --------------------
1.87      www       751: 
                    752: #
                    753: # Find most similar essay
                    754: #
                    755: 
                    756: sub most_similar {
1.596.2.12.2.  (raeburn  757:):     my ($uname,$udom,$symb,$uessay)=@_;
                    758:): 
                    759:):     unless ($symb) { return ''; }
                    760:): 
                    761:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       762: 
                    763: # ignore spaces and punctuation
                    764: 
                    765:     $uessay=~s/\W+/ /gs;
                    766: 
1.282     www       767: # ignore empty submissions (occuring when only files are sent)
                    768: 
1.596.2.4  raeburn   769:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       770: 
1.87      www       771: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       772:     my $limit=0.6;
1.87      www       773:     my $sname='';
                    774:     my $sdom='';
                    775:     my $scrsid='';
                    776:     my $sessay='';
                    777: # go through all essays ...
1.596.2.12.2.  (raeburn  778:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  779: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       780: # ... except the same student
1.426     albertel  781:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  782:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  783: 	$tessay=~s/\W+/ /gs;
1.87      www       784: # String similarity gives up if not even limit
1.426     albertel  785: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       786: # Found one
1.426     albertel  787: 	if ($tsimilar>$limit) {
                    788: 	    $limit=$tsimilar;
                    789: 	    $sname=$tname;
                    790: 	    $sdom=$tdom;
                    791: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  792:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  793: 	}
1.87      www       794:     }
1.88      www       795:     if ($limit>0.6) {
1.87      www       796:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    797:     } else {
                    798:        return ('','','','',0);
                    799:     }
                    800: }
                    801: 
1.44      ng        802: #-------------------------------------------------------------------
                    803: 
                    804: #------------------------------------ Receipt Verification Routines
1.45      ng        805: #
1.44      ng        806: #--- Check whether a receipt number is valid.---
                    807: sub verifyreceipt {
                    808:     my $request  = shift;
                    809: 
1.257     albertel  810:     my $courseid = $env{'request.course.id'};
1.184     www       811:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  812: 	$env{'form.receipt'};
1.44      ng        813:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  814:     my ($symb)   = &get_symb($request);
1.44      ng        815: 
1.487     albertel  816:     my $title.=
                    817: 	'<h3><span class="LC_info">'.
1.584     bisitz    818: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  819: 	'</span></h3>'."\n".
1.596.2.12.2.  2(raebur  820:3): 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
1.487     albertel  821: 	'</h4>'."\n";
1.44      ng        822: 
                    823:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   824:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  825:     
                    826:     my $receiptparts=0;
1.390     albertel  827:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    828: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  829:     my $parts=['0'];
1.582     raeburn   830:     if ($receiptparts) {
                    831:         my $res_error; 
                    832:         ($parts)=&response_type($symb,\$res_error);
                    833:         if ($res_error) {
                    834:             return &navmap_errormsg();
                    835:         } 
                    836:     }
1.486     albertel  837:     
                    838:     my $header = 
                    839: 	&Apache::loncommon::start_data_table().
                    840: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  841: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    842: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    843: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  844:     if ($receiptparts) {
1.487     albertel  845: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  846:     }
                    847:     $header.=
                    848: 	&Apache::loncommon::end_data_table_header_row();
                    849: 
1.294     albertel  850:     foreach (sort 
                    851: 	     {
                    852: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    853: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    854: 		 }
                    855: 		 return $a cmp $b;
                    856: 	     } (keys(%$fullname))) {
1.44      ng        857: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  858: 	foreach my $part (@$parts) {
                    859: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  860: 		$contents.=
                    861: 		    &Apache::loncommon::start_data_table_row().
                    862: 		    '<td>&nbsp;'."\n".
1.177     albertel  863: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  864: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  865: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    866: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    867: 		if ($receiptparts) {
                    868: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    869: 		}
1.486     albertel  870: 		$contents.= 
                    871: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  872: 		
                    873: 		$matches++;
                    874: 	    }
1.44      ng        875: 	}
                    876:     }
                    877:     if ($matches == 0) {
1.584     bisitz    878:         $string = $title
                    879:                  .'<p class="LC_warning">'
                    880:                  .&mt('No match found for the above receipt number.')
                    881:                  .'</p>';
1.44      ng        882:     } else {
1.324     albertel  883: 	$string = &jscriptNform($symb).$title.
1.487     albertel  884: 	    '<p>'.
1.584     bisitz    885: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  886: 	    '</p>'.
1.486     albertel  887: 	    $header.
                    888: 	    $contents.
                    889: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        890:     }
1.324     albertel  891:     return $string.&show_grading_menu_form($symb);
1.44      ng        892: }
                    893: 
                    894: #--- This is called by a number of programs.
                    895: #--- Called from the Grading Menu - View/Grade an individual student
                    896: #--- Also called directly when one clicks on the subm button 
                    897: #    on the problem page.
1.30      ng        898: sub listStudents {
1.41      ng        899:     my ($request) = shift;
1.49      albertel  900: 
1.324     albertel  901:     my ($symb) = &get_symb($request);
1.257     albertel  902:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    903:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    904:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  905:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  906:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    907:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  908:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    909: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  910: 
1.548     bisitz    911:     my $result='<h3><span class="LC_info">&nbsp;'
                    912: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  913: 	.'</span></h3>';
1.118     ng        914: 
1.324     albertel  915:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  916: 
1.559     raeburn   917:     my %lt = &Apache::lonlocal::texthash (
                    918: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    919: 		'single'   => 'Please select the student before clicking on the Next button.',
                    920: 	     );
1.45      ng        921:     $request->print(<<LISTJAVASCRIPT);
                    922: <script type="text/javascript" language="javascript">
1.110     ng        923:     function checkSelect(checkBox) {
                    924: 	var ctr=0;
                    925: 	var sense="";
                    926: 	if (checkBox.length > 1) {
                    927: 	    for (var i=0; i<checkBox.length; i++) {
                    928: 		if (checkBox[i].checked) {
                    929: 		    ctr++;
                    930: 		}
                    931: 	    }
1.485     albertel  932: 	    sense = '$lt{'multiple'}';
1.110     ng        933: 	} else {
                    934: 	    if (checkBox.checked) {
                    935: 		ctr = 1;
                    936: 	    }
1.485     albertel  937: 	    sense = '$lt{'single'}';
1.110     ng        938: 	}
                    939: 	if (ctr == 0) {
1.485     albertel  940: 	    alert(sense);
1.110     ng        941: 	    return false;
                    942: 	}
                    943: 	document.gradesub.submit();
                    944:     }
                    945: 
                    946:     function reLoadList(formname) {
1.112     ng        947: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        948: 	formname.command.value = 'submission';
                    949: 	formname.submit();
                    950:     }
1.45      ng        951: </script>
                    952: LISTJAVASCRIPT
                    953: 
1.118     ng        954:     &commonJSfunctions($request);
1.41      ng        955:     $request->print($result);
1.39      ng        956: 
1.401     albertel  957:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    958:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  959:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  960: 	"\n".$table;
                    961: 	
1.561     bisitz    962:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    963:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    964:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    965:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    966:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    967:                   .&Apache::lonhtmlcommon::row_closure();
                    968:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    969:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    970:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    971:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    972:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  973: 
                    974:     my $submission_options;
1.257     albertel  975:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  976: 	$submission_options.=
                    977: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  978:     }
1.442     banghart  979:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    980:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  981:     $env{'form.Status'} = $saveStatus;
1.485     albertel  982:     $submission_options.=
1.592     bisitz    983:         '<span class="LC_nobreak">'.
                    984:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    985:         &mt('last submission only').' </label></span>'."\n".
                    986:         '<span class="LC_nobreak">'.
                    987:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    988:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    989:         '<span class="LC_nobreak">'.
                    990:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    991:         &mt('by dates and submissions').'</label></span>'."\n".
                    992:         '<span class="LC_nobreak">'.
                    993:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    994:         &mt('all details').'</label></span>';
1.561     bisitz    995:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    996:                   .$submission_options
                    997:                   .&Apache::lonhtmlcommon::row_closure();
                    998: 
                    999:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1000:                   .'<select name="increment">'
                   1001:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1002:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1003:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1004:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1005:                   .'</select>'
                   1006:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1007: 
                   1008:     $gradeTable .= 
1.432     banghart 1009:         &build_section_inputs().
1.45      ng       1010: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel 1011: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                   1012: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                   1013: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1014: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1015: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1016: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1017: 
1.257     albertel 1018:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz   1019: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1020:     } else {
1.561     bisitz   1021:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1022:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1023:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1024:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1025:     }
1.112     ng       1026: 
1.561     bisitz   1027:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1028:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1029:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1030:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1031: 
                   1032:     $gradeTable .= '<p>'
                   1033:                   .&mt('To '.lc($viewgrade)." 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"
                   1034:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1035:                   .'</p>';
1.249     albertel 1036: 
                   1037: # checkall buttons
                   1038:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1039:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1040:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1041:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1042:     $gradeTable.=&check_buttons();
1.450     banghart 1043:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1044:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1045: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1046:     my $loop = 0;
                   1047:     while ($loop < 2) {
1.485     albertel 1048: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1049: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1050: 	if ($env{'form.showgrading'} eq 'yes' 
                   1051: 	    && $submitonly ne 'queued'
                   1052: 	    && $submitonly ne 'all') {
1.485     albertel 1053: 	    foreach my $part (sort(@$partlist)) {
                   1054: 		my $display_part=
                   1055: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1056: 		$gradeTable.=
                   1057: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1058: 	    }
1.301     albertel 1059: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1060: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1061: 	}
                   1062: 	$loop++;
1.126     ng       1063: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1064:     }
1.474     albertel 1065:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1066: 
1.45      ng       1067:     my $ctr = 0;
1.294     albertel 1068:     foreach my $student (sort 
                   1069: 			 {
                   1070: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1071: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1072: 			     }
                   1073: 			     return $a cmp $b;
                   1074: 			 }
                   1075: 			 (keys(%$fullname))) {
1.41      ng       1076: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1077: 
1.110     ng       1078: 	my %status = ();
1.301     albertel 1079: 
                   1080: 	if ($submitonly eq 'queued') {
                   1081: 	    my %queue_status = 
                   1082: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1083: 							$udom,$uname);
                   1084: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1085: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1086: 	}
                   1087: 
                   1088: 	if ($env{'form.showgrading'} eq 'yes' 
                   1089: 	    && $submitonly ne 'queued'
                   1090: 	    && $submitonly ne 'all') {
1.324     albertel 1091: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1092: 	    my $submitted = 0;
1.164     albertel 1093: 	    my $graded = 0;
1.248     albertel 1094: 	    my $incorrect = 0;
1.110     ng       1095: 	    foreach (keys(%status)) {
1.145     albertel 1096: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1097: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1098: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1099: 		
1.110     ng       1100: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1101: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1102: 		    $submitted = 0;
1.150     albertel 1103: 		    my ($part)=split(/\./,$partid);
1.110     ng       1104: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1105: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1106: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1107: 		}
1.41      ng       1108: 	    }
1.248     albertel 1109: 	    
1.156     albertel 1110: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1111: 				     $submitonly eq 'incorrect' ||
                   1112: 				     $submitonly eq 'graded'));
1.248     albertel 1113: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1114: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1115: 	}
1.34      ng       1116: 
1.45      ng       1117: 	$ctr++;
1.249     albertel 1118: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1119:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1120: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1121: 	    if ($ctr%2 ==1) {
                   1122: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1123: 	    }
1.126     ng       1124: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1125:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1126:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1127: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1128: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1129: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1130: 
1.257     albertel 1131: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1132: 		foreach (sort(keys(%status))) {
1.485     albertel 1133: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1134: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1135: 		}
1.41      ng       1136: 	    }
1.126     ng       1137: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1138: 	    if ($ctr%2 ==0) {
                   1139: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1140: 	    }
1.41      ng       1141: 	}
                   1142:     }
1.110     ng       1143:     if ($ctr%2 ==1) {
1.126     ng       1144: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1145: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1146: 		&& $submitonly ne 'queued'
                   1147: 		&& $submitonly ne 'all') {
1.110     ng       1148: 		foreach (@$partlist) {
                   1149: 		    $gradeTable.='<td>&nbsp;</td>';
                   1150: 		}
1.301     albertel 1151: 	    } elsif ($submitonly eq 'queued') {
                   1152: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1153: 	    }
1.474     albertel 1154: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1155:     }
                   1156: 
1.474     albertel 1157:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1158:         '<input type="button" '.
                   1159:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1160:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1161:     if ($ctr == 0) {
1.96      albertel 1162: 	my $num_students=(scalar(keys(%$fullname)));
                   1163: 	if ($num_students eq 0) {
1.485     albertel 1164: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1165: 	} else {
1.171     albertel 1166: 	    my $submissions='submissions';
                   1167: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1168: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1169: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1170: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1171:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1172: 		    $num_students).
                   1173: 		'</span><br />';
1.96      albertel 1174: 	}
1.46      ng       1175:     } elsif ($ctr == 1) {
1.474     albertel 1176: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1177:     }
1.324     albertel 1178:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1179:     $request->print($gradeTable);
1.44      ng       1180:     return '';
1.10      ng       1181: }
                   1182: 
1.44      ng       1183: #---- Called from the listStudents routine
1.249     albertel 1184: 
                   1185: sub check_script {
                   1186:     my ($form, $type)=@_;
                   1187:     my $chkallscript='<script type="text/javascript">
                   1188:     function checkall() {
                   1189:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1190:             ele = document.forms.'.$form.'.elements[i];
                   1191:             if (ele.name == "'.$type.'") {
                   1192:             document.forms.'.$form.'.elements[i].checked=true;
                   1193:                                        }
                   1194:         }
                   1195:     }
                   1196: 
                   1197:     function checksec() {
                   1198:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1199:             ele = document.forms.'.$form.'.elements[i];
                   1200:            string = document.forms.'.$form.'.chksec.value;
                   1201:            if
                   1202:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1203:               document.forms.'.$form.'.elements[i].checked=true;
                   1204:             }
                   1205:         }
                   1206:     }
                   1207: 
                   1208: 
                   1209:     function uncheckall() {
                   1210:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1211:             ele = document.forms.'.$form.'.elements[i];
                   1212:             if (ele.name == "'.$type.'") {
                   1213:             document.forms.'.$form.'.elements[i].checked=false;
                   1214:                                        }
                   1215:         }
                   1216:     }
                   1217: 
                   1218: </script>'."\n";
                   1219:     return $chkallscript;
                   1220: }
                   1221: 
                   1222: sub check_buttons {
1.485     albertel 1223:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1224:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1225:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1226:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1227:     return $buttons;
                   1228: }
                   1229: 
1.44      ng       1230: #     Displays the submissions for one student or a group of students
1.34      ng       1231: sub processGroup {
1.41      ng       1232:     my ($request)  = shift;
                   1233:     my $ctr        = 0;
1.155     albertel 1234:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1235:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1236: 
1.396     banghart 1237:     foreach my $student (@stuchecked) {
                   1238: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1239: 	$env{'form.student'}        = $uname;
                   1240: 	$env{'form.userdom'}        = $udom;
                   1241: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1242: 	&submission($request,$ctr,$total);
                   1243: 	$ctr++;
                   1244:     }
                   1245:     return '';
1.35      ng       1246: }
1.34      ng       1247: 
1.44      ng       1248: #------------------------------------------------------------------------------------
                   1249: #
                   1250: #-------------------------- Next few routines handles grading by student, essentially
                   1251: #                           handles essay response type problem/part
                   1252: #
                   1253: #--- Javascript to handle the submission page functionality ---
                   1254: sub sub_page_js {
                   1255:     my $request = shift;
1.539     riegler  1256: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1257:     $request->print(<<SUBJAVASCRIPT);
                   1258: <script type="text/javascript" language="javascript">
1.71      ng       1259:     function updateRadio(formname,id,weight) {
1.125     ng       1260: 	var gradeBox = formname["GD_BOX"+id];
                   1261: 	var radioButton = formname["RADVAL"+id];
                   1262: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1263: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1264: 	gradeBox.value = pts;
                   1265: 	var resetbox = false;
                   1266: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1267: 	    alert("$alertmsg"+pts);
1.71      ng       1268: 	    for (var i=0; i<radioButton.length; i++) {
                   1269: 		if (radioButton[i].checked) {
                   1270: 		    gradeBox.value = i;
                   1271: 		    resetbox = true;
                   1272: 		}
                   1273: 	    }
                   1274: 	    if (!resetbox) {
                   1275: 		formtextbox.value = "";
                   1276: 	    }
                   1277: 	    return;
1.44      ng       1278: 	}
1.71      ng       1279: 
                   1280: 	if (pts > weight) {
                   1281: 	    var resp = confirm("You entered a value ("+pts+
                   1282: 			       ") greater than the weight for the part. Accept?");
                   1283: 	    if (resp == false) {
1.125     ng       1284: 		gradeBox.value = oldpts;
1.71      ng       1285: 		return;
                   1286: 	    }
1.44      ng       1287: 	}
1.13      albertel 1288: 
1.71      ng       1289: 	for (var i=0; i<radioButton.length; i++) {
                   1290: 	    radioButton[i].checked=false;
                   1291: 	    if (pts == i && pts != "") {
                   1292: 		radioButton[i].checked=true;
                   1293: 	    }
                   1294: 	}
                   1295: 	updateSelect(formname,id);
1.125     ng       1296: 	formname["stores"+id].value = "0";
1.41      ng       1297:     }
1.5       albertel 1298: 
1.72      ng       1299:     function writeBox(formname,id,pts) {
1.125     ng       1300: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1301: 	if (checkSolved(formname,id) == 'update') {
                   1302: 	    gradeBox.value = pts;
                   1303: 	} else {
1.125     ng       1304: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1305: 	    gradeBox.value = oldpts;
1.125     ng       1306: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1307: 	    for (var i=0; i<radioButton.length; i++) {
                   1308: 		radioButton[i].checked=false;
1.72      ng       1309: 		if (i == oldpts) {
1.71      ng       1310: 		    radioButton[i].checked=true;
                   1311: 		}
                   1312: 	    }
1.41      ng       1313: 	}
1.125     ng       1314: 	formname["stores"+id].value = "0";
1.71      ng       1315: 	updateSelect(formname,id);
                   1316: 	return;
1.41      ng       1317:     }
1.44      ng       1318: 
1.71      ng       1319:     function clearRadBox(formname,id) {
                   1320: 	if (checkSolved(formname,id) == 'noupdate') {
                   1321: 	    updateSelect(formname,id);
                   1322: 	    return;
                   1323: 	}
1.125     ng       1324: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1325: 	for (var i=0; i<gradeSelect.length; i++) {
                   1326: 	    if (gradeSelect[i].selected) {
                   1327: 		var selectx=i;
                   1328: 	    }
                   1329: 	}
1.125     ng       1330: 	var stores = formname["stores"+id];
1.71      ng       1331: 	if (selectx == stores.value) { return };
1.125     ng       1332: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1333: 	gradeBox.value = "";
1.125     ng       1334: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1335: 	for (var i=0; i<radioButton.length; i++) {
                   1336: 	    radioButton[i].checked=false;
                   1337: 	}
                   1338: 	stores.value = selectx;
                   1339:     }
1.5       albertel 1340: 
1.71      ng       1341:     function checkSolved(formname,id) {
1.125     ng       1342: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1343: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1344: 	    if (!reply) {return "noupdate";}
1.120     ng       1345: 	    formname.overRideScore.value = 'yes';
1.41      ng       1346: 	}
1.71      ng       1347: 	return "update";
1.13      albertel 1348:     }
1.71      ng       1349: 
                   1350:     function updateSelect(formname,id) {
1.125     ng       1351: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1352: 	return;
1.41      ng       1353:     }
1.33      ng       1354: 
1.121     ng       1355: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1356:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1357: 	formname.gradeOpt.value = val;
1.71      ng       1358: 	if (val == "Save & Next") {
                   1359: 	    for (i=0;i<=total;i++) {
                   1360: 		for (j=0;j<parttot;j++) {
1.125     ng       1361: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1362: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1363: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1364: 			if (points == "") {
1.125     ng       1365: 			    var name = formname["name"+i].value;
1.129     ng       1366: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1367: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1368: 					       ", part "+partid+". Continue?");
1.71      ng       1369: 			    if (resp == false) {
1.125     ng       1370: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1371: 				return false;
                   1372: 			    }
                   1373: 			}
                   1374: 		    }
                   1375: 		}
                   1376: 	    }
                   1377: 	}
1.121     ng       1378: 	if (val == "Grade Student") {
                   1379: 	    formname.showgrading.value = "yes";
                   1380: 	    if (formname.Status.value == "") {
                   1381: 		formname.Status.value = "Active";
                   1382: 	    }
                   1383: 	    formname.studentNo.value = total;
                   1384: 	}
1.120     ng       1385: 	formname.submit();
                   1386:     }
                   1387: 
1.71      ng       1388: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1389:     function checkSubmitPage(formname,total) {
                   1390: 	noscore = new Array(100);
                   1391: 	var ptr = 0;
                   1392: 	for (i=1;i<total;i++) {
1.125     ng       1393: 	    var partid = formname["q_"+i].value;
1.127     ng       1394: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1395: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1396: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1397: 		if (points == "" && status != "correct_by_student") {
                   1398: 		    noscore[ptr] = i;
                   1399: 		    ptr++;
                   1400: 		}
                   1401: 	    }
                   1402: 	}
                   1403: 	if (ptr != 0) {
                   1404: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1405: 	    var prolist = "";
                   1406: 	    if (ptr == 1) {
                   1407: 		prolist = noscore[0];
                   1408: 	    } else {
                   1409: 		var i = 0;
                   1410: 		while (i < ptr-1) {
                   1411: 		    prolist += noscore[i]+", ";
                   1412: 		    i++;
                   1413: 		}
                   1414: 		prolist += "and "+noscore[i];
                   1415: 	    }
                   1416: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1417: 	    if (resp == false) {
                   1418: 		return false;
                   1419: 	    }
                   1420: 	}
1.45      ng       1421: 
1.71      ng       1422: 	formname.submit();
                   1423:     }
                   1424: </script>
                   1425: SUBJAVASCRIPT
                   1426: }
1.45      ng       1427: 
1.71      ng       1428: #--- javascript for essay type problem --
                   1429: sub sub_page_kw_js {
                   1430:     my $request = shift;
1.80      ng       1431:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1432:     &commonJSfunctions($request);
1.350     albertel 1433: 
1.351     albertel 1434:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1435:     <script text="text/javascript">
                   1436:     function checkInput() {
                   1437:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1438:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1439:       var usrctr = document.msgcenter.usrctr.value;
                   1440:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1441:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1442: 
                   1443:       var msgchk = "";
                   1444:       if (document.msgcenter.subchk.checked) {
                   1445:          msgchk = "msgsub,";
                   1446:       }
                   1447:       var includemsg = 0;
                   1448:       for (var i=1; i<=nmsg; i++) {
                   1449:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1450:           var frmmsg = document.msgcenter["msg"+i];
                   1451:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1452:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1453:           showflg.value = "1";
                   1454:           var chkbox = document.msgcenter["msgn"+i];
                   1455:           if (chkbox.checked) {
                   1456:              msgchk += "savemsg"+i+",";
                   1457:              includemsg = 1;
                   1458:           }
                   1459:       }
                   1460:       if (document.msgcenter.newmsgchk.checked) {
                   1461:          msgchk += "newmsg"+usrctr;
                   1462:          includemsg = 1;
                   1463:       }
                   1464:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1465:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1466:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1467:       includemsg.value = msgchk;
                   1468: 
                   1469:       self.close()
                   1470: 
                   1471:     }
                   1472:     </script>
                   1473: INNERJS
                   1474: 
1.351     albertel 1475:     my $inner_js_highlight_central=<<INNERJS;
                   1476:  <script type="text/javascript">
                   1477:     function updateChoice(flag) {
                   1478:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1479:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1480:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1481:       opener.document.SCORE.refresh.value = "on";
                   1482:       if (opener.document.SCORE.keywords.value!=""){
                   1483:          opener.document.SCORE.submit();
                   1484:       }
                   1485:       self.close()
                   1486:     }
                   1487: </script>
                   1488: INNERJS
                   1489: 
                   1490:     my $start_page_msg_central = 
                   1491:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1492: 				       {'js_ready'  => 1,
                   1493: 					'only_body' => 1,
                   1494: 					'bgcolor'   =>'#FFFFFF',});
                   1495:     my $end_page_msg_central = 
                   1496: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1497: 
                   1498: 
                   1499:     my $start_page_highlight_central = 
                   1500:         &Apache::loncommon::start_page('Highlight Central',
                   1501: 				       $inner_js_highlight_central,
1.350     albertel 1502: 				       {'js_ready'  => 1,
                   1503: 					'only_body' => 1,
                   1504: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1505:     my $end_page_highlight_central = 
1.350     albertel 1506: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1507: 
1.219     www      1508:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1509:     $docopen=~s/^document\.//;
1.596.2.4  raeburn  1510:     my %lt = &Apache::lonlocal::texthash(
                   1511:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1512:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1513:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1514:                 comp => 'Compose Message for: ',
                   1515:                 incl => 'Include',
                   1516:                 type => 'Type',
                   1517:                 subj => 'Subject',
                   1518:                 mesa => 'Message',
                   1519:                 new  => 'New',
                   1520:                 save => 'Save',
                   1521:                 canc => 'Cancel',
                   1522:                 kehi => 'Keyword Highlight Options',
                   1523:                 txtc => 'Text Color',
                   1524:                 font => 'Font Size',
                   1525:                 fnst => 'Font Style',
1.596.2.12.2.  8(raebur 1526:4):                 col1 => 'red',
                   1527:4):                 col2 => 'green',
                   1528:4):                 col3 => 'blue',
                   1529:4):                 siz1 => 'normal',
                   1530:4):                 siz2 => '+1',
                   1531:4):                 siz3 => '+2',
                   1532:4):                 sty1 => 'normal',
                   1533:4):                 sty2 => 'italic',
                   1534:4):                 sty3 => 'bold',
1.596.2.4  raeburn  1535:              );
1.71      ng       1536:     $request->print(<<SUBJAVASCRIPT);
                   1537: <script type="text/javascript" language="javascript">
1.45      ng       1538: 
1.44      ng       1539: //===================== Show list of keywords ====================
1.122     ng       1540:   function keywords(formname) {
1.596.2.4  raeburn  1541:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1542:     if (nret==null) return;
1.122     ng       1543:     formname.keywords.value = nret;
1.44      ng       1544: 
1.122     ng       1545:     if (formname.keywords.value != "") {
1.128     ng       1546: 	formname.refresh.value = "on";
1.122     ng       1547: 	formname.submit();
1.44      ng       1548:     }
                   1549:     return;
                   1550:   }
                   1551: 
                   1552: //===================== Script to view submitted by ==================
                   1553:   function viewSubmitter(submitter) {
                   1554:     document.SCORE.refresh.value = "on";
                   1555:     document.SCORE.NCT.value = "1";
                   1556:     document.SCORE.unamedom0.value = submitter;
                   1557:     document.SCORE.submit();
                   1558:     return;
                   1559:   }
                   1560: 
                   1561: //===================== Script to add keyword(s) ==================
                   1562:   function getSel() {
                   1563:     if (document.getSelection) txt = document.getSelection();
                   1564:     else if (document.selection) txt = document.selection.createRange().text;
                   1565:     else return;
                   1566:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1567:     if (cleantxt=="") {
1.596.2.4  raeburn  1568: 	alert("$lt{'plse'}");
1.44      ng       1569: 	return;
                   1570:     }
1.596.2.4  raeburn  1571:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1572:     if (nret==null) return;
1.127     ng       1573:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1574:     if (document.SCORE.keywords.value != "") {
1.127     ng       1575: 	document.SCORE.refresh.value = "on";
1.44      ng       1576: 	document.SCORE.submit();
                   1577:     }
                   1578:     return;
                   1579:   }
                   1580: 
                   1581: //====================== Script for composing message ==============
1.80      ng       1582:    // preload images
                   1583:    img1 = new Image();
                   1584:    img1.src = "$iconpath/mailbkgrd.gif";
                   1585:    img2 = new Image();
                   1586:    img2.src = "$iconpath/mailto.gif";
                   1587: 
1.44      ng       1588:   function msgCenter(msgform,usrctr,fullname) {
                   1589:     var Nmsg  = msgform.savemsgN.value;
                   1590:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1591:     var subject = msgform.msgsub.value;
1.127     ng       1592:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1593:     re = /msgsub/;
                   1594:     var shwsel = "";
                   1595:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1596:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1597:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1598:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1599: 	var testmsg = "savemsg"+i+",";
                   1600: 	re = new RegExp(testmsg,"g");
1.44      ng       1601: 	shwsel = "";
                   1602: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1603: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1604: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1605: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1606: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1607:     }
1.125     ng       1608:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1609:     shwsel = "";
                   1610:     re = /newmsg/;
                   1611:     if (re.test(msgchk)) { shwsel = "checked" }
                   1612:     newMsg(newmsg,shwsel);
                   1613:     msgTail(); 
                   1614:     return;
                   1615:   }
                   1616: 
1.123     ng       1617:   function checkEntities(strx) {
                   1618:     if (strx.length == 0) return strx;
                   1619:     var orgStr = ["&", "<", ">", '"']; 
                   1620:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1621:     var counter = 0;
                   1622:     while (counter < 4) {
                   1623: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1624: 	counter++;
                   1625:     }
                   1626:     return strx;
                   1627:   }
                   1628: 
                   1629:   function strReplace(strx, orgStr, newStr) {
                   1630:     return strx.split(orgStr).join(newStr);
                   1631:   }
                   1632: 
1.44      ng       1633:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1634:     var height = 70*Nmsg+250;
1.44      ng       1635:     if (height > 600) {
                   1636: 	height = 600;
                   1637:     }
1.118     ng       1638:     var xpos = (screen.width-600)/2;
                   1639:     xpos = (xpos < 0) ? '0' : xpos;
                   1640:     var ypos = (screen.height-height)/2-30;
                   1641:     ypos = (ypos < 0) ? '0' : ypos;
                   1642: 
1.596.2.12.2.  (raeburn 1643:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1644:     pWin.focus();
                   1645:     pDoc = pWin.document;
1.219     www      1646:     pDoc.$docopen;
1.351     albertel 1647:     pDoc.write('$start_page_msg_central');
1.76      ng       1648: 
                   1649:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1650:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.4  raeburn  1651:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1652: 
1.564     bisitz   1653:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1654:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.4  raeburn  1655:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1656: }
                   1657:     function displaySubject(msg,shwsel) {
1.76      ng       1658:     pDoc = pWin.document;
                   1659:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1660:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1661:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1662:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1663: }
                   1664: 
1.72      ng       1665:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1666:     pDoc = pWin.document;
                   1667:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1668:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1669:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1670:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1671: }
                   1672: 
                   1673:   function newMsg(newmsg,shwsel) {
1.76      ng       1674:     pDoc = pWin.document;
                   1675:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1676:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1677:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1678:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1679: }
                   1680: 
                   1681:   function msgTail() {
1.76      ng       1682:     pDoc = pWin.document;
1.465     albertel 1683:     pDoc.write("<\\/table>");
                   1684:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.4  raeburn  1685:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1686:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1687:     pDoc.write("<\\/form>");
1.351     albertel 1688:     pDoc.write('$end_page_msg_central');
1.128     ng       1689:     pDoc.close();
1.44      ng       1690: }
                   1691: 
                   1692: //====================== Script for keyword highlight options ==============
                   1693:   function kwhighlight() {
                   1694:     var kwclr    = document.SCORE.kwclr.value;
                   1695:     var kwsize   = document.SCORE.kwsize.value;
                   1696:     var kwstyle  = document.SCORE.kwstyle.value;
                   1697:     var redsel = "";
                   1698:     var grnsel = "";
                   1699:     var blusel = "";
1.596.2.12.2.  8(raebur 1700:4):     var txtcol1 = "$lt{'col1'}";
                   1701:4):     var txtcol2 = "$lt{'col2'}";
                   1702:4):     var txtcol3 = "$lt{'col3'}";
                   1703:4):     var txtsiz1 = "$lt{'siz1'}";
                   1704:4):     var txtsiz2 = "$lt{'siz2'}";
                   1705:4):     var txtsiz3 = "$lt{'siz3'}";
                   1706:4):     var txtsty1 = "$lt{'sty1'}";
                   1707:4):     var txtsty2 = "$lt{'sty2'}";
                   1708:4):     var txtsty3 = "$lt{'sty3'}";
                   1709:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1710:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1711:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1712:     var sznsel = "";
                   1713:     var sz1sel = "";
                   1714:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1715:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1716:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1717:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1718:     var synsel = "";
                   1719:     var syisel = "";
                   1720:     var sybsel = "";
1.596.2.12.2.  8(raebur 1721:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1722:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1723:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1724:     highlightCentral();
1.596.2.12.2.  8(raebur 1725:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1726:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1727:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1728:     highlightend();
                   1729:     return;
                   1730:   }
                   1731: 
                   1732:   function highlightCentral() {
1.76      ng       1733: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1734:     var xpos = (screen.width-400)/2;
                   1735:     xpos = (xpos < 0) ? '0' : xpos;
                   1736:     var ypos = (screen.height-330)/2-30;
                   1737:     ypos = (ypos < 0) ? '0' : ypos;
                   1738: 
1.206     albertel 1739:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1740:     hwdWin.focus();
                   1741:     var hDoc = hwdWin.document;
1.219     www      1742:     hDoc.$docopen;
1.351     albertel 1743:     hDoc.write('$start_page_highlight_central');
1.76      ng       1744:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  8(raebur 1745:4):     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1.76      ng       1746: 
1.596.2.12.2.  8(raebur 1747:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
                   1748:4):     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1749:   }
                   1750: 
                   1751:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1752:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1753:4):     hDoc.write("<tr>");
1.76      ng       1754:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1755:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1756:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1757:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1758:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1759:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1760:     hDoc.write("<\\/tr>");
1.44      ng       1761:   }
                   1762: 
                   1763:   function highlightend() { 
1.76      ng       1764:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1765:4):     hDoc.write("<\\/table><br \\/>");
                   1766:4):     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1767:4):     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1768:     hDoc.write("<\\/form>");
1.351     albertel 1769:     hDoc.write('$end_page_highlight_central');
1.128     ng       1770:     hDoc.close();
1.44      ng       1771:   }
                   1772: 
                   1773: </script>
                   1774: SUBJAVASCRIPT
                   1775: }
                   1776: 
1.349     albertel 1777: sub get_increment {
1.348     bowersj2 1778:     my $increment = $env{'form.increment'};
                   1779:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1780:         $increment != .1) {
                   1781:         $increment = 1;
                   1782:     }
                   1783:     return $increment;
                   1784: }
                   1785: 
1.585     bisitz   1786: sub gradeBox_start {
                   1787:     return (
                   1788:         &Apache::loncommon::start_data_table()
                   1789:        .&Apache::loncommon::start_data_table_header_row()
                   1790:        .'<th>'.&mt('Part').'</th>'
                   1791:        .'<th>'.&mt('Points').'</th>'
                   1792:        .'<th>&nbsp;</th>'
                   1793:        .'<th>'.&mt('Assign Grade').'</th>'
                   1794:        .'<th>'.&mt('Weight').'</th>'
                   1795:        .'<th>'.&mt('Grade Status').'</th>'
                   1796:        .&Apache::loncommon::end_data_table_header_row()
                   1797:     );
                   1798: }
                   1799: 
                   1800: sub gradeBox_end {
                   1801:     return (
                   1802:         &Apache::loncommon::end_data_table()
                   1803:     );
                   1804: }
1.71      ng       1805: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1806: sub gradeBox {
1.322     albertel 1807:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1808:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1809: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1810:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1811:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1812:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1813:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1814:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1815: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1816:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1817:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1818:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1819: 				       [$partid]);
                   1820:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1821:     if ($last_resets{$partid}) {
                   1822:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1823:     }
1.596.2.12.2.  8(raebur 1824:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1825:     my $ctr = 0;
1.348     bowersj2 1826:     my $thisweight = 0;
1.349     albertel 1827:     my $increment = &get_increment();
1.485     albertel 1828: 
                   1829:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1830:     while ($thisweight<=$wgt) {
1.532     bisitz   1831: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1832:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1833: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1834: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1835: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1836:         $thisweight += $increment;
1.71      ng       1837: 	$ctr++;
                   1838:     }
1.485     albertel 1839:     $radio.='</tr></table>';
                   1840: 
                   1841:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1842: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1843: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1844: 	$wgt.')" /></td>'."\n";
1.485     albertel 1845:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1846: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1847: 	' </td>'."\n";
                   1848:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1849: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1850:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1851: 	$line.='<option></option>'.
                   1852: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1853:     } else {
1.485     albertel 1854: 	$line.='<option selected="selected"></option>'.
                   1855: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1856:     }
1.485     albertel 1857:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1858: 
                   1859: 
                   1860:     $result .= 
1.596.2.12.2.  8(raebur 1861:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1862:3):     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1.71      ng       1863:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1864: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1865: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1866: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1867:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1868:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1869:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1870:         $aggtries.'" />'."\n";
1.582     raeburn  1871:     my $res_error;
                   1872:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 1873:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1874:     if ($res_error) {
                   1875:         return &navmap_errormsg();
                   1876:     }
1.318     banghart 1877:     return $result;
                   1878: }
1.322     albertel 1879: 
                   1880: sub handback_box {
1.582     raeburn  1881:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1882:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1883:     my (@respids);
1.596.2.4  raeburn  1884:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1885:     foreach my $part_response_id (@part_response_id) {
                   1886:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1887:         if ($part eq $partid) {
1.375     albertel 1888:             push(@respids,$resp);
1.323     banghart 1889:         }
                   1890:     }
1.318     banghart 1891:     my $result;
1.323     banghart 1892:     foreach my $respid (@respids) {
1.322     albertel 1893: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1894: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1895: 	next if (!@$files);
1.596.2.4  raeburn  1896: 	my $file_counter = 0;
1.313     banghart 1897: 	foreach my $file (@$files) {
1.368     banghart 1898: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1899:                 $file_counter++;
1.368     banghart 1900:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1901:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1902:     	        $file_disp = "$name.$ext";
                   1903:     	        $file = $file_path.$file_disp;
                   1904:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1905:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1906:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1907:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1908: 	    }
1.322     albertel 1909: 	}
1.596.2.4  raeburn  1910:         if ($file_counter) {
                   1911:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1912:                        '<span class="LC_info">'.
                   1913:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1914:         }
1.313     banghart 1915:     }
1.318     banghart 1916:     return $result;    
1.71      ng       1917: }
1.44      ng       1918: 
1.58      albertel 1919: sub show_problem {
1.382     albertel 1920:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1921:     my $rendered;
1.382     albertel 1922:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1923:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1924:     if ($mode eq 'both' or $mode eq 'text') {
                   1925: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1926: 						       $env{'request.course.id'},
                   1927: 						       undef,\%form);
1.144     albertel 1928:     }
1.58      albertel 1929:     if ($removeform) {
                   1930: 	$rendered=~s|<form(.*?)>||g;
                   1931: 	$rendered=~s|</form>||g;
1.374     albertel 1932: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1933:     }
1.144     albertel 1934:     my $companswer;
                   1935:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1936: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1937: 	$companswer=
                   1938: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1939: 						    $env{'request.course.id'},
                   1940: 						    %form);
1.144     albertel 1941:     }
1.58      albertel 1942:     if ($removeform) {
                   1943: 	$companswer=~s|<form(.*?)>||g;
                   1944: 	$companswer=~s|</form>||g;
1.144     albertel 1945: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1946:     }
1.596.2.12.2.  (raeburn 1947:):     my $renderheading = &mt('View of the problem');
                   1948:):     my $answerheading = &mt('Correct answer');
                   1949:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1950:):         my $stu_fullname = $env{'form.fullname'};
                   1951:):         if ($stu_fullname eq '') {
                   1952:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1953:):         }
                   1954:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1955:):         if ($forwhom ne '') {
                   1956:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1957:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1958:):         }
                   1959:):     }
1.468     albertel 1960:     $rendered=
1.588     bisitz   1961:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1962:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1963:        .$rendered
                   1964:        .'</div>';
1.468     albertel 1965:     $companswer=
1.588     bisitz   1966:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1967:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1968:        .$companswer
                   1969:        .'</div>';
1.468     albertel 1970:     my $result;
1.144     albertel 1971:     if ($mode eq 'both') {
1.588     bisitz   1972:         $result=$rendered.$companswer;
1.144     albertel 1973:     } elsif ($mode eq 'text') {
1.588     bisitz   1974:         $result=$rendered;
1.144     albertel 1975:     } elsif ($mode eq 'answer') {
1.588     bisitz   1976:         $result=$companswer;
1.144     albertel 1977:     }
1.71      ng       1978:     return $result;
1.58      albertel 1979: }
1.397     albertel 1980: 
1.396     banghart 1981: sub files_exist {
                   1982:     my ($r, $symb) = @_;
                   1983:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1984: 
1.396     banghart 1985:     foreach my $student (@students) {
                   1986:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1987:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1988: 					      $udom,$uname);
1.396     banghart 1989:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1990:         foreach my $submission (@$string) {
                   1991:             my ($partid,$respid) =
                   1992: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1993:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1994: 					   \%record);
                   1995:             return 1 if (@$files);
1.396     banghart 1996:         }
                   1997:     }
1.397     albertel 1998:     return 0;
1.396     banghart 1999: }
1.397     albertel 2000: 
1.394     banghart 2001: sub download_all_link {
                   2002:     my ($r,$symb) = @_;
1.395     albertel 2003:     my $all_students = 
                   2004: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2005: 
                   2006:     my $parts =
                   2007: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2008: 
1.394     banghart 2009:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2010:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2011:                              'cgi.'.$identifier.'.symb' => $symb,
                   2012:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2013:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2014: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 2015:     return
                   2016: }
1.395     albertel 2017: 
1.432     banghart 2018: sub build_section_inputs {
                   2019:     my $section_inputs;
                   2020:     if ($env{'form.section'} eq '') {
                   2021:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2022:     } else {
                   2023:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2024:         foreach my $section (@sections) {
1.432     banghart 2025:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2026:         }
                   2027:     }
                   2028:     return $section_inputs;
                   2029: }
                   2030: 
1.44      ng       2031: # --------------------------- show submissions of a student, option to grade 
                   2032: sub submission {
                   2033:     my ($request,$counter,$total) = @_;
1.257     albertel 2034:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2035:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2036:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2037:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  (raeburn 2038:):     my ($symb) = &get_symb($request); 
1.324     albertel 2039:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2040: 
                   2041:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2042:4):         $request->print(
                   2043:4):             '<span class="LC_warning">'.
                   2044:4):             &mt('Unable to view requested student.').
                   2045:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2046:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2047:4):             '</span>');
1.324     albertel 2048: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2049: 	return;
                   2050:     }
                   2051: 
1.257     albertel 2052:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2053:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2054:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2055:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2056:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2057: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2058: 	'/check.gif" height="16" border="0" />';
1.41      ng       2059: 
                   2060:     # header info
                   2061:     if ($counter == 0) {
                   2062: 	&sub_page_js($request);
1.257     albertel 2063: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2064: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2065: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2066: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2067: 	    &download_all_link($request, $symb);
                   2068: 	}
1.485     albertel 2069: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1.596.2.12.2.  2(raebur 2070:3): 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2071: 
1.44      ng       2072: 	# option to display problem, only once else it cause problems 
                   2073:         # with the form later since the problem has a form.
1.257     albertel 2074: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2075: 	    my $mode;
1.257     albertel 2076: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2077: 		$mode='both';
1.257     albertel 2078: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2079: 		$mode='text';
1.257     albertel 2080: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2081: 		$mode='answer';
                   2082: 	    }
1.329     albertel 2083: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2084: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2085: 	}
1.441     www      2086: 
1.596.2.12.2.  0(raebur 2087:3): 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2088:         # if this subroutine has been called once.
1.41      ng       2089: 	my %keyhash = ();
1.257     albertel 2090: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2091: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2092: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2093: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2094: 
1.257     albertel 2095: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2096: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2097: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2098: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2099: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2100: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2101: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2102: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2103: 	}
1.257     albertel 2104: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2105: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2106: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2107: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2108: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2109: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2110: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2111: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2112: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2113: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2114: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2115: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2116: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2117: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2118: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2119: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2120: 			&build_section_inputs().
1.326     albertel 2121: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2122: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2123: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2124: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2125: 	if ($env{'form.handgrade'} eq 'yes') {
                   2126: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2127: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2128: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2129: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2130: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2131: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2132: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2133: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2134: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2135: 	    }
1.123     ng       2136: 	}
1.41      ng       2137: 	
                   2138: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2139: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2140: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2141: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2142: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2143: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2144: 		'" />'."\n".
                   2145: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2146: 	    $cts++;
                   2147: 	}
                   2148: 	$request->print($prnmsg);
1.32      ng       2149: 
1.257     albertel 2150: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2151: 
                   2152:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2153:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2154:                           keyw => 'Keyword Options',
                   2155:                           list => 'List',
                   2156:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2157:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2158:                      );
1.88      www      2159: #
                   2160: # Print out the keyword options line
                   2161: #
1.596.2.12.2.  8(raebur 2162:4):             $request->print(
                   2163:4):                 '<div class="LC_columnSection">'
                   2164:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2165:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2166:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2167:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2168:4):  class="page">'.$lt{'past'}.'</a>',
                   2169:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2170:4):                     {legend => $lt{'keyw'}})
                   2171:4):                .'</fieldset></div>'
                   2172:4):             );
                   2173:4): 
1.88      www      2174: #
                   2175: # Load the other essays for similarity check
                   2176: #
1.324     albertel 2177:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2178: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2179: 	    $apath=&escape($apath);
1.88      www      2180: 	    $apath=~s/\W/\_/gs;
1.596.2.12.2.  (raeburn 2181:):             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2182:         }
                   2183:     }
1.44      ng       2184: 
1.441     www      2185: # This is where output for one specific student would start
1.592     bisitz   2186:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2187:     $request->print(
                   2188:         "\n\n"
                   2189:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2190:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2191:        ."\n"
                   2192:     );
1.441     www      2193: 
1.592     bisitz   2194:     # Show additional functions if allowed
                   2195:     if ($perm{'vgr'}) {
                   2196:         $request->print(
                   2197:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2198:3):                 'View recent activity',
1.592     bisitz   2199:                 $uname,$udom,'check')
                   2200:            .' '
                   2201:         );
                   2202:     }
                   2203:     if ($perm{'opa'}) {
                   2204:         $request->print(
                   2205:             &Apache::loncommon::pprmlink(
                   2206:                 &mt('Set/Change parameters'),
                   2207:                 $uname,$udom,$symb,'check'));
                   2208:     }
                   2209: 
                   2210:     # Show Problem
1.257     albertel 2211:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2212: 	my $mode;
1.257     albertel 2213: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2214: 	    $mode='both';
1.257     albertel 2215: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2216: 	    $mode='text';
1.257     albertel 2217: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2218: 	    $mode='answer';
                   2219: 	}
1.329     albertel 2220: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2221: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2222:     }
1.144     albertel 2223: 
1.257     albertel 2224:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2225:     my $res_error;
                   2226:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2227:     if ($res_error) {
                   2228:         $request->print(&navmap_errormsg());
                   2229:         return;
                   2230:     }
1.41      ng       2231: 
1.44      ng       2232:     # Display student info
1.41      ng       2233:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2234: 
                   2235:     my $result='<div class="LC_Box">'
                   2236:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2237:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2238:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2239:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2240:         $result.='<p class="LC_info">'
                   2241:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2242:                 ."</p>\n";
1.469     albertel 2243:     }
                   2244: 
1.118     ng       2245:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2246:     my $fullname;
                   2247:     my $col_fullnames = [];
1.257     albertel 2248:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2249: 	(my $sub_result,$fullname,$col_fullnames)=
                   2250: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2251: 				 $counter);
                   2252: 	$result.=$sub_result;
1.41      ng       2253:     }
1.44      ng       2254:     $request->print($result."\n");
1.588     bisitz   2255: 
1.44      ng       2256:     # print student answer/submission
1.588     bisitz   2257:     # Options are (1) Handgraded submission only
1.44      ng       2258:     #             (2) Last submission, includes submission that is not handgraded 
                   2259:     #                  (for multi-response type part)
                   2260:     #             (3) Last submission plus the parts info
                   2261:     #             (4) The whole record for this student
1.596.2.12.2.  1(raebur 2262:3): 
1.151     albertel 2263: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2264: 	
                   2265: 	my $lastsubonly;
                   2266: 
1.588     bisitz   2267:         if ($$timestamp eq '') {
                   2268:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2269:         } else {
1.592     bisitz   2270:             $lastsubonly =
                   2271:                 '<div class="LC_grade_submissions_body">'
                   2272:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2273: 
1.151     albertel 2274: 	    my %seenparts;
1.375     albertel 2275: 	    my @part_response_id = &flatten_responseType($responseType);
                   2276: 	    foreach my $part (@part_response_id) {
1.393     albertel 2277: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2278: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2279: 
1.375     albertel 2280: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2281: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2282: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2283: 		    if (exists($seenparts{$partid})) { next; }
                   2284: 		    $seenparts{$partid}=1;
1.596.2.12.2.  8(raebur 2285:3):                     $request->print(
                   2286:3):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2287:3):                         ' <b>'.&mt('Collaborative submission by: [_1]',
                   2288:3):                                    '<a href="javascript:viewSubmitter(\''.
                   2289:3):                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2290:3):                                    '\');" target="_self">'.
                   2291:3):                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2292:3):                         '<br />');
1.151     albertel 2293: 		    next;
                   2294: 		}
                   2295: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2296: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2297:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2298:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2299:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2300:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2301:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2302: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2303: 		    next;
                   2304: 		}
1.468     albertel 2305: 		foreach my $submission (@$string) {
                   2306: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2307: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596.2.12.2.  0(raebur 2308:4): 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.151     albertel 2309: 		    # Similarity check
                   2310: 		    my $similar='';
1.596.2.2  raeburn  2311:                     my ($type,$trial,$rndseed);
                   2312:                     if ($hide eq 'rand') {
                   2313:                         $type = 'randomizetry';
                   2314:                         $trial = $record{"resource.$partid.tries"};
                   2315:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2316:                     }
1.596.2.12.2.  1(raebur 2317:3): 		    if ($env{'form.checkPlag'}) {
1.151     albertel 2318: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.596.2.12.2.  (raeburn 2319:): 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2320: 			if ($osim) {
                   2321: 			    $osim=int($osim*100.0);
1.426     albertel 2322: 			    my %old_course_desc = 
                   2323: 				&Apache::lonnet::coursedescription($ocrsid,
                   2324: 								   {'one_time' => 1});
                   2325: 
1.596.2.2  raeburn  2326:                             if ($hide eq 'anon') {
1.596     raeburn  2327:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2328:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2329:                             } else {
                   2330: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2331: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2332: 				        $osim,
                   2333: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2334: 				        $old_course_desc{'description'},
                   2335: 				        $old_course_desc{'num'},
                   2336: 				        $old_course_desc{'domain'}).
                   2337: 				    '</span></h3><blockquote><i>'.
                   2338: 				    &keywords_highlight($oessay).
                   2339: 				    '</i></blockquote><hr />';
                   2340:                             }
1.151     albertel 2341: 			}
1.150     albertel 2342: 		    }
1.596.2.2  raeburn  2343: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2344:                                          undef,$type,$trial,$rndseed);
1.596.2.12.2.  1(raebur 2345:3):                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
                   2346:3):                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2347: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2348:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2349:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2350:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2351:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2352:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2353: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2354: 			if (@$files) {
1.596.2.2  raeburn  2355:                             if ($hide eq 'anon') {
1.596     raeburn  2356:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2357:                             } else {
1.596.2.12.2.  8(raebur 2358:3):                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2359:3):                                             .'<br /><span class="LC_warning">';
                   2360:3):                                 if(@$files == 1) {
                   2361:3):                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2362:3):                                 } else {
                   2363:3):                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2364:3):                                 }
                   2365:3):                                 $lastsubonly .= '</span>';
                   2366:3): 
1.596     raeburn  2367:                                 foreach my $file (@$files) {
                   2368:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
1.596.2.12.2.  8(raebur 2369:3):                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2370:                                 }
                   2371:                             }
1.236     albertel 2372: 			    $lastsubonly.='<br />';
1.41      ng       2373: 			}
1.596.2.2  raeburn  2374:                         if ($hide eq 'anon') {
1.596.2.12.2.  8(raebur 2375:3):                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
1.596     raeburn  2376:                         } else {
1.596.2.12.2.  0(raebur 2377:4): 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2378:4):                             if ($draft) {
                   2379:4):                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2380:4):                             }
                   2381:4):                             $subval =
1.596     raeburn  2382: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2383: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596.2.12.2.  0(raebur 2384:4):                             if ($responsetype eq 'essay') {
                   2385:4):                                 $subval =~ s{\n}{<br />}g;
                   2386:4):                             }
                   2387:4):                             $lastsubonly.=$subval."\n";
1.596     raeburn  2388:                         }
1.151     albertel 2389: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2390: 			$lastsubonly.='</div>';
1.41      ng       2391: 		    }
                   2392: 		}
                   2393: 	    }
1.588     bisitz   2394: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2395: 	}
                   2396: 	$request->print($lastsubonly);
1.596.2.12.2.  1(raebur 2397:3):    if ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2398: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2399: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2400:3):     }
                   2401:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2402:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2403: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2404: 								 $env{'request.course.id'},
1.44      ng       2405: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2406:5): 								 'Apache::grades::keywords_highlight',
                   2407:5):                                                                  $usec,$identifier));
1.41      ng       2408:     }
1.120     ng       2409: 
1.121     ng       2410:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2411: 	.$udom.'" />'."\n");
1.44      ng       2412:     # return if view submission with no grading option
1.257     albertel 2413:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2414: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2415: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2416: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2417: 	$toGrade.='</div>'."\n";
1.257     albertel 2418: 	if (($env{'form.command'} eq 'submission') || 
                   2419: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2420: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2421: 	}
1.180     albertel 2422: 	$request->print($toGrade);
1.41      ng       2423: 	return;
1.180     albertel 2424:     } else {
1.468     albertel 2425: 	$request->print('</div>'."\n");
1.41      ng       2426:     }
1.33      ng       2427: 
1.121     ng       2428:     # essay grading message center
1.257     albertel 2429:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2430: 	my $result='<div class="LC_grade_message_center">';
                   2431:     
                   2432: 	$result.='<div class="LC_grade_message_center_header">'.
                   2433: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2434: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2435: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2436: 	if (scalar(@$col_fullnames) > 0) {
                   2437: 	    my $lastone = pop(@$col_fullnames);
                   2438: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2439: 	}
                   2440: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2441: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2442: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2443: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2444: 	    ',\''.$msgfor.'\');" target="_self">'.
1.596.2.12.2.  8(raebur 2445:3): 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2446: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.596.2.12.2.  8(raebur 2447:3): 	    ' <img src="'.$request->dir_config('lonIconsURL').
1.118     ng       2448: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2449: 	    '<br />&nbsp;('.
1.468     albertel 2450: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2451: 	$result.='</div></div>';
1.121     ng       2452: 	$request->print($result);
1.118     ng       2453:     }
1.41      ng       2454: 
                   2455:     my %seen = ();
                   2456:     my @partlist;
1.129     ng       2457:     my @gradePartRespid;
1.375     albertel 2458:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2459:     $request->print(
1.588     bisitz   2460:         '<div class="LC_Box">'
                   2461:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2462:     );
1.592     bisitz   2463:     $request->print(&gradeBox_start());
1.375     albertel 2464:     foreach my $part_response_id (@part_response_id) {
                   2465:     	my ($partid,$respid) = @{ $part_response_id };
                   2466: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2467: 	next if ($seen{$partid} > 0);
1.41      ng       2468: 	$seen{$partid}++;
1.393     albertel 2469: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2470: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2471: 	push(@partlist,$partid);
                   2472: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2473: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2474:     }
1.585     bisitz   2475:     $request->print(&gradeBox_end()); # </div>
                   2476:     $request->print('</div>');
1.468     albertel 2477: 
                   2478:     $request->print('<div class="LC_grade_info_links">');
                   2479:     $request->print('</div>');
                   2480: 
1.45      ng       2481:     $result='<input type="hidden" name="partlist'.$counter.
                   2482: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2483:     $result.='<input type="hidden" name="gradePartRespid'.
                   2484: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2485:     my $ctr = 0;
                   2486:     while ($ctr < scalar(@partlist)) {
                   2487: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2488: 	    $partlist[$ctr].'" />'."\n";
                   2489: 	$ctr++;
                   2490:     }
1.468     albertel 2491:     $request->print($result.''."\n");
1.41      ng       2492: 
1.441     www      2493: # Done with printing info for one student
                   2494: 
1.468     albertel 2495:     $request->print('</div>');#LC_grade_show_user
1.441     www      2496: 
                   2497: 
1.41      ng       2498:     # print end of form
                   2499:     if ($counter == $total) {
1.592     bisitz   2500:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2501: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2502: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2503: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2504: 	my $ntstu ='<select name="NTSTU">'.
                   2505: 	    '<option>1</option><option>2</option>'.
                   2506: 	    '<option>3</option><option>5</option>'.
                   2507: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2508: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2509: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2510:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2511: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2512: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2513: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2514: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2515:         $endform.='<span class="LC_warning">'.
                   2516:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2517:                   '</span>'."\n" ;
1.349     albertel 2518:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2519:             "' name='increment' />";
1.485     albertel 2520: 	$endform.='</td></tr></table></form>';
1.324     albertel 2521: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2522: 	$request->print($endform);
                   2523:     }
                   2524:     return '';
1.38      ng       2525: }
                   2526: 
1.464     albertel 2527: sub check_collaborators {
                   2528:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2529:     my ($result,@col_fullnames);
                   2530:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2531:     foreach my $part (keys(%$handgrade)) {
                   2532: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2533: 					'.maxcollaborators',
                   2534: 					$symb,$udom,$uname);
                   2535: 	next if ($ncol <= 0);
                   2536: 	$part =~ s/\_/\./g;
                   2537: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2538: 	my (@good_collaborators, @bad_collaborators);
                   2539: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2540: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2541: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2542: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2543: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2544: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2545: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2546: 	    # Doing this grep allows 'fuzzy' specification
                   2547: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2548: 			       keys(%$classlist));
                   2549: 	    if (! scalar(@matches)) {
                   2550: 		push(@bad_collaborators, $possible_collaborator);
                   2551: 	    } else {
                   2552: 		push(@good_collaborators, @matches);
                   2553: 	    }
                   2554: 	}
                   2555: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2556: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2557: 	    foreach my $name (@good_collaborators) {
                   2558: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2559: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2560: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2561: 	    }
1.596.2.4  raeburn  2562: 	    $result.='</ol><br />'."\n";
1.466     albertel 2563: 	    my ($part)=split(/\./,$part);
1.464     albertel 2564: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2565: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2566: 		"\n";
                   2567: 	}
                   2568: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2569: 	    $result.='<div class="LC_warning">';
1.464     albertel 2570: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2571: 	    $result .= '</div>';
                   2572: 	}         
                   2573: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2574: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2575: 	    $result .= &mt('This student has submitted too many '.
                   2576: 		'collaborators.  Maximum is [_1].',$ncol);
                   2577: 	    $result .= '</div>';
                   2578: 	}
                   2579:     }
                   2580:     return ($result,$fullname,\@col_fullnames);
                   2581: }
                   2582: 
1.44      ng       2583: #--- Retrieve the last submission for all the parts
1.38      ng       2584: sub get_last_submission {
1.119     ng       2585:     my ($returnhash)=@_;
1.596     raeburn  2586:     my (@string,$timestamp,%lasthidden);
1.119     ng       2587:     if ($$returnhash{'version'}) {
1.46      ng       2588: 	my %lasthash=();
                   2589: 	my ($version);
1.119     ng       2590: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2591: 	    foreach my $key (sort(split(/\:/,
                   2592: 					$$returnhash{$version.':keys'}))) {
                   2593: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2594: 		$timestamp = 
1.545     raeburn  2595: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2596: 	    }
                   2597: 	}
1.596.2.2  raeburn  2598:         my (%typeparts,%randombytry);
1.596     raeburn  2599:         my $showsurv = 
                   2600:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2601:         foreach my $key (sort(keys(%lasthash))) {
                   2602:             if ($key =~ /\.type$/) {
                   2603:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2604:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2605:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2606:                     my ($ign,@parts) = split(/\./,$key);
                   2607:                     pop(@parts);
1.596.2.3  raeburn  2608:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2609:                     if ($lasthash{$key} eq 'randomizetry') {
                   2610:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2611:                     } else {
                   2612:                         unless ($showsurv) {
                   2613:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2614:                         }
1.596     raeburn  2615:                     }
                   2616:                     delete($lasthash{$key});
                   2617:                 }
                   2618:             }
                   2619:         }
                   2620:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2621:         my @randomize = keys(%randombytry);
1.397     albertel 2622: 	foreach my $key (keys(%lasthash)) {
                   2623: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2624:             my $hide;
                   2625:             if (@hidden) {
                   2626:                 foreach my $id (@hidden) {
                   2627:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2628:                         $hide = 'anon';
1.596     raeburn  2629:                         last;
                   2630:                     }
                   2631:                 }
                   2632:             }
1.596.2.2  raeburn  2633:             unless ($hide) {
                   2634:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2635:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2636:                         if ($key =~ /^\Q$id\E/) {
                   2637:                             $hide = 'rand';
                   2638:                             last;
                   2639:                         }
                   2640:                     }
                   2641:                 }
                   2642:             }
1.397     albertel 2643: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  0(raebur 2644:4): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
                   2645:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2646:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2647:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2648: 	}
                   2649:     }
1.397     albertel 2650:     if (!@string) {
                   2651: 	$string[0] =
1.539     riegler  2652: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2653:     }
                   2654:     return (\@string,\$timestamp);
1.38      ng       2655: }
1.35      ng       2656: 
1.44      ng       2657: #--- High light keywords, with style choosen by user.
1.38      ng       2658: sub keywords_highlight {
1.44      ng       2659:     my $string    = shift;
1.257     albertel 2660:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2661:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2662:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2663:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2664:     foreach my $keyword (@keylist) {
                   2665: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2666:     }
                   2667:     return $string;
1.38      ng       2668: }
1.36      ng       2669: 
1.596.2.12.2.  (raeburn 2670:): # For Tasks provide a mechanism to display previous version for one specific student
                   2671:): 
                   2672:): sub show_previous_task_version {
                   2673:):     my ($request,$symb) = @_;
                   2674:):     if ($symb eq '') {
          8(raebur 2675:4):         $request->print(
                   2676:4):             '<span class="LC_error">'.
                   2677:4):             &mt('Unable to handle ambiguous references.').
                   2678:4):             '</span>');
          (raeburn 2679:):         return '';
                   2680:):     }
                   2681:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2682:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2683:):     if (!&canview($usec)) {
          8(raebur 2684:4):         $request->print('<span class="LC_warning">'.
                   2685:4):                         &mt('Unable to view previous version for requested student.').
                   2686:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2687:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2688:4):                         '</span>');
          (raeburn 2689:):         return;
                   2690:):     }
                   2691:):     my $mode = 'both';
                   2692:):     my $isTask = ($symb =~/\.task$/);
                   2693:):     if ($isTask) {
                   2694:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2695:):             if ($env{'form.fullname'} eq '') {
                   2696:):                 $env{'form.fullname'} =
                   2697:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2698:):             }
                   2699:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2700:):             $request->print("\n\n".
                   2701:):                             '<div class="LC_grade_show_user">'.
                   2702:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2703:):                             '</h2>'."\n");
                   2704:):             &Apache::lonxml::clear_problem_counter();
                   2705:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2706:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2707:):             $request->print("\n</div>");
                   2708:):         }
                   2709:):     }
                   2710:):     return;
                   2711:): }
                   2712:): 
                   2713:): sub choose_task_version_form {
                   2714:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2715:):     my $isTask = ($symb =~/\.task$/);
                   2716:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2717:):     if ($isTask) {
                   2718:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2719:):                                               $udom,$uname);
                   2720:):         if (($record{'resource.0.version'} eq '') ||
                   2721:):             ($record{'resource.0.version'} < 2)) {
                   2722:):             return ($record{'resource.0.version'},
                   2723:):                     $record{'resource.0.version'},$result,$js);
                   2724:):         } else {
                   2725:):             $current = $record{'resource.0.version'};
                   2726:):         }
                   2727:):         if ($env{'form.previousversion'}) {
                   2728:):             $displayed = $env{'form.previousversion'};
                   2729:):             $rowtitle = &mt('Choose another version:')
                   2730:):         } else {
                   2731:):             $displayed = $current;
                   2732:):             $rowtitle = &mt('Show earlier version:');
                   2733:):         }
                   2734:):         $result = '<div class="LC_left_float">';
                   2735:):         my $list;
                   2736:):         my $numversions = 0;
                   2737:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2738:):             if ($i == $current) {
                   2739:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   2740:):                     next;
                   2741:):                 } else {
                   2742:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2743:):                     $numversions ++;
                   2744:):                 }
                   2745:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2746:):                 unless ($i == $env{'form.previousversion'}) {
                   2747:):                     $numversions ++;
                   2748:):                 }
                   2749:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2750:):             }
                   2751:):         }
                   2752:):         if ($numversions) {
                   2753:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2754:):             $result .=
                   2755:):                 '<form name="getprev" method="post" action=""'.
                   2756:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2757:):                 &Apache::loncommon::start_data_table().
                   2758:):                 &Apache::loncommon::start_data_table_row().
                   2759:):                 '<th align="left">'.$rowtitle.'</th>'.
                   2760:):                 '<td><select name="version">'.
                   2761:):                 '<option>'.&mt('Select').'</option>'.
                   2762:):                 $list.
                   2763:):                 '</select></td>'.
                   2764:):                 &Apache::loncommon::end_data_table_row();
                   2765:):             unless ($nomenu) {
                   2766:):                 $result .= &Apache::loncommon::start_data_table_row().
                   2767:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2768:):                 '<td><span class="LC_nobreak">'.
                   2769:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2770:):                 &mt('Yes').'</label>'.
                   2771:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2772:):                 '</span></td>'.
                   2773:):                 &Apache::loncommon::end_data_table_row();
                   2774:):             }
                   2775:):             $result .=
                   2776:):                 &Apache::loncommon::start_data_table_row().
                   2777:):                 '<th align="left">&nbsp;</th>'.
                   2778:):                 '<td>'.
                   2779:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2780:):                 '</td>'.
                   2781:):                 &Apache::loncommon::end_data_table_row().
                   2782:):                 &Apache::loncommon::end_data_table().
                   2783:):                 '</form>';
                   2784:):             $js = &previous_display_javascript($nomenu,$current);
                   2785:):         } elsif ($displayed && $nomenu) {
                   2786:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2787:):         } else {
                   2788:):             $result .= &mt('No previous versions to show for this student');
                   2789:):         }
                   2790:):         $result .= '</div>';
                   2791:):     }
                   2792:):     return ($current,$displayed,$result,$js);
                   2793:): }
                   2794:): 
                   2795:): sub previous_display_javascript {
                   2796:):     my ($nomenu,$current) = @_;
                   2797:):     my $js = <<"JSONE";
                   2798:): <script type="text/javascript">
                   2799:): // <![CDATA[
                   2800:): function previousVersion(uname,udom,symb) {
                   2801:):     var current = '$current';
                   2802:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2803:):     var prevstr = new RegExp("^\\\\d+\$");
                   2804:):     if (!prevstr.test(version)) {
                   2805:):         return false;
                   2806:):     }
                   2807:):     var url = '';
                   2808:):     if (version == current) {
                   2809:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2810:):     } else {
                   2811:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2812:):     }
                   2813:): JSONE
                   2814:):     if ($nomenu) {
                   2815:):         $js .= <<"JSTWO";
                   2816:):     document.location.href = url;
                   2817:): JSTWO
                   2818:):     } else {
                   2819:):         $js .= <<"JSTHREE";
                   2820:):     var newwin = 0;
                   2821:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2822:):         if (document.getprev.prevwin[i].checked == true) {
                   2823:):             newwin = document.getprev.prevwin[i].value;
                   2824:):         }
                   2825:):     }
                   2826:):     if (newwin == 1) {
                   2827:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2828:):         url = url+'&inhibitmenu=yes';
                   2829:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2830:):             previousWin = window.open(url,'',options,1);
                   2831:):         } else {
                   2832:):             previousWin.location.href = url;
                   2833:):         }
                   2834:):         previousWin.focus();
                   2835:):         return false;
                   2836:):     } else {
                   2837:):         document.location.href = url;
                   2838:):         return false;
                   2839:):     }
                   2840:): JSTHREE
                   2841:):     }
                   2842:):     $js .= <<"ENDJS";
                   2843:):     return false;
                   2844:): }
                   2845:): // ]]>
                   2846:): </script>
                   2847:): ENDJS
                   2848:): 
                   2849:): }
                   2850:): 
1.44      ng       2851: #--- Called from submission routine
1.38      ng       2852: sub processHandGrade {
1.41      ng       2853:     my ($request) = shift;
1.596.2.12.2.  (raeburn 2854:):     my ($symb)   = &get_symb($request);
1.324     albertel 2855:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2856:     my $button = $env{'form.gradeOpt'};
                   2857:     my $ngrade = $env{'form.NCT'};
                   2858:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2859:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2860:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2861: 
1.44      ng       2862:     if ($button eq 'Save & Next') {
                   2863: 	my $ctr = 0;
                   2864: 	while ($ctr < $ngrade) {
1.257     albertel 2865: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 2866:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2867:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2868: 	    if ($errorflag eq 'no_score') {
                   2869: 		$ctr++;
                   2870: 		next;
                   2871: 	    }
1.104     albertel 2872: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 2873:4):                 $request->print(
                   2874:4):                     '<span class="LC_error">'
                   2875:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2876:4):                    .'</span>');
1.104     albertel 2877: 		$ctr++;
                   2878: 		next;
                   2879: 	    }
1.596.2.12.2.  1(raebur 2880:5):             if ($numhidden) {
                   2881:5):                 $request->print(
                   2882:5):                     '<span class="LC_info">'
                   2883:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2884:5):                    .'</span><br />');
                   2885:5):             }
1.257     albertel 2886: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2887: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2888: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2889:             my ($feedurl,$showsymb) =
                   2890: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2891: 	    my $messagetail;
1.62      albertel 2892: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2893: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2894: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2895: 		$subject.=' ['.$restitle.']';
1.44      ng       2896: 		my (@msgnum) = split(/,/,$includemsg);
                   2897: 		foreach (@msgnum) {
1.257     albertel 2898: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2899: 		}
1.80      ng       2900: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2901: 		if ($env{'form.withgrades'.$ctr}) {
                   2902: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2903: 		    $messagetail = " for <a href=\"".
1.418     albertel 2904: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2905: 		}
                   2906: 		$msgstatus = 
                   2907:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2908: 						     $message.$messagetail,
1.418     albertel 2909:                                                      undef,$feedurl,undef,
1.386     raeburn  2910:                                                      undef,undef,$showsymb,
                   2911:                                                      $restitle);
1.574     bisitz   2912: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2913: 				$msgstatus.'<br />');
1.44      ng       2914: 	    }
1.257     albertel 2915: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2916: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2917: 		foreach my $collabstr (@collabstrs) {
                   2918: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2919: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2920: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2921: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2922: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2923: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2924: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2925: 			    next;
1.418     albertel 2926: 			} elsif ($message ne '') {
                   2927: 			    my ($baseurl,$showsymb) = 
                   2928: 				&get_feedurl_and_symb($symb,$collaborator,
                   2929: 						      $udom);
                   2930: 			    if ($env{'form.withgrades'.$ctr}) {
                   2931: 				$messagetail = " for <a href=\"".
1.386     raeburn  2932:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2933: 			    }
1.418     albertel 2934: 			    $msgstatus = 
                   2935: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2936: 			}
1.44      ng       2937: 		    }
                   2938: 		}
                   2939: 	    }
                   2940: 	    $ctr++;
                   2941: 	}
                   2942:     }
                   2943: 
1.257     albertel 2944:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2945: 	# Keywords sorted in alphabatical order
1.257     albertel 2946: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2947: 	my %keyhash = ();
1.257     albertel 2948: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2949: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2950: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2951: 	$env{'form.keywords'} = join(' ',@keywords);
                   2952: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2953: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2954: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2955: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2956: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2957: 
                   2958: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2959: 	# New messages are saved in env for the next student.
1.119     ng       2960: 	# All messages are saved in nohist_handgrade.db
                   2961: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2962: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2963: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2964: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2965: 		$idx++;
                   2966: 	    }
                   2967: 	    $ctr++;
1.41      ng       2968: 	}
1.119     ng       2969: 	$ctr = 0;
                   2970: 	while ($ctr < $ngrade) {
1.257     albertel 2971: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2972: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2973: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2974: 		$idx++;
                   2975: 	    }
                   2976: 	    $ctr++;
1.41      ng       2977: 	}
1.257     albertel 2978: 	$env{'form.savemsgN'} = --$idx;
                   2979: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2980: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2981: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2982:     }
1.44      ng       2983:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2984:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2985:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2986: 	my ($ctr,$total) = (0,0);
                   2987: 	while ($ctr < $ngrade) {
1.257     albertel 2988: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2989: 	    $ctr++;
                   2990: 	}
1.257     albertel 2991: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2992: 	$ctr = 0;
                   2993: 	while ($ctr < $total) {
1.257     albertel 2994: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2995: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2996: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2997: 	    &submission($request,$ctr,$total-1);
1.41      ng       2998: 	    $ctr++;
                   2999: 	}
                   3000: 	return '';
                   3001:     }
1.36      ng       3002: 
1.121     ng       3003: # Go directly to grade student - from submission or link from chart page
1.120     ng       3004:     if ($button eq 'Grade Student') {
1.324     albertel 3005: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 3006: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   3007: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3008: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       3009: 	&submission($request,0,0);
                   3010: 	return '';
                   3011:     }
                   3012: 
1.44      ng       3013:     # Get the next/previous one or group of students
1.257     albertel 3014:     my $firststu = $env{'form.unamedom0'};
                   3015:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3016:     my $ctr = 2;
1.41      ng       3017:     while ($laststu eq '') {
1.257     albertel 3018: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3019: 	$ctr++;
                   3020: 	$laststu = $firststu if ($ctr > $ngrade);
                   3021:     }
1.44      ng       3022: 
1.41      ng       3023:     my (@parsedlist,@nextlist);
                   3024:     my ($nextflg) = 0;
1.524     raeburn  3025:     foreach my $item (sort 
1.294     albertel 3026: 	     {
                   3027: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3028: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3029: 		 }
                   3030: 		 return $a cmp $b;
                   3031: 	     } (keys(%$fullname))) {
1.41      ng       3032: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3033: 	    push(@parsedlist,$item);
1.41      ng       3034: 	}
1.524     raeburn  3035: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3036: 	if ($button eq 'Previous') {
1.524     raeburn  3037: 	    last if ($item eq $firststu);
                   3038: 	    push(@parsedlist,$item);
1.41      ng       3039: 	}
                   3040:     }
                   3041:     $ctr = 0;
                   3042:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3043:     my $res_error;
                   3044:     my ($partlist) = &response_type($symb,\$res_error);
                   3045:     if ($res_error) {
                   3046:         $request->print(&navmap_errormsg());
                   3047:         return;
                   3048:     }
1.41      ng       3049:     foreach my $student (@parsedlist) {
1.257     albertel 3050: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3051: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3052: 	
                   3053: 	if ($submitonly eq 'queued') {
                   3054: 	    my %queue_status = 
                   3055: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3056: 							$udom,$uname);
                   3057: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3058: 	}
                   3059: 
1.156     albertel 3060: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3061: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3062: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3063: 	    my $submitted = 0;
1.248     albertel 3064: 	    my $ungraded = 0;
                   3065: 	    my $incorrect = 0;
1.524     raeburn  3066: 	    foreach my $item (keys(%status)) {
                   3067: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3068: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3069: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3070: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3071: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3072: 		    $submitted = 0;
                   3073: 		}
1.41      ng       3074: 	    }
1.156     albertel 3075: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3076: 				     $submitonly eq 'incorrect' ||
                   3077: 				     $submitonly eq 'graded'));
1.248     albertel 3078: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3079: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3080: 	}
1.524     raeburn  3081: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3082: 	last if ($ctr == $ntstu);
1.41      ng       3083: 	$ctr++;
                   3084:     }
1.36      ng       3085: 
1.41      ng       3086:     $ctr = 0;
                   3087:     my $total = scalar(@nextlist)-1;
1.39      ng       3088: 
1.524     raeburn  3089:     foreach (sort(@nextlist)) {
1.41      ng       3090: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3091: 	$env{'form.student'}  = $uname;
                   3092: 	$env{'form.userdom'}  = $udom;
                   3093: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       3094: 	&submission($request,$ctr,$total);
                   3095: 	$ctr++;
                   3096:     }
                   3097:     if ($total < 0) {
1.485     albertel 3098: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  3099: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 3100: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 3101: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       3102: 	$request->print($the_end);
                   3103:     }
                   3104:     return '';
1.38      ng       3105: }
1.36      ng       3106: 
1.44      ng       3107: #---- Save the score and award for each student, if changed
1.38      ng       3108: sub saveHandGrade {
1.324     albertel 3109:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3110:     my @version_parts;
1.104     albertel 3111:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3112: 					   $env{'request.course.id'});
1.104     albertel 3113:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3114:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3115:     my @parts_graded;
1.77      ng       3116:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3117:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3118:     my %aggregate = ();
                   3119:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3120:5):     if ($env{'form.HIDE'.$newflg}) {
                   3121:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3122:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3123:5):         $totchg += $numchgs;
                   3124:5):     }
1.301     albertel 3125:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3126:     foreach my $new_part (@parts) {
1.337     banghart 3127: 	#collaborator ($submi may vary for different parts
1.259     banghart 3128: 	if ($submitter && $new_part ne $part) { next; }
                   3129: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3130: 	if ($dropMenu eq 'excused') {
1.259     banghart 3131: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3132: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3133: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3134: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3135: 		}
1.364     banghart 3136: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3137: 	    }
1.125     ng       3138: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3139: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3140: 	    foreach my $key (keys(%record)) {
1.259     banghart 3141: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3142: 	    }
1.259     banghart 3143: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3144: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3145:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3146: 
                   3147:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3148: 					       [$new_part]);
                   3149:             my $aggtries =$totaltries;
1.269     raeburn  3150:             if ($last_resets{$new_part}) {
1.270     albertel 3151:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3152: 					   $new_part);
1.269     raeburn  3153:             }
1.270     albertel 3154: 
                   3155:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3156:             if ($aggtries > 0) {
1.327     albertel 3157:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3158:                 $aggregateflag = 1;
                   3159:             }
1.125     ng       3160: 	} elsif ($dropMenu eq '') {
1.259     banghart 3161: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3162: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3163: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3164: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3165: 		next;
                   3166: 	    }
1.259     banghart 3167: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3168: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3169: 	    my $partial= $pts/$wgt;
1.259     banghart 3170: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3171: 		#do not update score for part if not changed.
1.346     banghart 3172:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3173: 		next;
1.251     banghart 3174: 	    } else {
1.524     raeburn  3175: 	        push(@parts_graded,$new_part);
1.153     albertel 3176: 	    }
1.259     banghart 3177: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3178: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3179: 	    }
1.259     banghart 3180: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3181: 	    if ($partial == 0) {
1.153     albertel 3182: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3183: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3184: 		}
1.41      ng       3185: 	    } else {
1.153     albertel 3186: 		if ($record{$reckey} ne 'correct_by_override') {
                   3187: 		    $newrecord{$reckey} = 'correct_by_override';
                   3188: 		}
                   3189: 	    }	    
                   3190: 	    if ($submitter && 
1.259     banghart 3191: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3192: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3193: 	    }
1.259     banghart 3194: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3195: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3196: 	}
1.259     banghart 3197: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3198: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3199: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3200: 	        $dropMenu eq 'reset status')
                   3201: 	   {
1.524     raeburn  3202: 	    push(@version_parts,$new_part);
1.259     banghart 3203: 	}
1.41      ng       3204:     }
1.301     albertel 3205:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3206:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3207: 
1.344     albertel 3208:     if (%newrecord) {
                   3209:         if (@version_parts) {
1.364     banghart 3210:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3211:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3212: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3213: 	    foreach my $new_part (@version_parts) {
                   3214: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3215: 				$new_part,\%newrecord);
                   3216: 	    }
1.259     banghart 3217:         }
1.44      ng       3218: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3219: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3220: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3221: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3222:     }
1.269     raeburn  3223:     if ($aggregateflag) {
                   3224:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3225: 			      $cdom,$cnum);
1.269     raeburn  3226:     }
1.596.2.12.2.  1(raebur 3227:5):     return ('',$pts,$wgt,$totchg);
                   3228:5): }
                   3229:5): 
                   3230:5): sub makehidden {
                   3231:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3232:5):     return unless (ref($record) eq 'HASH');
                   3233:5):     my %modified;
                   3234:5):     my $numchanged = 0;
                   3235:5):     if (exists($record->{$version.':keys'})) {
                   3236:5):         my $partsregexp = $parts;
                   3237:5):         $partsregexp =~ s/,/|/g;
                   3238:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3239:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3240:5):                  my $item = $1;
                   3241:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3242:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3243:5):                  }
                   3244:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3245:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3246:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3247:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3248:5):             }
                   3249:5):         }
                   3250:5):         if (keys(%modified)) {
                   3251:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3252:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3253:5):                 $numchanged ++;
                   3254:5):             }
                   3255:5):         }
                   3256:5):     }
                   3257:5):     return $numchanged;
1.36      ng       3258: }
1.322     albertel 3259: 
1.380     albertel 3260: sub check_and_remove_from_queue {
                   3261:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3262:     my @ungraded_parts;
                   3263:     foreach my $part (@{$parts}) {
                   3264: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3265: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3266: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3267: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3268: 		) {
                   3269: 	    push(@ungraded_parts, $part);
                   3270: 	}
                   3271:     }
                   3272:     if ( !@ungraded_parts ) {
                   3273: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3274: 					       $cnum,$domain,$stuname);
                   3275:     }
                   3276: }
                   3277: 
1.337     banghart 3278: sub handback_files {
                   3279:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3280:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3281:     my $res_error;
                   3282:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3283:     if ($res_error) {
                   3284:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3285:         return;
                   3286:     }
1.596.2.4  raeburn  3287:     my @handedback;
                   3288:     my $file_msg;
1.375     albertel 3289:     my @part_response_id = &flatten_responseType($responseType);
                   3290:     foreach my $part_response_id (@part_response_id) {
                   3291:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3292: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3293:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3294:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3295:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3296: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3297:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3298:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3299:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3300:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3301: 		        &file_name_version_ext($answer_file);
1.355     banghart 3302: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3303:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3304:):                     my ($dir_list,$listerror) =
                   3305:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3306:):                                                  $domain,$stuname,$getpropath);
                   3307:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3308:3):                     # fix filename
1.355     banghart 3309:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3310:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3311:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3312:             	                                $save_file_name);
1.337     banghart 3313:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3314:                         $request->print('<br /><span class="LC_error">'.
                   3315:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3316:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3317:                                         '</span>');
1.356     banghart 3318:                     } else {
1.360     banghart 3319:                         # mark the file as read only
1.596.2.4  raeburn  3320:                         push(@handedback,$save_file_name);
1.367     albertel 3321: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3322: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3323: 			}
                   3324:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3325: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3326: 
1.337     banghart 3327:                     }
1.596.2.12.2.  3(raebur 3328:3):                     $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 3329:                 }
                   3330:             }
                   3331:         }
1.596.2.4  raeburn  3332:     }
                   3333:     if (@handedback > 0) {
                   3334:         $request->print('<br />');
                   3335:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3336:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3337:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3338:         my ($subject,$message);
                   3339:         if (scalar(@handedback) == 1) {
                   3340:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3341:         } else {
                   3342:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3343:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3344:         }
                   3345:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3346:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3347:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3348:         my ($feedurl,$showsymb) =
                   3349:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3350:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3351:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3352:         my $msgstatus =
                   3353:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3354:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3355:                  $restitle);
                   3356:         if ($msgstatus) {
                   3357:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3358:         }
                   3359:     }
1.338     banghart 3360:     return;
1.337     banghart 3361: }
                   3362: 
1.418     albertel 3363: sub get_feedurl_and_symb {
                   3364:     my ($symb,$uname,$udom) = @_;
                   3365:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3366:     $url = &Apache::lonnet::clutter($url);
                   3367:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3368: 					$symb,$udom,$uname);
                   3369:     if ($encrypturl =~ /^yes$/i) {
                   3370: 	&Apache::lonenc::encrypted(\$url,1);
                   3371: 	&Apache::lonenc::encrypted(\$symb,1);
                   3372:     }
                   3373:     return ($url,$symb);
                   3374: }
                   3375: 
1.313     banghart 3376: sub get_submitted_files {
                   3377:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3378:     my @files;
                   3379:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3380:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3381:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3382:     	    push(@files,$file_url.$file);
                   3383:         }
                   3384:     }
                   3385:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3386:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3387:     }
                   3388:     return (\@files);
                   3389: }
1.322     albertel 3390: 
1.269     raeburn  3391: # ----------- Provides number of tries since last reset.
                   3392: sub get_num_tries {
                   3393:     my ($record,$last_reset,$part) = @_;
                   3394:     my $timestamp = '';
                   3395:     my $num_tries = 0;
                   3396:     if ($$record{'version'}) {
                   3397:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3398:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3399:                 $timestamp = $$record{$version.':timestamp'};
                   3400:                 if ($timestamp > $last_reset) {
                   3401:                     $num_tries ++;
                   3402:                 } else {
                   3403:                     last;
                   3404:                 }
                   3405:             }
                   3406:         }
                   3407:     }
                   3408:     return $num_tries;
                   3409: }
                   3410: 
                   3411: # ----------- Determine decrements required in aggregate totals 
                   3412: sub decrement_aggs {
                   3413:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3414:     my %decrement = (
                   3415:                         attempts => 0,
                   3416:                         users => 0,
                   3417:                         correct => 0
                   3418:                     );
                   3419:     $decrement{'attempts'} = $aggtries;
                   3420:     if ($solvedstatus =~ /^correct/) {
                   3421:         $decrement{'correct'} = 1;
                   3422:     }
                   3423:     if ($aggtries == $totaltries) {
                   3424:         $decrement{'users'} = 1;
                   3425:     }
1.524     raeburn  3426:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3427:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3428:     }
                   3429:     return;
                   3430: }
                   3431: 
                   3432: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3433: sub get_last_resets {
1.270     albertel 3434:     my ($symb,$courseid,$partids) =@_;
                   3435:     my %last_resets;
1.269     raeburn  3436:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3437:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3438:     my @keys;
                   3439:     foreach my $part (@{$partids}) {
                   3440: 	push(@keys,"$symb\0$part\0resettime");
                   3441:     }
                   3442:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3443: 				     $cdom,$cname);
                   3444:     foreach my $part (@{$partids}) {
                   3445: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3446:     }
1.270     albertel 3447:     return %last_resets;
1.269     raeburn  3448: }
                   3449: 
1.251     banghart 3450: # ----------- Handles creating versions for portfolio files as answers
                   3451: sub version_portfiles {
1.343     banghart 3452:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3453:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3454:     my @returned_keys;
1.255     banghart 3455:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3456:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3457:     foreach my $key (keys(%$record)) {
1.259     banghart 3458:         my $new_portfiles;
1.263     banghart 3459:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3460:             my @versioned_portfiles;
1.367     albertel 3461:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3462:             foreach my $file (@portfiles) {
1.306     banghart 3463:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3464:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3465: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3466: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3467:):                 my $getpropath = 1;
                   3468:):                 my ($dir_list,$listerror) =
                   3469:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3470:):                                              $stu_name,$getpropath);
                   3471:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3472:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3473:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3474:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3475:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3476:                         [$directory.$new_answer],
1.306     banghart 3477:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3478:                 }
1.252     banghart 3479:             }
1.343     banghart 3480:             $$record{$key} = join(',',@versioned_portfiles);
                   3481:             push(@returned_keys,$key);
1.251     banghart 3482:         }
                   3483:     } 
1.343     banghart 3484:     return (@returned_keys);   
1.305     banghart 3485: }
                   3486: 
1.307     banghart 3487: sub get_next_version {
1.341     banghart 3488:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3489:     my $version;
1.596.2.12.2.  (raeburn 3490:):     if (ref($dir_list) eq 'ARRAY') {
                   3491:):         foreach my $row (@{$dir_list}) {
                   3492:):             my ($file) = split(/\&/,$row,2);
                   3493:):             my ($file_name,$file_version,$file_ext) =
                   3494:): 	        &file_name_version_ext($file);
                   3495:):             if (($file_name eq $answer_name) && 
                   3496:): 	        ($file_ext eq $answer_ext)) {
                   3497:):                 # gets here if filename and extension match, 
                   3498:):                 # regardless of version
1.307     banghart 3499:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3500:):                     # a versioned file is found  so save it for later
                   3501:):                     if ($file_version > $version) {
                   3502:): 		        $version = $file_version;
                   3503:):                     }
1.307     banghart 3504: 	        }
                   3505:             }
                   3506:         }
1.596.2.12.2.  (raeburn 3507:):     }
1.307     banghart 3508:     $version ++;
                   3509:     return($version);
                   3510: }
                   3511: 
1.305     banghart 3512: sub version_selected_portfile {
1.306     banghart 3513:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3514:     my ($answer_name,$answer_ver,$answer_ext) =
                   3515:         &file_name_version_ext($file_name);
                   3516:     my $new_answer;
                   3517:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3518:     if($env{'form.copy'} eq '-1') {
                   3519:         $new_answer = 'problem getting file';
                   3520:     } else {
                   3521:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3522:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3523:                             $stu_name,$domain,'copy',
                   3524: 		        '/portfolio'.$directory.$new_answer);
                   3525:     }    
                   3526:     return ($new_answer);
1.251     banghart 3527: }
                   3528: 
1.304     albertel 3529: sub file_name_version_ext {
                   3530:     my ($file)=@_;
                   3531:     my @file_parts = split(/\./, $file);
                   3532:     my ($name,$version,$ext);
                   3533:     if (@file_parts > 1) {
                   3534: 	$ext=pop(@file_parts);
                   3535: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3536: 	    $version=pop(@file_parts);
                   3537: 	}
                   3538: 	$name=join('.',@file_parts);
                   3539:     } else {
                   3540: 	$name=join('.',@file_parts);
                   3541:     }
                   3542:     return($name,$version,$ext);
                   3543: }
                   3544: 
1.44      ng       3545: #--------------------------------------------------------------------------------------
                   3546: #
                   3547: #-------------------------- Next few routines handles grading by section or whole class
                   3548: #
                   3549: #--- Javascript to handle grading by section or whole class
1.42      ng       3550: sub viewgrades_js {
                   3551:     my ($request) = shift;
                   3552: 
1.539     riegler  3553:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3554:     $request->print(<<VIEWJAVASCRIPT);
                   3555: <script type="text/javascript" language="javascript">
1.45      ng       3556:    function writePoint(partid,weight,point) {
1.125     ng       3557: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3558: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3559: 	if (point == "textval") {
1.125     ng       3560: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3561: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3562: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3563: 		var resetbox = false;
                   3564: 		for (var i=0; i<radioButton.length; i++) {
                   3565: 		    if (radioButton[i].checked) {
                   3566: 			textbox.value = i;
                   3567: 			resetbox = true;
                   3568: 		    }
                   3569: 		}
                   3570: 		if (!resetbox) {
                   3571: 		    textbox.value = "";
                   3572: 		}
                   3573: 		return;
                   3574: 	    }
1.109     matthew  3575: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3576: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3577: 				   ") greater than the weight for the part. Accept?");
                   3578: 		if (resp == false) {
                   3579: 		    textbox.value = "";
                   3580: 		    return;
                   3581: 		}
                   3582: 	    }
1.42      ng       3583: 	    for (var i=0; i<radioButton.length; i++) {
                   3584: 		radioButton[i].checked=false;
1.109     matthew  3585: 		if (parseFloat(point) == i) {
1.42      ng       3586: 		    radioButton[i].checked=true;
                   3587: 		}
                   3588: 	    }
1.41      ng       3589: 
1.42      ng       3590: 	} else {
1.125     ng       3591: 	    textbox.value = parseFloat(point);
1.42      ng       3592: 	}
1.41      ng       3593: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3594: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3595: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3596: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3597: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3598: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3599: 	    if (saveval != "correct") {
                   3600: 		scorename.value = point;
1.43      ng       3601: 		if (selname[0].selected != true) {
                   3602: 		    selname[0].selected = true;
                   3603: 		}
1.42      ng       3604: 	    }
                   3605: 	}
1.125     ng       3606: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3607:     }
                   3608: 
                   3609:     function writeRadText(partid,weight) {
1.125     ng       3610: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3611: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3612:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3613: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3614: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3615: 	    for (var i=0; i<radioButton.length; i++) {
                   3616: 		radioButton[i].checked=false;
                   3617: 
                   3618: 	    }
                   3619: 	    textbox.value = "";
                   3620: 
                   3621: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3622: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3623: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3624: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3625: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3626: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3627: 		if ((saveval != "correct") || override) {
1.42      ng       3628: 		    scorename.value = "";
1.125     ng       3629: 		    if (selval[1].selected) {
                   3630: 			selname[1].selected = true;
                   3631: 		    } else {
                   3632: 			selname[2].selected = true;
                   3633: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3634: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3635: 		    }
1.42      ng       3636: 		}
                   3637: 	    }
1.43      ng       3638: 	} else {
                   3639: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3640: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3641: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3642: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3643: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3644: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3645: 		if ((saveval != "correct") || override) {
1.125     ng       3646: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3647: 		    selname[0].selected = true;
                   3648: 		}
                   3649: 	    }
                   3650: 	}	    
1.42      ng       3651:     }
                   3652: 
                   3653:     function changeSelect(partid,user) {
1.125     ng       3654: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3655: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3656: 	var point  = textbox.value;
1.125     ng       3657: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3658: 
1.109     matthew  3659: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3660: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3661: 	    textbox.value = "";
                   3662: 	    return;
                   3663: 	}
1.109     matthew  3664: 	if (parseFloat(point) > parseFloat(weight)) {
                   3665: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3666: 			       ") greater than the weight of the part. Accept?");
                   3667: 	    if (resp == false) {
                   3668: 		textbox.value = "";
                   3669: 		return;
                   3670: 	    }
                   3671: 	}
1.42      ng       3672: 	selval[0].selected = true;
                   3673:     }
                   3674: 
                   3675:     function changeOneScore(partid,user) {
1.125     ng       3676: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3677: 	if (selval[1].selected || selval[2].selected) {
                   3678: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3679: 	    if (selval[2].selected) {
                   3680: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3681: 	    }
1.269     raeburn  3682:         }
1.42      ng       3683:     }
                   3684: 
                   3685:     function resetEntry(numpart) {
                   3686: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3687: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3688: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3689: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3690: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3691: 	    for (var i=0; i<radioButton.length; i++) {
                   3692: 		radioButton[i].checked=false;
                   3693: 
                   3694: 	    }
                   3695: 	    textbox.value = "";
                   3696: 	    selval[0].selected = true;
                   3697: 
                   3698: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3699: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3700: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3701: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3702: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3703: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3704: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3705: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3706: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3707: 		if (saveselval == "excused") {
1.43      ng       3708: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3709: 		} else {
1.43      ng       3710: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3711: 		}
                   3712: 	    }
1.41      ng       3713: 	}
1.42      ng       3714:     }
                   3715: 
1.41      ng       3716: </script>
                   3717: VIEWJAVASCRIPT
1.42      ng       3718: }
                   3719: 
1.44      ng       3720: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3721: sub viewgrades {
                   3722:     my ($request) = shift;
                   3723:     &viewgrades_js($request);
1.41      ng       3724: 
1.324     albertel 3725:     my ($symb) = &get_symb($request);
1.168     albertel 3726:     #need to make sure we have the correct data for later EXT calls, 
                   3727:     #thus invalidate the cache
                   3728:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3729:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3730:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3731:     &Apache::lonnet::clear_EXT_cache_status();
                   3732: 
1.398     albertel 3733:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.596.2.12.2.  9(raebur 3734:3):     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3735: 
                   3736:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3737:     $result.=&jscriptNform($symb);
1.41      ng       3738: 
1.44      ng       3739:     #beginning of class grading form
1.442     banghart 3740:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3741:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3742: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3743: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3744: 	&build_section_inputs().
1.257     albertel 3745: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3746: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3747: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3748: 
1.560     raeburn  3749:     my ($common_header,$specific_header);
1.257     albertel 3750:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3751: 	$common_header = &mt('Assign Common Grade to Class');
                   3752:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3753:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3754:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3755: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3756:     } else {
1.560     raeburn  3757:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3758:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3759: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3760:     }
1.560     raeburn  3761:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3762:     #radio buttons/text box for assigning points for a section or class.
                   3763:     #handles different parts of a problem
1.582     raeburn  3764:     my $res_error;
                   3765:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3766:     if ($res_error) {
                   3767:         return &navmap_errormsg();
                   3768:     }
1.42      ng       3769:     my %weight = ();
                   3770:     my $ctsparts = 0;
1.45      ng       3771:     my %seen = ();
1.375     albertel 3772:     my @part_response_id = &flatten_responseType($responseType);
                   3773:     foreach my $part_response_id (@part_response_id) {
                   3774:     	my ($partid,$respid) = @{ $part_response_id };
                   3775: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3776: 	next if $seen{$partid};
                   3777: 	$seen{$partid}++;
1.375     albertel 3778: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3779: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3780: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3781: 
1.324     albertel 3782: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3783: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3784: 	my $ctr = 0;
1.42      ng       3785: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3786: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3787: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3788: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3789: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3790: 	    $ctr++;
                   3791: 	}
1.485     albertel 3792: 	$radio.='</tr></table>';
                   3793: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3794: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3795: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3796: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 3797:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3798:3):                 '<select name="SELVAL_'.$partid.'" '.
                   3799:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3800: 		$weight{$partid}.')"> '.
1.401     albertel 3801: 	    '<option selected="selected"> </option>'.
1.485     albertel 3802: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3803: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3804: 	    '</select></td>'.
                   3805:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3806: 	$line.='<input type="hidden" name="partid_'.
                   3807: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3808: 	$line.='<input type="hidden" name="weight_'.
                   3809: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3810: 
                   3811: 	$result.=
                   3812: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3813: 	    '<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 3814: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3815: 	$ctsparts++;
1.41      ng       3816:     }
1.474     albertel 3817:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3818: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3819:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3820: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3821: 
1.44      ng       3822:     #table listing all the students in a section/class
                   3823:     #header of table
1.560     raeburn  3824:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3825:               &Apache::loncommon::start_data_table().
                   3826: 	      &Apache::loncommon::start_data_table_header_row().
                   3827: 	      '<th>'.&mt('No.').'</th>'.
                   3828: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3829:     my $partserror;
                   3830:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3831:     if ($partserror) {
                   3832:         return &navmap_errormsg();
                   3833:     }
1.324     albertel 3834:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3835:     my @partids = ();
1.41      ng       3836:     foreach my $part (@parts) {
                   3837: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3838:         my $narrowtext = &mt('Tries');
                   3839: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3840: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3841: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3842:         push(@partids,$partid);
1.324     albertel 3843: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3844: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3845: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 3846:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   3847:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3848: 	    next;
1.485     albertel 3849: 	    
1.207     albertel 3850: 	} else {
1.485     albertel 3851: 	    if ($display =~ /Problem Status/) {
                   3852: 		my $grade_status_mt = &mt('Grade Status');
                   3853: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3854: 	    }
                   3855: 	    my $part_mt = &mt('Part:');
                   3856: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3857: 	}
1.485     albertel 3858: 
1.474     albertel 3859: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3860:     }
1.474     albertel 3861:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3862: 
1.270     albertel 3863:     my %last_resets = 
                   3864: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3865: 
1.41      ng       3866:     #get info for each student
1.44      ng       3867:     #list all the students - with points and grade status
1.257     albertel 3868:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3869:     my $ctr = 0;
1.294     albertel 3870:     foreach (sort 
                   3871: 	     {
                   3872: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3873: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3874: 		 }
                   3875: 		 return $a cmp $b;
                   3876: 	     } (keys(%$fullname))) {
1.126     ng       3877: 	$ctr++;
1.324     albertel 3878: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3879: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3880:     }
1.474     albertel 3881:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3882:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3883:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3884: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3885:     if (scalar(%$fullname) eq 0) {
                   3886: 	my $colspan=3+scalar(@parts);
1.433     banghart 3887: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3888:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3889: 	$result='<span class="LC_warning">'.
1.485     albertel 3890: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3891: 	        $section_display, $stu_status).
1.433     banghart 3892: 	    '</span>';
1.96      albertel 3893:     }
1.324     albertel 3894:     $result.=&show_grading_menu_form($symb);
1.41      ng       3895:     return $result;
                   3896: }
                   3897: 
1.44      ng       3898: #--- call by previous routine to display each student
1.41      ng       3899: sub viewstudentgrade {
1.324     albertel 3900:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3901:     my ($uname,$udom) = split(/:/,$student);
                   3902:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3903:     my %aggregates = (); 
1.474     albertel 3904:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3905: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3906: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3907: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3908: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3909: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3910:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3911:     foreach my $apart (@$parts) {
                   3912: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3913: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3914:         $result.='<td align="center">';
1.269     raeburn  3915:         my ($aggtries,$totaltries);
                   3916:         unless (exists($aggregates{$part})) {
1.270     albertel 3917: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3918: 
                   3919: 	    $aggtries = $totaltries;
1.269     raeburn  3920:             if ($$last_resets{$part}) {  
1.270     albertel 3921:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3922: 					   $part);
                   3923:             }
1.269     raeburn  3924:             $result.='<input type="hidden" name="'.
                   3925:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3926:             $result.='<input type="hidden" name="'.
                   3927:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3928:             $aggregates{$part} = 1;
                   3929:         }
1.41      ng       3930: 	if ($type eq 'awarded') {
1.320     albertel 3931: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3932: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3933: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3934: 	    $result.='<input type="text" name="'.
1.89      albertel 3935: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3936:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3937: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3938: 	} elsif ($type eq 'solved') {
                   3939: 	    my ($status,$foo)=split(/_/,$score,2);
                   3940: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3941: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3942: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3943: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3944: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3945:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3946: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3947: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3948: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3949: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3950: 	} else {
                   3951: 	    $result.='<input type="hidden" name="'.
                   3952: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3953: 		    "\n";
1.233     albertel 3954: 	    $result.='<input type="text" name="'.
1.122     ng       3955: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3956: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3957: 	}
                   3958:     }
1.474     albertel 3959:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3960:     return $result;
1.38      ng       3961: }
                   3962: 
1.44      ng       3963: #--- change scores for all the students in a section/class
                   3964: #    record does not get update if unchanged
1.38      ng       3965: sub editgrades {
1.41      ng       3966:     my ($request) = @_;
                   3967: 
1.596.2.12.2.  (raeburn 3968:):     my ($symb)=&get_symb($request);
1.433     banghart 3969:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3970:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 3971:3):     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
                   3972:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       3973: 
1.477     albertel 3974:     my $result= &Apache::loncommon::start_data_table().
                   3975: 	&Apache::loncommon::start_data_table_header_row().
                   3976: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3977: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3978:     my %scoreptr = (
                   3979: 		    'correct'  =>'correct_by_override',
                   3980: 		    'incorrect'=>'incorrect_by_override',
                   3981: 		    'excused'  =>'excused',
                   3982: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3983:                     'credited' =>'credit_attempted',
1.43      ng       3984: 		    'nothing'  => '',
                   3985: 		    );
1.257     albertel 3986:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3987: 
1.44      ng       3988:     my (@partid);
                   3989:     my %weight = ();
1.54      albertel 3990:     my %columns = ();
1.44      ng       3991:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3992: 
1.582     raeburn  3993:     my $partserror;
                   3994:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3995:     if ($partserror) {
                   3996:         return &navmap_errormsg();
                   3997:     }
1.54      albertel 3998:     my $header;
1.257     albertel 3999:     while ($ctr < $env{'form.totalparts'}) {
                   4000: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4001: 	push(@partid,$partid);
1.257     albertel 4002: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4003: 	$ctr++;
1.54      albertel 4004:     }
1.324     albertel 4005:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 4006:     foreach my $partid (@partid) {
1.478     albertel 4007: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4008: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4009: 	$columns{$partid}=2;
                   4010: 	foreach my $stores (@parts) {
                   4011: 	    my ($part,$type) = &split_part_type($stores);
                   4012: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4013: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4014: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4015: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4016:             my $narrowtext = &mt('Tries');
                   4017: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4018: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4019: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4020: 	    $columns{$partid}+=2;
                   4021: 	}
                   4022:     }
                   4023:     foreach my $partid (@partid) {
1.324     albertel 4024: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4025: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4026: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4027: 	    '</th>';
1.54      albertel 4028: 
1.44      ng       4029:     }
1.477     albertel 4030:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4031: 	&Apache::loncommon::start_data_table_header_row().
                   4032: 	$header.
                   4033: 	&Apache::loncommon::end_data_table_header_row();
                   4034:     my @noupdate;
1.126     ng       4035:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4036:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 4037: 	my $line;
1.257     albertel 4038: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4039: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4040: 	my %newrecord;
                   4041: 	my $updateflag = 0;
1.281     albertel 4042: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 4043: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 4044: 	if (!&canmodify($usec)) {
1.126     ng       4045: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 4046: 	    push(@noupdate,
1.478     albertel 4047: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   4048: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 4049: 	    next;
                   4050: 	}
1.269     raeburn  4051:         my %aggregate = ();
                   4052:         my $aggregateflag = 0;
1.281     albertel 4053: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4054: 	foreach (@partid) {
1.257     albertel 4055: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4056: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4057: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4058: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4059: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4060: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4061: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4062: 	    my $score;
                   4063: 	    if ($partial eq '') {
1.257     albertel 4064: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4065: 	    } elsif ($partial > 0) {
                   4066: 		$score = 'correct_by_override';
                   4067: 	    } elsif ($partial == 0) {
                   4068: 		$score = 'incorrect_by_override';
                   4069: 	    }
1.257     albertel 4070: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4071: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4072: 
1.292     albertel 4073: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4074: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4075: 	    if ($dropMenu eq 'reset status' &&
                   4076: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4077: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4078: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4079: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4080: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4081: 		$updateflag = 1;
1.269     raeburn  4082:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4083:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4084:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4085:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4086:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4087:                     $aggregateflag = 1;
                   4088:                 }
1.139     albertel 4089: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4090: 		$updateflag = 1;
                   4091: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4092: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4093: 		$rec_update++;
1.125     ng       4094: 	    }
                   4095: 
1.93      albertel 4096: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4097: 		'<td align="center">'.$awarded.
                   4098: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4099: 
1.54      albertel 4100: 
                   4101: 	    my $partid=$_;
                   4102: 	    foreach my $stores (@parts) {
                   4103: 		my ($part,$type) = &split_part_type($stores);
                   4104: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4105: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4106: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4107: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4108: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4109: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4110: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4111: 		    $updateflag=1;
                   4112: 		}
1.93      albertel 4113: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4114: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4115: 	    }
1.44      ng       4116: 	}
1.477     albertel 4117: 	$line.="\n";
1.301     albertel 4118: 
                   4119: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4120: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4121: 
1.44      ng       4122: 	if ($updateflag) {
                   4123: 	    $count++;
1.257     albertel 4124: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4125: 				    $udom,$uname);
1.301     albertel 4126: 
                   4127: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4128: 					      $cnum,$udom,$uname)) {
                   4129: 		# need to figure out if should be in queue.
                   4130: 		my %record =  
                   4131: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4132: 					     $udom,$uname);
                   4133: 		my $all_graded = 1;
                   4134: 		my $none_graded = 1;
                   4135: 		foreach my $part (@parts) {
                   4136: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4137: 			$all_graded = 0;
                   4138: 		    } else {
                   4139: 			$none_graded = 0;
                   4140: 		    }
                   4141: 		}
                   4142: 
                   4143: 		if ($all_graded || $none_graded) {
                   4144: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4145: 							   $symb,$cdom,$cnum,
                   4146: 							   $udom,$uname);
                   4147: 		}
                   4148: 	    }
                   4149: 
1.477     albertel 4150: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4151: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4152: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4153: 	    $updateCtr++;
1.93      albertel 4154: 	} else {
1.477     albertel 4155: 	    push(@noupdate,
                   4156: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4157: 	    $noupdateCtr++;
1.44      ng       4158: 	}
1.269     raeburn  4159:         if ($aggregateflag) {
                   4160:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4161: 				  $cdom,$cnum);
1.269     raeburn  4162:         }
1.93      albertel 4163:     }
1.477     albertel 4164:     if (@noupdate) {
1.126     ng       4165: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4166: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4167: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4168: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4169: 	    &mt('No Changes Occurred For the Students Below').
                   4170: 	    '</td>'.
1.477     albertel 4171: 	    &Apache::loncommon::end_data_table_row();
                   4172: 	foreach my $line (@noupdate) {
                   4173: 	    $result.=
                   4174: 		&Apache::loncommon::start_data_table_row().
                   4175: 		$line.
                   4176: 		&Apache::loncommon::end_data_table_row();
                   4177: 	}
1.44      ng       4178:     }
1.477     albertel 4179:     $result .= &Apache::loncommon::end_data_table().
                   4180: 	&show_grading_menu_form($symb);
1.478     albertel 4181:     my $msg = '<p><b>'.
                   4182: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4183: 	    $rec_update,$count).'</b><br />'.
                   4184: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4185: 	'</b></p>';
1.44      ng       4186:     return $title.$msg.$result;
1.5       albertel 4187: }
1.54      albertel 4188: 
                   4189: sub split_part_type {
                   4190:     my ($partstr) = @_;
                   4191:     my ($temp,@allparts)=split(/_/,$partstr);
                   4192:     my $type=pop(@allparts);
1.439     albertel 4193:     my $part=join('_',@allparts);
1.54      albertel 4194:     return ($part,$type);
                   4195: }
                   4196: 
1.44      ng       4197: #------------- end of section for handling grading by section/class ---------
                   4198: #
                   4199: #----------------------------------------------------------------------------
                   4200: 
1.5       albertel 4201: 
1.44      ng       4202: #----------------------------------------------------------------------------
                   4203: #
                   4204: #-------------------------- Next few routines handles grading by csv upload
                   4205: #
                   4206: #--- Javascript to handle csv upload
1.27      albertel 4207: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4208:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4209:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4210:   return(<<ENDPICK);
                   4211:   function verify(vf) {
                   4212:     var foundsomething=0;
                   4213:     var founduname=0;
1.243     albertel 4214:     var foundID=0;
1.27      albertel 4215:     for (i=0;i<=vf.nfields.value;i++) {
                   4216:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4217:       if (i==0 && tw!=0) { foundID=1; }
                   4218:       if (i==1 && tw!=0) { founduname=1; }
                   4219:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4220:     }
1.246     albertel 4221:     if (founduname==0 && foundID==0) {
                   4222: 	alert('$error1');
                   4223: 	return;
1.27      albertel 4224:     }
                   4225:     if (foundsomething==0) {
1.246     albertel 4226: 	alert('$error2');
                   4227: 	return;
1.27      albertel 4228:     }
                   4229:     vf.submit();
                   4230:   }
                   4231:   function flip(vf,tf) {
                   4232:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4233:     var i;
                   4234:     for (i=0;i<=vf.nfields.value;i++) {
                   4235:       //can not pick the same destination field for both name and domain
                   4236:       if (((i ==0)||(i ==1)) && 
                   4237:           ((tf==0)||(tf==1)) && 
                   4238:           (i!=tf) &&
                   4239:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4240:         eval('vf.f'+i+'.selectedIndex=0;')
                   4241:       }
                   4242:     }
                   4243:   }
                   4244: ENDPICK
                   4245: }
                   4246: 
                   4247: sub csvupload_javascript_forward_associate {
1.573     bisitz   4248:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4249:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4250:   return(<<ENDPICK);
                   4251:   function verify(vf) {
                   4252:     var foundsomething=0;
                   4253:     var founduname=0;
1.243     albertel 4254:     var foundID=0;
1.27      albertel 4255:     for (i=0;i<=vf.nfields.value;i++) {
                   4256:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4257:       if (tw==1) { foundID=1; }
                   4258:       if (tw==2) { founduname=1; }
                   4259:       if (tw>3) { foundsomething=1; }
1.27      albertel 4260:     }
1.246     albertel 4261:     if (founduname==0 && foundID==0) {
                   4262: 	alert('$error1');
                   4263: 	return;
1.27      albertel 4264:     }
                   4265:     if (foundsomething==0) {
1.246     albertel 4266: 	alert('$error2');
                   4267: 	return;
1.27      albertel 4268:     }
                   4269:     vf.submit();
                   4270:   }
                   4271:   function flip(vf,tf) {
                   4272:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4273:     var i;
                   4274:     //can not pick the same destination field twice
                   4275:     for (i=0;i<=vf.nfields.value;i++) {
                   4276:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4277:         eval('vf.f'+i+'.selectedIndex=0;')
                   4278:       }
                   4279:     }
                   4280:   }
                   4281: ENDPICK
                   4282: }
                   4283: 
1.26      albertel 4284: sub csvuploadmap_header {
1.324     albertel 4285:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4286:     my $javascript;
1.257     albertel 4287:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4288: 	$javascript=&csvupload_javascript_reverse_associate();
                   4289:     } else {
                   4290: 	$javascript=&csvupload_javascript_forward_associate();
                   4291:     }
1.45      ng       4292: 
1.324     albertel 4293:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 4294:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4295:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4296:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       4297:     $request->print(<<ENDPICK);
1.26      albertel 4298: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4299: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       4300: $result
1.326     albertel 4301: <hr />
1.26      albertel 4302: <h3>Identify fields</h3>
                   4303: Total number of records found in file: $distotal <hr />
                   4304: Enter as many fields as you can. The system will inform you and bring you back
                   4305: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4306: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4307: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4308: <input type="hidden" name="associate"  value="" />
                   4309: <input type="hidden" name="phase"      value="three" />
                   4310: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4311: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4312: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4313: <input type="hidden" name="upfile_associate" 
1.257     albertel 4314:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4315: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4316: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4317: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4318: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4319: <hr />
                   4320: <script type="text/javascript" language="Javascript">
                   4321: $javascript
                   4322: </script>
                   4323: ENDPICK
1.118     ng       4324:     return '';
1.26      albertel 4325: 
                   4326: }
                   4327: 
                   4328: sub csvupload_fields {
1.582     raeburn  4329:     my ($symb,$errorref) = @_;
                   4330:     my (@parts) = &getpartlist($symb,$errorref);
                   4331:     if (ref($errorref)) {
                   4332:         if ($$errorref) {
                   4333:             return;
                   4334:         }
                   4335:     }
                   4336: 
1.556     weissno  4337:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4338: 		['username','Student Username'],
                   4339: 		['domain','Student Domain']);
1.324     albertel 4340:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4341:     foreach my $part (sort(@parts)) {
                   4342: 	my @datum;
                   4343: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4344: 	my $name=$part;
                   4345: 	if  (!$display) { $display = $name; }
                   4346: 	@datum=($name,$display);
1.244     albertel 4347: 	if ($name=~/^stores_(.*)_awarded/) {
                   4348: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4349: 	}
1.41      ng       4350: 	push(@fields,\@datum);
                   4351:     }
                   4352:     return (@fields);
1.26      albertel 4353: }
                   4354: 
                   4355: sub csvuploadmap_footer {
1.41      ng       4356:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4357:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4358:     $request->print(<<ENDPICK);
1.26      albertel 4359: </table>
                   4360: <input type="hidden" name="nfields" value="$i" />
                   4361: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4362:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4363: </form>
                   4364: ENDPICK
                   4365: }
                   4366: 
1.283     albertel 4367: sub checkforfile_js {
1.539     riegler  4368:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       4369:     my $result =<<CSVFORMJS;
                   4370: <script type="text/javascript" language="javascript">
                   4371:     function checkUpload(formname) {
                   4372: 	if (formname.upfile.value == "") {
1.539     riegler  4373: 	    alert("$alertmsg");
1.86      ng       4374: 	    return false;
                   4375: 	}
                   4376: 	formname.submit();
                   4377:     }
                   4378:     </script>
                   4379: CSVFORMJS
1.283     albertel 4380:     return $result;
                   4381: }
                   4382: 
                   4383: sub upcsvScores_form {
                   4384:     my ($request) = shift;
1.324     albertel 4385:     my ($symb)=&get_symb($request);
1.283     albertel 4386:     if (!$symb) {return '';}
                   4387:     my $result=&checkforfile_js();
1.257     albertel 4388:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4389:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4390:     $result.=$table;
1.326     albertel 4391:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4392:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4393:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4394: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4395:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4396:     my $upload=&mt("Upload Scores");
1.86      ng       4397:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4398:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4399:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4400:     $result.=<<ENDUPFORM;
1.106     albertel 4401: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4402: <input type="hidden" name="symb" value="$symb" />
                   4403: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4404: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4405: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4406: $upfile_select
1.589     bisitz   4407: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4408: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4409: </form>
                   4410: ENDUPFORM
1.370     www      4411:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4412:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4413:     .'</td></tr></table>'."\n";
1.86      ng       4414:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4415:     $result.=&show_grading_menu_form($symb);
1.86      ng       4416:     return $result;
                   4417: }
                   4418: 
                   4419: 
1.26      albertel 4420: sub csvuploadmap {
1.41      ng       4421:     my ($request)= @_;
1.324     albertel 4422:     my ($symb)=&get_symb($request);
1.41      ng       4423:     if (!$symb) {return '';}
1.72      ng       4424: 
1.41      ng       4425:     my $datatoken;
1.257     albertel 4426:     if (!$env{'form.datatoken'}) {
1.41      ng       4427: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4428:     } else {
1.257     albertel 4429: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4430: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4431:     }
1.41      ng       4432:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4433:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4434:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4435:     my ($i,$keyfields);
                   4436:     if (@records) {
1.582     raeburn  4437:         my $fieldserror;
                   4438: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4439:         if ($fieldserror) {
                   4440:             $request->print(&navmap_errormsg());
                   4441:             return;
                   4442:         }
1.257     albertel 4443: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4444: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4445: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4446: 							  \@fields);
                   4447: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4448: 	    chop($keyfields);
                   4449: 	} else {
                   4450: 	    unshift(@fields,['none','']);
                   4451: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4452: 							    \@fields);
1.311     banghart 4453:             foreach my $rec (@records) {
                   4454:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4455:                 if (%temp) {
                   4456:                     $keyfields=join(',',sort(keys(%temp)));
                   4457:                     last;
                   4458:                 }
                   4459:             }
1.41      ng       4460: 	}
                   4461:     }
                   4462:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4463:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4464: 
1.41      ng       4465:     return '';
1.27      albertel 4466: }
                   4467: 
1.246     albertel 4468: sub csvuploadoptions {
1.41      ng       4469:     my ($request)= @_;
1.324     albertel 4470:     my ($symb)=&get_symb($request);
1.257     albertel 4471:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4472:     my $ignore=&mt('Ignore First Line');
                   4473:     $request->print(<<ENDPICK);
                   4474: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4475: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4476: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4477: <!--
1.246     albertel 4478: <p>
                   4479: <label>
                   4480:    <input type="checkbox" name="show_full_results" />
                   4481:    Show a table of all changes
                   4482: </label>
                   4483: </p>
1.302     albertel 4484: -->
1.246     albertel 4485: <p>
                   4486: <label>
                   4487:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4488:    Overwrite any existing score
                   4489: </label>
                   4490: </p>
                   4491: ENDPICK
                   4492:     my %fields=&get_fields();
                   4493:     if (!defined($fields{'domain'})) {
1.257     albertel 4494: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4495: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4496:     }
1.257     albertel 4497:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4498: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4499: 	my $cleankey=$1;
                   4500: 	if ($cleankey eq 'command') { next; }
                   4501: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4502: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4503:     }
                   4504:     # FIXME do a check for any duplicated user ids...
                   4505:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4506:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4507: <hr /></form>'."\n");
1.324     albertel 4508:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4509:     return '';
                   4510: }
                   4511: 
                   4512: sub get_fields {
                   4513:     my %fields;
1.257     albertel 4514:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4515:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4516: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4517: 	    if ($env{'form.f'.$i} ne 'none') {
                   4518: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4519: 	    }
                   4520: 	} else {
1.257     albertel 4521: 	    if ($env{'form.f'.$i} ne 'none') {
                   4522: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4523: 	    }
                   4524: 	}
1.27      albertel 4525:     }
1.246     albertel 4526:     return %fields;
                   4527: }
                   4528: 
                   4529: sub csvuploadassign {
                   4530:     my ($request)= @_;
1.324     albertel 4531:     my ($symb)=&get_symb($request);
1.246     albertel 4532:     if (!$symb) {return '';}
1.345     bowersj2 4533:     my $error_msg = '';
1.246     albertel 4534:     &Apache::loncommon::load_tmp_file($request);
                   4535:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4536:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4537:     my %fields=&get_fields();
1.41      ng       4538:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4539:     my $courseid=$env{'request.course.id'};
1.97      albertel 4540:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4541:     my @notallowed;
1.41      ng       4542:     my @skipped;
1.596.2.4  raeburn  4543:     my @warnings;
1.41      ng       4544:     my $countdone=0;
                   4545:     foreach my $grade (@gradedata) {
                   4546: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4547: 	my $domain;
                   4548: 	if ($entries{$fields{'domain'}}) {
                   4549: 	    $domain=$entries{$fields{'domain'}};
                   4550: 	} else {
1.257     albertel 4551: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4552: 	}
1.243     albertel 4553: 	$domain=~s/\s//g;
1.41      ng       4554: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4555: 	$username=~s/\s//g;
1.243     albertel 4556: 	if (!$username) {
                   4557: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4558: 	    $id=~s/\s//g;
1.243     albertel 4559: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4560: 	    $username=$ids{$id};
                   4561: 	}
1.41      ng       4562: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4563: 	    my $id=$entries{$fields{'ID'}};
                   4564: 	    $id=~s/\s//g;
                   4565: 	    if ($id) {
                   4566: 		push(@skipped,"$id:$domain");
                   4567: 	    } else {
                   4568: 		push(@skipped,"$username:$domain");
                   4569: 	    }
1.41      ng       4570: 	    next;
                   4571: 	}
1.108     albertel 4572: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4573: 	if (!&canmodify($usec)) {
                   4574: 	    push(@notallowed,"$username:$domain");
                   4575: 	    next;
                   4576: 	}
1.244     albertel 4577: 	my %points;
1.41      ng       4578: 	my %grades;
                   4579: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4580: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4581: 		$dest eq 'domain') { next; }
                   4582: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4583: 	    if ($dest=~/stores_(.*)_points/) {
                   4584: 		my $part=$1;
                   4585: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4586: 					      $symb,$domain,$username);
1.345     bowersj2 4587:                 if ($wgt) {
                   4588:                     $entries{$fields{$dest}}=~s/\s//g;
                   4589:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4590:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4591:                                           : 'correct_by_override';
1.596.2.4  raeburn  4592:                     if ($pcr>1) {
                   4593:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4594:                     }
1.345     bowersj2 4595:                     $grades{"resource.$part.awarded"}=$pcr;
                   4596:                     $grades{"resource.$part.solved"}=$award;
                   4597:                     $points{$part}=1;
                   4598:                 } else {
                   4599:                     $error_msg = "<br />" .
                   4600:                         &mt("Some point values were assigned"
                   4601:                             ." for problems with a weight "
                   4602:                             ."of zero. These values were "
                   4603:                             ."ignored.");
                   4604:                 }
1.244     albertel 4605: 	    } else {
                   4606: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4607: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4608: 		my $store_key=$dest;
                   4609: 		$store_key=~s/^stores/resource/;
                   4610: 		$store_key=~s/_/\./g;
                   4611: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4612: 	    }
1.41      ng       4613: 	}
1.508     www      4614: 	if (! %grades) { 
                   4615:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4616:         } else {
                   4617: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4618: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4619: 					   $env{'request.course.id'},
                   4620: 					   $domain,$username);
1.508     www      4621: 	   if ($result eq 'ok') {
                   4622: 	      $request->print('.');
1.596.2.4  raeburn  4623: # Remove from grading queue
                   4624:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4625:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4626:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4627:                                              $domain,$username);
1.508     www      4628: 	   } else {
                   4629: 	      $request->print("<p><span class=\"LC_error\">".
                   4630:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4631:                                   "$username:$domain",$result)."</span></p>");
                   4632: 	   }
                   4633: 	   $request->rflush();
                   4634: 	   $countdone++;
                   4635:         }
1.41      ng       4636:     }
1.570     www      4637:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4638:     if (@warnings) {
                   4639:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4640:         $request->print(join(', ',@warnings));
                   4641:     }
1.41      ng       4642:     if (@skipped) {
1.571     www      4643: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4644:         $request->print(join(', ',@skipped));
1.106     albertel 4645:     }
                   4646:     if (@notallowed) {
1.571     www      4647: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4648: 	$request->print(join(', ',@notallowed));
1.41      ng       4649:     }
1.106     albertel 4650:     $request->print("<br />\n");
1.324     albertel 4651:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4652:     return $error_msg;
1.26      albertel 4653: }
1.44      ng       4654: #------------- end of section for handling csv file upload ---------
                   4655: #
                   4656: #-------------------------------------------------------------------
                   4657: #
1.122     ng       4658: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4659: #
                   4660: #--- Select a page/sequence and a student to grade
1.68      ng       4661: sub pickStudentPage {
                   4662:     my ($request) = shift;
                   4663: 
1.539     riegler  4664:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4665:     $request->print(<<LISTJAVASCRIPT);
                   4666: <script type="text/javascript" language="javascript">
                   4667: 
                   4668: function checkPickOne(formname) {
1.76      ng       4669:     if (radioSelection(formname.student) == null) {
1.539     riegler  4670: 	alert("$alertmsg");
1.68      ng       4671: 	return;
                   4672:     }
1.125     ng       4673:     ptr = pullDownSelection(formname.selectpage);
                   4674:     formname.page.value = formname["page"+ptr].value;
                   4675:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4676:     formname.submit();
                   4677: }
                   4678: 
                   4679: </script>
                   4680: LISTJAVASCRIPT
1.118     ng       4681:     &commonJSfunctions($request);
1.324     albertel 4682:     my ($symb) = &get_symb($request);
1.257     albertel 4683:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4684:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4685:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4686: 
1.398     albertel 4687:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4688: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4689: 
1.80      ng       4690:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4691:     my $map_error;
                   4692:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4693:     if ($map_error) {
                   4694:         $request->print(&navmap_errormsg());
                   4695:         return; 
                   4696:     }
1.137     albertel 4697:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4698: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4699: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4700:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4701:     my $ctr=0;
1.68      ng       4702:     foreach (@$titles) {
                   4703: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4704: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4705: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4706: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4707: 	$ctr++;
1.68      ng       4708:     }
1.485     albertel 4709:     $select.= '</select>';
1.539     riegler  4710:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4711: 
1.70      ng       4712:     $ctr=0;
                   4713:     foreach (@$titles) {
                   4714: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4715: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4716: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4717: 	$ctr++;
                   4718:     }
1.72      ng       4719:     $result.='<input type="hidden" name="page" />'."\n".
                   4720: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4721: 
1.485     albertel 4722:     my $options =
                   4723: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4724: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4725:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4726: 
                   4727:     $options =
                   4728: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4729: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4730: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4731:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4732:     
                   4733:     $result.=&build_section_inputs();
1.442     banghart 4734:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4735:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4736: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4737: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4738: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4739: 
1.539     riegler  4740:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4741: 
1.80      ng       4742:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4743:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4744: 
1.68      ng       4745:     $request->print($result);
                   4746: 
1.485     albertel 4747:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4748: 	&Apache::loncommon::start_data_table().
                   4749: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4750: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4751: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4752: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4753: 	'<th>'.&nameUserString('header').'</th>'.
                   4754: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4755:  
1.76      ng       4756:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4757:     my $ptr = 1;
1.294     albertel 4758:     foreach my $student (sort 
                   4759: 			 {
                   4760: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4761: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4762: 			     }
                   4763: 			     return $a cmp $b;
                   4764: 			 } (keys(%$fullname))) {
1.68      ng       4765: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4766: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4767:                                   : '</td>');
1.126     ng       4768: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4769: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4770: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4771: 	$studentTable.=
                   4772: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4773:                          : '');
1.68      ng       4774: 	$ptr++;
                   4775:     }
1.484     albertel 4776:     if ($ptr%2 == 0) {
                   4777: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4778: 	    &Apache::loncommon::end_data_table_row();
                   4779:     }
                   4780:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4781:     $studentTable.='<input type="button" '.
1.589     bisitz   4782:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4783: 
1.324     albertel 4784:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4785:     $request->print($studentTable);
                   4786: 
                   4787:     return '';
                   4788: }
                   4789: 
                   4790: sub getSymbMap {
1.582     raeburn  4791:     my ($map_error) = @_;
1.132     bowersj2 4792:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4793:     unless (ref($navmap)) {
                   4794:         if (ref($map_error)) {
                   4795:             $$map_error = 'navmap';
                   4796:         }
                   4797:         return;
                   4798:     }
1.68      ng       4799:     my %symbx = ();
                   4800:     my @titles = ();
1.117     bowersj2 4801:     my $minder = 0;
                   4802: 
                   4803:     # Gather every sequence that has problems.
1.240     albertel 4804:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4805: 					       1,0,1);
1.117     bowersj2 4806:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4807: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4808: 	    my $title = $minder.'.'.
                   4809: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4810: 	    push(@titles, $title); # minder in case two titles are identical
                   4811: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4812: 	    $minder++;
1.241     albertel 4813: 	}
1.68      ng       4814:     }
                   4815:     return \@titles,\%symbx;
                   4816: }
                   4817: 
1.72      ng       4818: #
                   4819: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4820: sub displayPage {
                   4821:     my ($request) = shift;
                   4822: 
1.324     albertel 4823:     my ($symb) = &get_symb($request);
1.257     albertel 4824:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4825:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4826:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4827:     my $pageTitle = $env{'form.page'};
1.103     albertel 4828:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4829:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4830:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4831: 
                   4832:     #need to make sure we have the correct data for later EXT calls, 
                   4833:     #thus invalidate the cache
                   4834:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4835:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4836:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4837:     &Apache::lonnet::clear_EXT_cache_status();
                   4838: 
1.103     albertel 4839:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 4840:4): 	$request->print('<span class="LC_warning">'.
                   4841:4):                         &mt('Unable to view requested student. ([_1])',
                   4842:4):                             $env{'form.student'}).
                   4843:4):                         '</span>');
                   4844:4):         $request->print(&show_grading_menu_form($symb));
                   4845:4):         return;
1.103     albertel 4846:     }
1.398     albertel 4847:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4848:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4849: 	'</h3>'."\n";
1.500     albertel 4850:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4851:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4852: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4853:     } else {
                   4854: 	delete($env{'form.CODE'});
                   4855:     }
1.71      ng       4856:     &sub_page_js($request);
                   4857:     $request->print($result);
                   4858: 
1.132     bowersj2 4859:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4860:     unless (ref($navmap)) {
                   4861:         $request->print(&navmap_errormsg());
                   4862:         $request->print(&show_grading_menu_form($symb));
                   4863:         return;
                   4864:     }
1.257     albertel 4865:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4866:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4867:     if (!$map) {
1.485     albertel 4868: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4869: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4870: 	return; 
                   4871:     }
1.68      ng       4872:     my $iterator = $navmap->getIterator($map->map_start(),
                   4873: 					$map->map_finish());
                   4874: 
1.71      ng       4875:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4876: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4877: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4878: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4879: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4880: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4881: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4882: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4883: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4884: 
1.382     albertel 4885:     if (defined($env{'form.CODE'})) {
                   4886: 	$studentTable.=
                   4887: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4888:     }
1.381     albertel 4889:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4890: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4891: 
1.594     bisitz   4892:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4893:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4894:         '</span>'."\n".
1.484     albertel 4895: 	&Apache::loncommon::start_data_table().
                   4896: 	&Apache::loncommon::start_data_table_header_row().
                   4897: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4898: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4899: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4900: 
1.329     albertel 4901:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4902:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4903:     $iterator->next(); # skip the first BEGIN_MAP
                   4904:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4905:     while ($depth > 0) {
1.68      ng       4906:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4907:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4908: 
1.385     albertel 4909:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4910: 	    my $parts = $curRes->parts();
1.68      ng       4911:             my $title = $curRes->compTitle();
1.71      ng       4912: 	    my $symbx = $curRes->symb();
1.484     albertel 4913: 	    $studentTable.=
                   4914: 		&Apache::loncommon::start_data_table_row().
                   4915: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4916: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 4917:2): 		                        : '<br />('.&mt('[_1]parts',
                   4918:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4919: 		 ).
                   4920: 		 '</td>';
1.71      ng       4921: 	    $studentTable.='<td valign="top">';
1.382     albertel 4922: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4923: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4924: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4925: 					     undef,'both',\%form);
1.71      ng       4926: 	    } else {
1.382     albertel 4927: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4928: 		$companswer =~ s|<form(.*?)>||g;
                   4929: 		$companswer =~ s|</form>||g;
1.71      ng       4930: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4931: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4932: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4933: #		}
1.116     ng       4934: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4935: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4936: 	    }
                   4937: 
1.257     albertel 4938: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4939: 
1.257     albertel 4940: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4941: 		if ($record{'version'} eq '') {
1.485     albertel 4942: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4943: 		} else {
1.116     ng       4944: 		    my %responseType = ();
                   4945: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4946: 			my @responseIds =$curRes->responseIds($partid);
                   4947: 			my @responseType =$curRes->responseType($partid);
                   4948: 			my %responseIds;
                   4949: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4950: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4951: 			}
                   4952: 			$responseType{$partid} = \%responseIds;
1.116     ng       4953: 		    }
1.148     albertel 4954: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4955: 
1.71      ng       4956: 		}
1.257     albertel 4957: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4958: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 4959:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       4960: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4961: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 4962:5): 									'','.submission',undef,
                   4963:5):                                                                         $usec,$identifier);
1.71      ng       4964:  
                   4965: 	    }
1.103     albertel 4966: 	    if (&canmodify($usec)) {
1.585     bisitz   4967:             $studentTable.=&gradeBox_start();
1.103     albertel 4968: 		foreach my $partid (@{$parts}) {
                   4969: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4970: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4971: 		    $question++;
                   4972: 		}
1.585     bisitz   4973:             $studentTable.=&gradeBox_end();
1.196     albertel 4974: 		$prob++;
1.71      ng       4975: 	    }
                   4976: 	    $studentTable.='</td></tr>';
1.68      ng       4977: 
1.103     albertel 4978: 	}
1.68      ng       4979:         $curRes = $iterator->next();
                   4980:     }
                   4981: 
1.589     bisitz   4982:     $studentTable.=
                   4983:         '</table>'."\n".
                   4984:         '<input type="button" value="'.&mt('Save').'" '.
                   4985:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4986:         '</form>'."\n";
1.324     albertel 4987:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4988:     $request->print($studentTable);
                   4989: 
                   4990:     return '';
1.119     ng       4991: }
                   4992: 
                   4993: sub displaySubByDates {
1.148     albertel 4994:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4995:     my $isCODE=0;
1.335     albertel 4996:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4997:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4998:     my $studentTable=&Apache::loncommon::start_data_table().
                   4999: 	&Apache::loncommon::start_data_table_header_row().
                   5000: 	'<th>'.&mt('Date/Time').'</th>'.
                   5001: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5002:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5003: 	'<th>'.&mt('Submission').'</th>'.
                   5004: 	'<th>'.&mt('Status').'</th>'.
                   5005: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5006:     my ($version);
                   5007:     my %mark;
1.148     albertel 5008:     my %orders;
1.119     ng       5009:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5010:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5011: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5012:     }
1.335     albertel 5013: 
                   5014:     my $interaction;
1.525     raeburn  5015:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5016:5):     my (%lastrndseed,%lasttype);
1.119     ng       5017:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5018: 	my $timestamp = 
                   5019: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5020: 	if (exists($$record{$version.':resource.0.version'})) {
                   5021: 	    $interaction = $$record{$version.':resource.0.version'};
                   5022: 	}
1.596.2.12.2.  (raeburn 5023:):         if ($isTask && $env{'form.previousversion'}) {
                   5024:):             next unless ($interaction == $env{'form.previousversion'});
                   5025:):         }
1.335     albertel 5026: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5027: 		             : "$version:resource");
1.467     albertel 5028: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5029: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5030: 	if ($isCODE) {
                   5031: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5032: 	}
1.596.2.12.2.  (raeburn 5033:):         if ($isTask) {
                   5034:):             $studentTable.='<td>'.$interaction.'</td>';
                   5035:):         }
1.119     ng       5036: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5037: 	my @displaySub = ();
                   5038: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5039:             my ($hidden,$type);
                   5040:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5041:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5042:                 $hidden = 1;
                   5043:             }
1.335     albertel 5044: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   5045: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5046: 	    
1.122     ng       5047: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5048: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5049: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5050: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5051: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5052:                     
1.335     albertel 5053: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5054: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5055:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5056:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5057:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5058:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5059:                                    .'</span>'
                   5060:                                    .' <b>';
1.596     raeburn  5061:                     if ($hidden) {
                   5062:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5063:                     } else {
1.596.2.2  raeburn  5064:                         my ($trial,$rndseed,$newvariation);
                   5065:                         if ($type eq 'randomizetry') {
                   5066:                             $trial = $$record{"$where.$partid.tries"};
                   5067:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5068:                         }
1.596     raeburn  5069: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5070: 			    $displaySub[0].=&mt('Trial not counted');
                   5071: 		        } else {
                   5072: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5073: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5074:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5075:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5076:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5077:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5078:                                 }
                   5079:                             }
1.596.2.12.2.  4(raebur 5080:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5081:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5082: 		        }
                   5083: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5084:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5085: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5086: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5087: 			    $orders{$partid}->{$responseId}=
                   5088: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5089:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5090: 		        }
1.596.2.2  raeburn  5091: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5092: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5093: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5094:                     }
1.147     albertel 5095: 		}
                   5096: 	    }
1.335     albertel 5097: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5098: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5099: 				    $$record{"$where.$partid.checkedin"},
                   5100: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5101: 					'<br />';
1.335     albertel 5102: 	    }
                   5103: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5104: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5105: 		    lc($$record{"$where.$partid.award"}).' '.
                   5106: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5107: 		    '<br />';
                   5108: 	    }
1.335     albertel 5109: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5110: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5111: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5112: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5113: 		$displaySub[2].=
                   5114: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5115: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5116: 	    }
                   5117: 	}
                   5118: 	# needed because old essay regrader has not parts info
                   5119: 	if (exists $$record{"$version:resource.regrader"}) {
                   5120: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5121: 	}
                   5122: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5123: 	if ($displaySub[2]) {
1.467     albertel 5124: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5125: 	}
1.467     albertel 5126: 	$studentTable.='&nbsp;</td>'.
                   5127: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5128:     }
1.467     albertel 5129:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5130:     return $studentTable;
1.71      ng       5131: }
                   5132: 
                   5133: sub updateGradeByPage {
                   5134:     my ($request) = shift;
                   5135: 
1.257     albertel 5136:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5137:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5138:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5139:     my $pageTitle = $env{'form.page'};
1.103     albertel 5140:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5141:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5142:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5143:     if (!&canmodify($usec)) {
1.526     raeburn  5144: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 5145: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 5146: 	return;
                   5147:     }
1.398     albertel 5148:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5149:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5150: 	'</h3>'."\n";
1.70      ng       5151: 
1.68      ng       5152:     $request->print($result);
                   5153: 
1.582     raeburn  5154: 
1.132     bowersj2 5155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5156:     unless (ref($navmap)) {
                   5157:         $request->print(&navmap_errormsg());
                   5158:         return;
                   5159:     }
1.257     albertel 5160:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5161:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5162:     if (!$map) {
1.527     raeburn  5163: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 5164: 	my ($symb)=&get_symb($request);
                   5165: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5166: 	return; 
                   5167:     }
1.71      ng       5168:     my $iterator = $navmap->getIterator($map->map_start(),
                   5169: 					$map->map_finish());
1.70      ng       5170: 
1.484     albertel 5171:     my $studentTable=
                   5172: 	&Apache::loncommon::start_data_table().
                   5173: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5174: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5175: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5176: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5177: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5178: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5179: 
                   5180:     $iterator->next(); # skip the first BEGIN_MAP
                   5181:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5182:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5183:     while ($depth > 0) {
1.71      ng       5184:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5185:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5186: 
1.385     albertel 5187:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5188: 	    my $parts = $curRes->parts();
1.71      ng       5189:             my $title = $curRes->compTitle();
                   5190: 	    my $symbx = $curRes->symb();
1.484     albertel 5191: 	    $studentTable.=
                   5192: 		&Apache::loncommon::start_data_table_row().
                   5193: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5194: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5195:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5196: 		.')').'</td>';
1.71      ng       5197: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5198: 
                   5199: 	    my %newrecord=();
                   5200: 	    my @displayPts=();
1.269     raeburn  5201:             my %aggregate = ();
                   5202:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5203:5):             if ($env{'form.HIDE'.$prob}) {
                   5204:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5205:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5206:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5207:5):                 $hideflag += $numchgs;
                   5208:5):             }
1.71      ng       5209: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5210: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5211: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5212: 
1.257     albertel 5213: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5214: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5215: 		my $partial = $newpts/$wgt;
                   5216: 		my $score;
                   5217: 		if ($partial > 0) {
                   5218: 		    $score = 'correct_by_override';
1.125     ng       5219: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5220: 		    $score = 'incorrect_by_override';
                   5221: 		}
1.257     albertel 5222: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5223: 		if ($dropMenu eq 'excused') {
1.71      ng       5224: 		    $partial = '';
                   5225: 		    $score = 'excused';
1.125     ng       5226: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5227: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5228: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5229: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5230: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5231: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5232: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5233: 		    $changeflag++;
                   5234: 		    $newpts = '';
1.269     raeburn  5235:                     
                   5236:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5237:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5238:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5239:                     if ($aggtries > 0) {
                   5240:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5241:                         $aggregateflag = 1;
                   5242:                     }
1.71      ng       5243: 		}
1.324     albertel 5244: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5245: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5246: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5247: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5248: 		    '&nbsp;<br />';
1.526     raeburn  5249: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5250: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5251: 		    '&nbsp;<br />';
1.71      ng       5252: 		$question++;
1.380     albertel 5253: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5254: 
1.71      ng       5255: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5256: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5257: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5258: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5259: 
                   5260: 		$changeflag++;
                   5261: 	    }
                   5262: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5263: 		my %record = 
                   5264: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5265: 					     $udom,$uname);
                   5266: 
                   5267: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5268: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5269: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5270: 		    $newrecord{'resource.CODE'} = '';
                   5271: 		}
1.257     albertel 5272: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5273: 					$udom,$uname);
1.382     albertel 5274: 		%record = &Apache::lonnet::restore($symbx,
                   5275: 						   $env{'request.course.id'},
                   5276: 						   $udom,$uname);
1.380     albertel 5277: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5278: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5279: 	    }
1.380     albertel 5280: 	    
1.269     raeburn  5281:             if ($aggregateflag) {
                   5282:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5283:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5284:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5285:             }
1.125     ng       5286: 
1.71      ng       5287: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5288: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5289: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5290: 
1.196     albertel 5291: 	    $prob++;
1.68      ng       5292: 	}
1.71      ng       5293:         $curRes = $iterator->next();
1.68      ng       5294:     }
1.98      albertel 5295: 
1.484     albertel 5296:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 5297:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  5298:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5299: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5300:5): 		  $changeflag).'<br />');
                   5301:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5302:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5303:5):                      $hideflag).'<br />');
                   5304:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5305: 
1.70      ng       5306:     return '';
                   5307: }
                   5308: 
1.72      ng       5309: #-------- end of section for handling grading by page/sequence ---------
                   5310: #
                   5311: #-------------------------------------------------------------------
                   5312: 
1.581     www      5313: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5314: #
                   5315: #------ start of section for handling grading by page/sequence ---------
                   5316: 
1.423     albertel 5317: =pod
                   5318: 
                   5319: =head1 Bubble sheet grading routines
                   5320: 
1.424     albertel 5321:   For this documentation:
                   5322: 
                   5323:    'scanline' refers to the full line of characters
                   5324:    from the file that we are parsing that represents one entire sheet
                   5325: 
                   5326:    'bubble line' refers to the data
1.596.2.6  raeburn  5327:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5328: 
                   5329: 
1.596.2.6  raeburn  5330: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5331: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5332: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5333: one of the predefined configurations for what each scanline looks
                   5334: like.
                   5335: 
                   5336: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5337: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5338: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5339:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5340: invalid student/employee ID
1.424     albertel 5341: 
                   5342: If the CODE option is used that determines the randomization of the
1.556     weissno  5343: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5344: username:domain.
                   5345: 
                   5346: During the validation phase the instructor can choose to skip scanlines. 
                   5347: 
1.596.2.6  raeburn  5348: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5349: 
                   5350:   scantron_original_filename (unmodified original file)
                   5351:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5352:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5353: 
                   5354: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5355: correction information that isn't representable in the bubblesheet
1.424     albertel 5356: file (see &scantron_getfile() for more information)
                   5357: 
                   5358: After all scanlines are either valid, marked as valid or skipped, then
                   5359: foreach line foreach problem in the picked sequence, an ssi request is
                   5360: made that simulates a user submitting their selected letter(s) against
                   5361: the homework problem.
1.423     albertel 5362: 
                   5363: =over 4
                   5364: 
                   5365: 
                   5366: 
                   5367: =item defaultFormData
                   5368: 
                   5369:   Returns html hidden inputs used to hold context/default values.
                   5370: 
                   5371:  Arguments:
                   5372:   $symb - $symb of the current resource 
                   5373: 
                   5374: =cut
1.422     foxr     5375: 
1.81      albertel 5376: sub defaultFormData {
1.324     albertel 5377:     my ($symb)=@_;
1.447     foxr     5378:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5379:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5380:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5381: }
                   5382: 
1.447     foxr     5383: 
1.423     albertel 5384: =pod 
                   5385: 
                   5386: =item getSequenceDropDown
                   5387: 
                   5388:    Return html dropdown of possible sequences to grade
                   5389:  
                   5390:  Arguments:
1.582     raeburn  5391:    $symb - $symb of the current resource
                   5392:    $map_error - ref to scalar which will container error if
                   5393:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5394: 
                   5395: =cut
1.422     foxr     5396: 
1.75      albertel 5397: sub getSequenceDropDown {
1.582     raeburn  5398:     my ($symb,$map_error)=@_;
1.75      albertel 5399:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5400:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5401:     if (ref($map_error)) {
                   5402:         return if ($$map_error);
                   5403:     }
1.137     albertel 5404:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5405:     my $ctr=0;
                   5406:     foreach (@$titles) {
                   5407: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5408: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5409: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5410: 	    '>'.$showtitle.'</option>'."\n";
                   5411: 	$ctr++;
                   5412:     }
                   5413:     $result.= '</select>';
                   5414:     return $result;
                   5415: }
                   5416: 
1.495     albertel 5417: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5418:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5419: 
                   5420: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5421: 
1.509     raeburn  5422: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5423:                                    # matchresponse or rankresponse, where 
                   5424:                                    # an individual response can have multiple 
                   5425:                                    # lines
1.503     raeburn  5426: 
                   5427: my %responsetype_per_response;     # responsetype for each response
                   5428: 
1.596.2.12.2.  6(raebur 5429:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5430:3):                                    # numbered response. Needed when randomorder
                   5431:3):                                    # or randompick are in use. Key is ID, value 
                   5432:3):                                    # is response number.
                   5433:3): 
1.495     albertel 5434: # Save and restore the bubble lines array to the form env.
                   5435: 
                   5436: 
                   5437: sub save_bubble_lines {
                   5438:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5439: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5440: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5441: 	    $first_bubble_line{$line};
1.503     raeburn  5442:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5443:             $subdivided_bubble_lines{$line};
                   5444:         $env{"form.scantron.responsetype.$line"} =
                   5445:             $responsetype_per_response{$line};
1.495     albertel 5446:     }
1.596.2.12.2.  6(raebur 5447:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5448:3):         my $line = $masterseq_id_responsenum{$resid};
                   5449:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5450:3):     }
1.495     albertel 5451: }
                   5452: 
                   5453: 
                   5454: sub restore_bubble_lines {
                   5455:     my $line = 0;
                   5456:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5457:3):     %masterseq_id_responsenum = ();
1.495     albertel 5458:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5459: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5460: 	$bubble_lines_per_response{$line} = $value;
                   5461: 	$first_bubble_line{$line}  =
                   5462: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5463:         $subdivided_bubble_lines{$line} =
                   5464:             $env{"form.scantron.sub_bubblelines.$line"};
                   5465:         $responsetype_per_response{$line} =
                   5466:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5467:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5468:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5469: 	$line++;
                   5470:     }
                   5471: }
                   5472: 
1.423     albertel 5473: =pod 
                   5474: 
                   5475: =item scantron_filenames
                   5476: 
                   5477:    Returns a list of the scantron files in the current course 
                   5478: 
                   5479: =cut
1.422     foxr     5480: 
1.202     albertel 5481: sub scantron_filenames {
1.257     albertel 5482:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5483:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5484:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5485:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5486:):                                                         $cname,$getpropath);
1.202     albertel 5487:     my @possiblenames;
1.596.2.12.2.  (raeburn 5488:):     if (ref($dirlist) eq 'ARRAY') {
                   5489:):         foreach my $filename (sort(@{$dirlist})) {
                   5490:): 	    ($filename)=split(/&/,$filename);
                   5491:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5492:): 	    $filename=~s/^scantron_orig_//;
                   5493:): 	    push(@possiblenames,$filename);
                   5494:):         }
1.202     albertel 5495:     }
                   5496:     return @possiblenames;
                   5497: }
                   5498: 
1.423     albertel 5499: =pod 
                   5500: 
                   5501: =item scantron_uploads
                   5502: 
                   5503:    Returns  html drop-down list of scantron files in current course.
                   5504: 
                   5505:  Arguments:
                   5506:    $file2grade - filename to set as selected in the dropdown
                   5507: 
                   5508: =cut
1.422     foxr     5509: 
1.202     albertel 5510: sub scantron_uploads {
1.209     ng       5511:     my ($file2grade) = @_;
1.202     albertel 5512:     my $result=	'<select name="scantron_selectfile">';
                   5513:     $result.="<option></option>";
                   5514:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5515: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5516:     }
                   5517:     $result.="</select>";
                   5518:     return $result;
                   5519: }
                   5520: 
1.423     albertel 5521: =pod 
                   5522: 
                   5523: =item scantron_scantab
                   5524: 
                   5525:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5526:   file.
                   5527: 
                   5528: =cut
1.422     foxr     5529: 
1.82      albertel 5530: sub scantron_scantab {
                   5531:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5532:     $result.='<option></option>'."\n";
1.518     raeburn  5533:     my @lines = &get_scantronformat_file();
                   5534:     if (@lines > 0) {
                   5535:         foreach my $line (@lines) {
                   5536:             next if (($line =~ /^\#/) || ($line eq ''));
                   5537: 	    my ($name,$descrip)=split(/:/,$line);
                   5538: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5539:         }
1.82      albertel 5540:     }
                   5541:     $result.='</select>'."\n";
1.518     raeburn  5542:     return $result;
                   5543: }
                   5544: 
                   5545: =pod
                   5546: 
                   5547: =item get_scantronformat_file
                   5548: 
                   5549:   Returns an array containing lines from the scantron format file for
                   5550:   the domain of the course.
                   5551: 
                   5552:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5553:   lines are from this file.
                   5554: 
                   5555:   Otherwise, if a default.tab has been published in RES space by the 
                   5556:   domainconfig user, lines are from this file.
                   5557: 
                   5558:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5559:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5560: 
1.518     raeburn  5561: =cut
                   5562: 
                   5563: sub get_scantronformat_file {
                   5564:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5565:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5566:     my $gottab = 0;
                   5567:     my @lines;
                   5568:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5569:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5570:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5571:             if ($formatfile ne '-1') {
                   5572:                 @lines = split("\n",$formatfile,-1);
                   5573:                 $gottab = 1;
                   5574:             }
                   5575:         }
                   5576:     }
                   5577:     if (!$gottab) {
                   5578:         my $confname = $cdom.'-domainconfig';
                   5579:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5580:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5581:         if ($formatfile ne '-1') {
                   5582:             @lines = split("\n",$formatfile,-1);
                   5583:             $gottab = 1;
                   5584:         }
                   5585:     }
                   5586:     if (!$gottab) {
1.519     raeburn  5587:         my @domains = &Apache::lonnet::current_machine_domains();
                   5588:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5589:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5590:             @lines = <$fh>;
                   5591:             close($fh);
                   5592:         } else {
                   5593:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5594:             @lines = <$fh>;
                   5595:             close($fh);
                   5596:         }
1.518     raeburn  5597:     }
                   5598:     return @lines;
1.82      albertel 5599: }
                   5600: 
1.423     albertel 5601: =pod 
                   5602: 
                   5603: =item scantron_CODElist
                   5604: 
                   5605:   Returns html drop down of the saved CODE lists from current course,
                   5606:   generated from earlier printings.
                   5607: 
                   5608: =cut
1.422     foxr     5609: 
1.186     albertel 5610: sub scantron_CODElist {
1.257     albertel 5611:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5612:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5613:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5614:     my $namechoice='<option></option>';
1.225     albertel 5615:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5616: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5617: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5618: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5619:     }
                   5620:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5621:     return $namechoice;
                   5622: }
                   5623: 
1.423     albertel 5624: =pod 
                   5625: 
                   5626: =item scantron_CODEunique
                   5627: 
                   5628:   Returns the html for "Each CODE to be used once" radio.
                   5629: 
                   5630: =cut
1.422     foxr     5631: 
1.186     albertel 5632: sub scantron_CODEunique {
1.532     bisitz   5633:     my $result='<span class="LC_nobreak">
1.272     albertel 5634:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5635:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5636:                 </span>
1.532     bisitz   5637:                 <span class="LC_nobreak">
1.272     albertel 5638:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5639:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5640:                 </span>';
1.186     albertel 5641:     return $result;
                   5642: }
1.423     albertel 5643: 
                   5644: =pod 
                   5645: 
                   5646: =item scantron_selectphase
                   5647: 
1.596.2.6  raeburn  5648:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5649:   Allows for - starting a grading run.
1.424     albertel 5650:              - downloading existing scan data (original, corrected
1.423     albertel 5651:                                                 or skipped info)
                   5652: 
                   5653:              - uploading new scan data
                   5654: 
                   5655:  Arguments:
                   5656:   $r          - The Apache request object
                   5657:   $file2grade - name of the file that contain the scanned data to score
                   5658: 
                   5659: =cut
1.186     albertel 5660: 
1.75      albertel 5661: sub scantron_selectphase {
1.209     ng       5662:     my ($r,$file2grade) = @_;
1.324     albertel 5663:     my ($symb)=&get_symb($r);
1.75      albertel 5664:     if (!$symb) {return '';}
1.582     raeburn  5665:     my $map_error;
                   5666:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5667:     if ($map_error) {
                   5668:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5669:         return;
                   5670:     }
1.324     albertel 5671:     my $default_form_data=&defaultFormData($symb);
                   5672:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5673:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5674:     my $format_selector=&scantron_scantab();
1.186     albertel 5675:     my $CODE_selector=&scantron_CODElist();
                   5676:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5677:     my $result;
1.422     foxr     5678: 
1.513     foxr     5679:     $ssi_error = 0;
                   5680: 
1.596.2.4  raeburn  5681:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5682:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5683: 
                   5684:         # Chunk of form to prompt for a scantron file upload.
                   5685: 
                   5686:         $r->print('
                   5687:     <br />
                   5688:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5689:        '.&Apache::loncommon::start_data_table_header_row().'
                   5690:             <th>
                   5691:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5692:             </th>
                   5693:        '.&Apache::loncommon::end_data_table_header_row().'
                   5694:        '.&Apache::loncommon::start_data_table_row().'
                   5695:             <td>
                   5696: ');
                   5697:     my $default_form_data=&defaultFormData(&get_symb($r,1));
                   5698:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5699:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5700:     $r->print('
                   5701:               <script type="text/javascript" language="javascript">
                   5702:     function checkUpload(formname) {
                   5703:         if (formname.upfile.value == "") {
                   5704:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5705:             return false;
                   5706:         }
                   5707:         formname.submit();
                   5708:     }
                   5709:               </script>
                   5710: 
                   5711:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5712:                 '.$default_form_data.'
                   5713:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5714:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5715:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5716:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5717:                 <br />
                   5718:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5719:               </form>
                   5720: ');
                   5721: 
                   5722:         $r->print('
                   5723:             </td>
                   5724:        '.&Apache::loncommon::end_data_table_row().'
                   5725:        '.&Apache::loncommon::end_data_table().'
                   5726: ');
                   5727:     }
                   5728: 
1.422     foxr     5729:     # Chunk of form to prompt for a file to grade and how:
                   5730: 
1.489     albertel 5731:     $result.= '
                   5732:     <br />
                   5733:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5734:     <input type="hidden" name="command" value="scantron_warning" />
                   5735:     '.$default_form_data.'
                   5736:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5737:        '.&Apache::loncommon::start_data_table_header_row().'
                   5738:             <th colspan="2">
1.492     albertel 5739:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5740:             </th>
                   5741:        '.&Apache::loncommon::end_data_table_header_row().'
                   5742:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5743:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_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('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5747:        '.&Apache::loncommon::end_data_table_row().'
                   5748:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5749:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_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('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5753:        '.&Apache::loncommon::end_data_table_row().'
                   5754:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5755:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5756:        '.&Apache::loncommon::end_data_table_row().'
                   5757:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5758: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5759:             <td>
1.492     albertel 5760: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5761:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5762:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5763: 	    </td>
1.489     albertel 5764:        '.&Apache::loncommon::end_data_table_row().'
                   5765:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5766:             <td colspan="2">
1.572     www      5767:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5768:             </td>
1.489     albertel 5769:        '.&Apache::loncommon::end_data_table_row().'
                   5770:     '.&Apache::loncommon::end_data_table().'
                   5771:     </form>
                   5772: ';
1.162     albertel 5773:    
                   5774:     $r->print($result);
                   5775: 
1.422     foxr     5776:     # Chunk of the form that prompts to view a scoring office file,
                   5777:     # corrected file, skipped records in a file.
                   5778: 
1.489     albertel 5779:     $r->print('
                   5780:    <br />
                   5781:    <form action="/adm/grades" name="scantron_download">
                   5782:      '.$default_form_data.'
                   5783:      <input type="hidden" name="command" value="scantron_download" />
                   5784:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5785:        '.&Apache::loncommon::start_data_table_header_row().'
                   5786:               <th>
1.492     albertel 5787:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5788:               </th>
                   5789:        '.&Apache::loncommon::end_data_table_header_row().'
                   5790:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5791:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5792:                 <br />
1.492     albertel 5793:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5794:        '.&Apache::loncommon::end_data_table_row().'
                   5795:      '.&Apache::loncommon::end_data_table().'
                   5796:    </form>
                   5797:    <br />
                   5798: ');
1.162     albertel 5799: 
1.457     banghart 5800:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5801: 
1.596.2.12.2.  8(raebur 5802:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5803:              $default_form_data."\n".
                   5804:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5805:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5806:              '<th colspan="2">
1.572     www      5807:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5808:              '</th>'."\n".
                   5809:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5810:               &Apache::loncommon::start_data_table_row()."\n".
                   5811:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5812:               '<td> '.$sequence_selector.' </td>'.
                   5813:               &Apache::loncommon::end_data_table_row()."\n".
                   5814:               &Apache::loncommon::start_data_table_row()."\n".
                   5815:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5816:               '<td> '.$file_selector.' </td>'."\n".
                   5817:               &Apache::loncommon::end_data_table_row()."\n".
                   5818:               &Apache::loncommon::start_data_table_row()."\n".
                   5819:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5820:               '<td> '.$format_selector.' </td>'."\n".
                   5821:               &Apache::loncommon::end_data_table_row()."\n".
                   5822:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5823:               '<td> '.&mt('Options').' </td>'."\n".
                   5824:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5825:               &Apache::loncommon::end_data_table_row()."\n".
                   5826:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5827:               '<td colspan="2">'."\n".
                   5828:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5829:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5830:               '</td>'."\n".
                   5831:               &Apache::loncommon::end_data_table_row()."\n".
                   5832:               &Apache::loncommon::end_data_table()."\n".
                   5833:               '</form><br />');
1.457     banghart 5834:     $r->print($grading_menu_button);
1.523     raeburn  5835:     return;
1.75      albertel 5836: }
                   5837: 
1.423     albertel 5838: =pod
                   5839: 
                   5840: =item get_scantron_config
                   5841: 
                   5842:    Parse and return the scantron configuration line selected as a
                   5843:    hash of configuration file fields.
                   5844: 
                   5845:  Arguments:
                   5846:     which - the name of the configuration to parse from the file.
                   5847: 
                   5848: 
                   5849:  Returns:
                   5850:             If the named configuration is not in the file, an empty
                   5851:             hash is returned.
                   5852:     a hash with the fields
                   5853:       name         - internal name for the this configuration setup
                   5854:       description  - text to display to operator that describes this config
                   5855:       CODElocation - if 0 or the string 'none'
                   5856:                           - no CODE exists for this config
                   5857:                      if -1 || the string 'letter'
                   5858:                           - a CODE exists for this config and is
                   5859:                             a string of letters
                   5860:                      Unsupported value (but planned for future support)
                   5861:                           if a positive integer
                   5862:                                - The CODE exists as the first n items from
                   5863:                                  the question section of the form
                   5864:                           if the string 'number'
                   5865:                                - The CODE exists for this config and is
                   5866:                                  a string of numbers
                   5867:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5868:                      the CODE starts
                   5869:       CODElength  - length of the CODE
1.573     bisitz   5870:       IDstart     - column where the student/employee ID starts
1.556     weissno  5871:       IDlength    - length of the student/employee ID info
1.423     albertel 5872:       Qstart      - column where the information from the bubbled
                   5873:                     'questions' start
                   5874:       Qlength     - number of columns comprising a single bubble line from
                   5875:                     the sheet. (usually either 1 or 10)
1.424     albertel 5876:       Qon         - either a single character representing the character used
1.423     albertel 5877:                     to signal a bubble was chosen in the positional setup, or
                   5878:                     the string 'letter' if the letter of the chosen bubble is
                   5879:                     in the final, or 'number' if a number representing the
                   5880:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5881:       Qoff        - the character used to represent that a bubble was
                   5882:                     left blank
1.423     albertel 5883:       PaperID     - if the scanning process generates a unique number for each
                   5884:                     sheet scanned the column that this ID number starts in
                   5885:       PaperIDlength - number of columns that comprise the unique ID number
                   5886:                       for the sheet of paper
1.424     albertel 5887:       FirstName   - column that the first name starts in
1.423     albertel 5888:       FirstNameLength - number of columns that the first name spans
                   5889:  
                   5890:       LastName    - column that the last name starts in
                   5891:       LastNameLength - number of columns that the last name spans
1.596.2.12.2.  (raeburn 5892:):       BubblesPerRow - number of bubbles available in each row used to
                   5893:):                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5894: 
                   5895: =cut
1.422     foxr     5896: 
1.82      albertel 5897: sub get_scantron_config {
                   5898:     my ($which) = @_;
1.518     raeburn  5899:     my @lines = &get_scantronformat_file();
1.82      albertel 5900:     my %config;
1.157     albertel 5901:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5902:     foreach my $line (@lines) {
1.82      albertel 5903: 	my ($name,$descrip)=split(/:/,$line);
                   5904: 	if ($name ne $which ) { next; }
                   5905: 	chomp($line);
                   5906: 	my @config=split(/:/,$line);
                   5907: 	$config{'name'}=$config[0];
                   5908: 	$config{'description'}=$config[1];
                   5909: 	$config{'CODElocation'}=$config[2];
                   5910: 	$config{'CODEstart'}=$config[3];
                   5911: 	$config{'CODElength'}=$config[4];
                   5912: 	$config{'IDstart'}=$config[5];
                   5913: 	$config{'IDlength'}=$config[6];
                   5914: 	$config{'Qstart'}=$config[7];
1.497     foxr     5915:  	$config{'Qlength'}=$config[8];
1.82      albertel 5916: 	$config{'Qoff'}=$config[9];
                   5917: 	$config{'Qon'}=$config[10];
1.157     albertel 5918: 	$config{'PaperID'}=$config[11];
                   5919: 	$config{'PaperIDlength'}=$config[12];
                   5920: 	$config{'FirstName'}=$config[13];
                   5921: 	$config{'FirstNamelength'}=$config[14];
                   5922: 	$config{'LastName'}=$config[15];
                   5923: 	$config{'LastNamelength'}=$config[16];
1.596.2.12.2.  (raeburn 5924:):         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5925: 	last;
                   5926:     }
                   5927:     return %config;
                   5928: }
                   5929: 
1.423     albertel 5930: =pod 
                   5931: 
                   5932: =item username_to_idmap
                   5933: 
1.556     weissno  5934:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5935:     student username:domain.
                   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.596.2.12.2.  3(raebur 5953:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   5954:5):         unless ($id eq '') {
                   5955:5):             if (!exists($idmap{$id})) {
                   5956:5):                 $idmap{$id} = $student;
                   5957:5):             } else {
                   5958:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   5959:5):                 if ($status eq 'Active') {
                   5960:5):                     $idmap{$id} = $student;
                   5961:5):                 }
                   5962:5):             }
                   5963:5):         }
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: 
                   6135:   Decodes a scanline from the selected scantron file
                   6136: 
                   6137:  Arguments:
                   6138:     line             - The text of the scantron file line to process
                   6139:     whichline        - Line number
                   6140:     scantron_config  - Hash describing the format of the scantron lines.
                   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.596.2.12.2.  6(raebur 6145:3):     randomorder      - True if randomorder in use
                   6146:3):     randompick       - True if randompick in use
                   6147:3):     sequence         - Exam folder URL
                   6148:3):     master_seq       - Ref to array containing symbs in exam folder
                   6149:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6150:3):                        (corresponding values are resource objects)
                   6151:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6152:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6153:3):                        are refs to an array of resource objects, ordered
                   6154:3):                        according to order used for CODE, when randomorder
                   6155:3):                        and or randompick are in use.
                   6156:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6157:3):                        for current line to question number used for same question
                   6158:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6159:3):     startline        - Ref to hash where key is question number (0 is first)
                   6160:3):                        and value is number of first bubble line for current 
                   6161:3):                        student or code-based randompick and/or randomorder.
                   6162:3):     totalref         - Ref of scalar used to score total number of bubble
                   6163:3):                        lines needed for responses in a scan line (used when
                   6164:3):                        randompick in use. 
                   6165:3): 
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.596.2.12.2.  6(raebur 6210:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6211:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6212:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6213: 
1.82      albertel 6214:     my %record;
1.596.2.12.2.  6(raebur 6215:3):     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.596.2.12.2.  6(raebur 6251:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6252:3):     if ($randompick || $randomorder) {
                   6253:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6254:3):                                          $master_seq,$symb_to_resource,
                   6255:3):                                          $partids_by_symb,$orderedforcode,
                   6256:3):                                          $respnumlookup,$startline);
                   6257:3):         if ($total) {
                   6258:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6259:3):         }
                   6260:3):         if (ref($totalref)) {
                   6261:3):             $$totalref = $total;
                   6262:3):         }
                   6263:3):     }
                   6264:3):     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.596.2.12.2.  6(raebur 6268:3):         my $answers_needed;
                   6269:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6270:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6271:3):         } else {
                   6272:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6273:3):         }
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.596.2.12.2.  6(raebur 6282:3):         my $subdivided;
                   6283:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6284:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6285:3):         } else {
                   6286:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6287:3):         }
                   6288:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6289:             my $subquestnum = 1;
                   6290:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6291:3):             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.596.2.12.2.  6(raebur 6302:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6303:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6304:                 } else {
                   6305:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6306:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6307:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6308:3):                         $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.596.2.12.2.  6(raebur 6317:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6318:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6319:             } else {
                   6320:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6321:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6322:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6323:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6324:             }
                   6325:         }
                   6326:     }
                   6327:     $record{'scantron.maxquest'}=$questnum;
                   6328:     return \%record;
                   6329: }
1.447     foxr     6330: 
1.596.2.12.2.  6(raebur 6331:3): sub get_master_seq {
                   6332:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6333:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6334:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6335:3):     my $resource_error;
                   6336:3):     foreach my $resource (@{$resources}) {
                   6337:3):         my $ressymb;
                   6338:3):         if (ref($resource)) {
                   6339:3):             $ressymb = $resource->symb();
                   6340:3):             push(@{$master_seq},$ressymb);
                   6341:3):             $symb_to_resource->{$ressymb} = $resource;
                   6342:3):         } else {
                   6343:3):             $resource_error = 1;
                   6344:3):             last;
                   6345:3):         }
                   6346:3):     }
                   6347:3):     return $resource_error;
                   6348:3): }
                   6349:3): 
                   6350:3): sub get_respnum_lookups {
                   6351:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6352:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6353:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6354:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6355:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6356:3):                    (ref($startline) eq 'HASH'));
                   6357:3):     my ($user,$scancode);
                   6358:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6359:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6360:3):         $scancode = $record->{'scantron.CODE'};
                   6361:3):     } else {
                   6362:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6363:3):     }
                   6364:3):     my @mapresources =
                   6365:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6366:3):                      $orderedforcode);
                   6367:3):     my $total = 0;
                   6368:3):     my $count = 0;
                   6369:3):     foreach my $resource (@mapresources) {
                   6370:3):         my $id = $resource->id();
                   6371:3):         my $symb = $resource->symb();
                   6372:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6373:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6374:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6375:3):                 if ($respnum ne '') {
                   6376:3):                     $respnumlookup->{$count} = $respnum;
                   6377:3):                     $startline->{$count} = $total;
                   6378:3):                     $total += $bubble_lines_per_response{$respnum};
                   6379:3):                     $count ++;
                   6380:3):                 }
                   6381:3):             }
                   6382:3):         }
                   6383:3):     }
                   6384:3):     return $total;
                   6385:3): }
                   6386:3): 
1.503     raeburn  6387: sub scantron_validator_lettnum {
                   6388:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6389:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6390:3):         $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.596.2.12.2.  6(raebur 6409:3):     my $responsenum = $questnum-1;
                   6410:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6411:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6412:3):     }
                   6413:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6414:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6415:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6416:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6417:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6418:3):         ($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.596.2.12.2.  6(raebur 6425:3):         }
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.596.2.12.2.  6(raebur 6473:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6474:3):         $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.596.2.12.2.  6(raebur 6516:3):         my $responsenum = $questnum-1;
                   6517:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6518:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6519:3):         }
                   6520:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6521:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6522:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6523:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6524:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6525:3):             ($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.596.2.12.2.  0(raebur 6707:3): 	$r->print(
                   6708:3):             '<p class="LC_error">'
                   6709:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6710:3):                 $errmsg)
          1(raebur 6711:3):            .'</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.596.2.6  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 {
                   6825:     my ($button_text)=@_;
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.596.2.12.2.  8(raebur 6833:4): 	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.596.2.12.2.  (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.596.2.12.2.  6(raebur 6847:3): '.&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.596.2.12.2.  (raeburn 6852:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 6853: </table>
                   6854: <br />
1.596.2.12.2.  2(raebur 6855:2): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
                   6856:2): <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
1.203     albertel 6857: 
                   6858: <br />
1.492     albertel 6859: ');
1.203     albertel 6860: }
                   6861: 
1.423     albertel 6862: =pod
                   6863: 
                   6864: =item scantron_do_warning
                   6865: 
1.424     albertel 6866:    Check if the operator has picked something for all required
                   6867:    fields. Error out if something is missing.
                   6868: 
1.423     albertel 6869: =cut
                   6870: 
1.203     albertel 6871: sub scantron_do_warning {
                   6872:     my ($r)=@_;
1.324     albertel 6873:     my ($symb)=&get_symb($r);
1.203     albertel 6874:     if (!$symb) {return '';}
1.324     albertel 6875:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6876:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6877:     if ( $env{'form.selectpage'} eq '' ||
                   6878: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6879: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  6880: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6881: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6882: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6883: 	} 
1.257     albertel 6884: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  6885: 	    $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 6886: 	} 
1.257     albertel 6887: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  6888: 	    $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 6889: 	} 
                   6890:     } else {
1.265     www      6891: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.596.2.12.2.  (raeburn 6892:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6893: 	$r->print('
1.596.2.12.2.  (raeburn 6894:): '.$warning.$bubbledbyhand.'
1.492     albertel 6895: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6896: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6897: ');
1.237     albertel 6898:     }
1.352     albertel 6899:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6900:     return '';
                   6901: }
                   6902: 
1.423     albertel 6903: =pod
                   6904: 
                   6905: =item scantron_form_start
                   6906: 
1.424     albertel 6907:     html hidden input for remembering all selected grading options
                   6908: 
1.423     albertel 6909: =cut
                   6910: 
1.203     albertel 6911: sub scantron_form_start {
                   6912:     my ($max_bubble)=@_;
                   6913:     my $result= <<SCANTRONFORM;
                   6914: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6915:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6916:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6917:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6918:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6919:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6920:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6921:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6922:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6923:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6924: SCANTRONFORM
1.447     foxr     6925: 
                   6926:   my $line = 0;
                   6927:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6928:        my $chunk =
                   6929: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6930:        $chunk .=
                   6931: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6932:        $chunk .= 
                   6933:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6934:        $chunk .=
                   6935:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 6936:3):        $chunk .=
                   6937:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6938:        $result .= $chunk;
                   6939:        $line++;
1.596.2.12.2.  6(raebur 6940:3):     }
1.203     albertel 6941:     return $result;
                   6942: }
                   6943: 
1.423     albertel 6944: =pod
                   6945: 
                   6946: =item scantron_validate_file
                   6947: 
1.596.2.6  raeburn  6948:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6949: 
                   6950:     Also processes any necessary information resets that need to
                   6951:     occur before validation begins (ignore previous corrections,
                   6952:     restarting the skipped records processing)
                   6953: 
1.423     albertel 6954: =cut
                   6955: 
1.157     albertel 6956: sub scantron_validate_file {
                   6957:     my ($r) = @_;
1.324     albertel 6958:     my ($symb)=&get_symb($r);
1.157     albertel 6959:     if (!$symb) {return '';}
1.324     albertel 6960:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6961:     
1.596.2.12.2.  0(raebur 6962:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 6963:     # them when doing the corrections reset
1.257     albertel 6964:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6965: 	&reset_skipping_status();
                   6966:     }
1.257     albertel 6967:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6968: 	&remember_current_skipped();
1.257     albertel 6969: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6970:     }
                   6971: 
1.257     albertel 6972:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6973: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6974: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6975: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6976: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6977:     }
1.200     albertel 6978: 
1.257     albertel 6979:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6980: 	&scantron_process_corrections($r);
                   6981:     }
1.503     raeburn  6982:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6983:     #get the student pick code ready
                   6984:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6985:     my $nav_error;
1.596.2.12.2.  (raeburn 6986:):     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6987:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6988:     if ($nav_error) {
                   6989:         $r->print(&navmap_errormsg());
                   6990:         return '';
                   6991:     }
1.203     albertel 6992:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 6993:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6994:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6995:):     }
1.157     albertel 6996:     $r->print($result);
                   6997:     
1.334     albertel 6998:     my @validate_phases=( 'sequence',
                   6999: 			  'ID',
1.157     albertel 7000: 			  'CODE',
                   7001: 			  'doublebubble',
                   7002: 			  'missingbubbles');
1.257     albertel 7003:     if (!$env{'form.validatepass'}) {
                   7004: 	$env{'form.validatepass'} = 0;
1.157     albertel 7005:     }
1.257     albertel 7006:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7007: 
1.448     foxr     7008: 
1.157     albertel 7009:     my $stop=0;
                   7010:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7011: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7012: 	$r->rflush();
1.596.2.12.2.  6(raebur 7013:3): 
1.157     albertel 7014: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7015: 	{
                   7016: 	    no strict 'refs';
                   7017: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7018: 	}
                   7019:     }
                   7020:     if (!$stop) {
1.203     albertel 7021: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  7022: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7023:                   $warning.
                   7024:                   &mt('Perform verification for each student after storage of submissions?').
                   7025:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7026:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7027:                   ('&nbsp;'x3).'<label>'.
                   7028:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7029:                   '</label></span><br />'.
                   7030:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      7031:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
1.542     raeburn  7032:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7033:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7034:     } else {
                   7035: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7036: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7037:     }
                   7038:     if ($stop) {
1.334     albertel 7039: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7040: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7041: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7042: 
1.492     albertel 7043: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 7044: 	} else {
1.503     raeburn  7045:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7046: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7047:             } else {
1.539     riegler  7048:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7049:             }
1.492     albertel 7050: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7051: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7052: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7053: 	}
1.157     albertel 7054:     }
1.352     albertel 7055:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 7056:     return '';
                   7057: }
                   7058: 
1.423     albertel 7059: 
                   7060: =pod
                   7061: 
                   7062: =item scantron_remove_file
                   7063: 
1.596.2.6  raeburn  7064:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7065:    scantron_original_<filename> is never removed
                   7066: 
                   7067: 
1.423     albertel 7068: =cut
                   7069: 
1.200     albertel 7070: sub scantron_remove_file {
1.192     albertel 7071:     my ($which)=@_;
1.257     albertel 7072:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7073:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7074:     my $file='scantron_';
1.200     albertel 7075:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7076: 	$file.=$which.'_';
1.192     albertel 7077:     } else {
                   7078: 	return 'refused';
                   7079:     }
1.257     albertel 7080:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7081:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7082: }
                   7083: 
1.423     albertel 7084: 
                   7085: =pod
                   7086: 
                   7087: =item scantron_remove_scan_data
                   7088: 
1.596.2.6  raeburn  7089:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7090:    data file.  (In the case that both the are doing skipped records we need
                   7091:    to remember the old skipped lines for the time being so that element
                   7092:    persists for a while.)
                   7093: 
1.423     albertel 7094: =cut
                   7095: 
1.200     albertel 7096: sub scantron_remove_scan_data {
1.257     albertel 7097:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7098:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7099:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7100:     my @todelete;
1.257     albertel 7101:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7102:     foreach my $key (@keys) {
                   7103: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7104: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7105: 		$key=~/remember_skipping/) {
                   7106: 		next;
                   7107: 	    }
1.192     albertel 7108: 	    push(@todelete,$key);
                   7109: 	}
                   7110:     }
1.200     albertel 7111:     my $result;
1.192     albertel 7112:     if (@todelete) {
1.491     albertel 7113: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7114: 				       \@todelete,$cdom,$cname);
                   7115:     } else {
                   7116: 	$result = 'ok';
1.192     albertel 7117:     }
                   7118:     return $result;
                   7119: }
                   7120: 
1.423     albertel 7121: 
                   7122: =pod
                   7123: 
                   7124: =item scantron_getfile
                   7125: 
1.596.2.6  raeburn  7126:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7127:     the scan_data hash
                   7128:   
                   7129:   Arguments:
                   7130:     None
                   7131: 
                   7132:   Returns:
                   7133:     2 hash references
                   7134: 
                   7135:      - first one has 
                   7136:          orig      -
                   7137:          corrected -
                   7138:          skipped   -  each of which points to an array ref of the specified
                   7139:                       file broken up into individual lines
                   7140:          count     - number of scanlines
                   7141:  
                   7142:      - second is the scan_data hash possible keys are
1.425     albertel 7143:        ($number refers to scanline numbered $number and thus the key affects
                   7144:         only that scanline
                   7145:         $bubline refers to the specific bubble line element and the aspects
                   7146:         refers to that specific bubble line element)
                   7147: 
                   7148:        $number.user - username:domain to use
                   7149:        $number.CODE_ignore_dup 
                   7150:                     - ignore the duplicate CODE error 
                   7151:        $number.useCODE
                   7152:                     - use the CODE in the scanline as is
                   7153:        $number.no_bubble.$bubline
                   7154:                     - it is valid that there is no bubbled in bubble
                   7155:                       at $number $bubline
                   7156:        remember_skipping
                   7157:                     - a frozen hash containing keys of $number and values
                   7158:                       of either 
                   7159:                         1 - we are on a 'do skipped records pass' and plan
                   7160:                             on processing this line
                   7161:                         2 - we are on a 'do skipped records pass' and this
                   7162:                             scanline has been marked to skip yet again
1.424     albertel 7163: 
1.423     albertel 7164: =cut
                   7165: 
1.157     albertel 7166: sub scantron_getfile {
1.200     albertel 7167:     #FIXME really would prefer a scantron directory
1.257     albertel 7168:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7169:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7170:     my $lines;
                   7171:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7172: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7173:     my %scanlines;
                   7174:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7175:     my $temp=$scanlines{'orig'};
                   7176:     $scanlines{'count'}=$#$temp;
                   7177: 
                   7178:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7179: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7180:     if ($lines eq '-1') {
                   7181: 	$scanlines{'corrected'}=[];
                   7182:     } else {
                   7183: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7184:     }
                   7185:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7186: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7187:     if ($lines eq '-1') {
                   7188: 	$scanlines{'skipped'}=[];
                   7189:     } else {
                   7190: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7191:     }
1.175     albertel 7192:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7193:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7194:     my %scan_data = @tmp;
                   7195:     return (\%scanlines,\%scan_data);
                   7196: }
                   7197: 
1.423     albertel 7198: =pod
                   7199: 
                   7200: =item lonnet_putfile
                   7201: 
1.424     albertel 7202:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7203: 
                   7204:  Arguments:
                   7205:    $contents - data to store
                   7206:    $filename - filename to store $contents into
                   7207: 
                   7208:  Returns:
                   7209:    result value from &Apache::lonnet::finishuserfileupload
                   7210: 
1.423     albertel 7211: =cut
                   7212: 
1.157     albertel 7213: sub lonnet_putfile {
                   7214:     my ($contents,$filename)=@_;
1.257     albertel 7215:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7216:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7217:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7218:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7219: 
                   7220: }
                   7221: 
1.423     albertel 7222: =pod
                   7223: 
                   7224: =item scantron_putfile
                   7225: 
1.596.2.6  raeburn  7226:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7227:     scan_data hash. (Does not modify the original version only the
                   7228:     corrected and skipped versions.
                   7229: 
                   7230:  Arguments:
                   7231:     $scanlines - hash ref that looks like the first return value from
                   7232:                  &scantron_getfile()
                   7233:     $scan_data - hash ref that looks like the second return value from
                   7234:                  &scantron_getfile()
                   7235: 
1.423     albertel 7236: =cut
                   7237: 
1.157     albertel 7238: sub scantron_putfile {
                   7239:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7240:     #FIXME really would prefer a scantron directory
1.257     albertel 7241:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7242:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7243:     if ($scanlines) {
                   7244: 	my $prefix='scantron_';
1.157     albertel 7245: # no need to update orig, shouldn't change
                   7246: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7247: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7248: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7249: 			$prefix.'corrected_'.
1.257     albertel 7250: 			$env{'form.scantron_selectfile'});
1.200     albertel 7251: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7252: 			$prefix.'skipped_'.
1.257     albertel 7253: 			$env{'form.scantron_selectfile'});
1.200     albertel 7254:     }
1.175     albertel 7255:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7256: }
                   7257: 
1.423     albertel 7258: =pod
                   7259: 
                   7260: =item scantron_get_line
                   7261: 
1.424     albertel 7262:    Returns the correct version of the scanline
                   7263: 
                   7264:  Arguments:
                   7265:     $scanlines - hash ref that looks like the first return value from
                   7266:                  &scantron_getfile()
                   7267:     $scan_data - hash ref that looks like the second return value from
                   7268:                  &scantron_getfile()
                   7269:     $i         - number of the requested line (starts at 0)
                   7270: 
                   7271:  Returns:
                   7272:    A scanline, (either the original or the corrected one if it
                   7273:    exists), or undef if the requested scanline should be
                   7274:    skipped. (Either because it's an skipped scanline, or it's an
                   7275:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7276:    pass.
                   7277: 
1.423     albertel 7278: =cut
                   7279: 
1.157     albertel 7280: sub scantron_get_line {
1.200     albertel 7281:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7282:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7283:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7284:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7285:     return $scanlines->{'orig'}[$i]; 
                   7286: }
                   7287: 
1.423     albertel 7288: =pod
                   7289: 
                   7290: =item scantron_todo_count
                   7291: 
1.424     albertel 7292:     Counts the number of scanlines that need processing.
                   7293: 
                   7294:  Arguments:
                   7295:     $scanlines - hash ref that looks like the first return value from
                   7296:                  &scantron_getfile()
                   7297:     $scan_data - hash ref that looks like the second return value from
                   7298:                  &scantron_getfile()
                   7299: 
                   7300:  Returns:
                   7301:     $count - number of scanlines to process
                   7302: 
1.423     albertel 7303: =cut
                   7304: 
1.200     albertel 7305: sub get_todo_count {
                   7306:     my ($scanlines,$scan_data)=@_;
                   7307:     my $count=0;
                   7308:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7309: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7310: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7311: 	$count++;
                   7312:     }
                   7313:     return $count;
                   7314: }
                   7315: 
1.423     albertel 7316: =pod
                   7317: 
                   7318: =item scantron_put_line
                   7319: 
1.596.2.6  raeburn  7320:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7321:     data file.
                   7322: 
                   7323:  Arguments:
                   7324:     $scanlines - hash ref that looks like the first return value from
                   7325:                  &scantron_getfile()
                   7326:     $scan_data - hash ref that looks like the second return value from
                   7327:                  &scantron_getfile()
                   7328:     $i         - line number to update
                   7329:     $newline   - contents of the updated scanline
                   7330:     $skip      - if true make the line for skipping and update the
                   7331:                  'skipped' file
                   7332: 
1.423     albertel 7333: =cut
                   7334: 
1.157     albertel 7335: sub scantron_put_line {
1.200     albertel 7336:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7337:     if ($skip) {
                   7338: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7339: 	&start_skipping($scan_data,$i);
1.157     albertel 7340: 	return;
                   7341:     }
                   7342:     $scanlines->{'corrected'}[$i]=$newline;
                   7343: }
                   7344: 
1.423     albertel 7345: =pod
                   7346: 
                   7347: =item scantron_clear_skip
                   7348: 
1.424     albertel 7349:    Remove a line from the 'skipped' file
                   7350: 
                   7351:  Arguments:
                   7352:     $scanlines - hash ref that looks like the first return value from
                   7353:                  &scantron_getfile()
                   7354:     $scan_data - hash ref that looks like the second return value from
                   7355:                  &scantron_getfile()
                   7356:     $i         - line number to update
                   7357: 
1.423     albertel 7358: =cut
                   7359: 
1.376     albertel 7360: sub scantron_clear_skip {
                   7361:     my ($scanlines,$scan_data,$i)=@_;
                   7362:     if (exists($scanlines->{'skipped'}[$i])) {
                   7363: 	undef($scanlines->{'skipped'}[$i]);
                   7364: 	return 1;
                   7365:     }
                   7366:     return 0;
                   7367: }
                   7368: 
1.423     albertel 7369: =pod
                   7370: 
                   7371: =item scantron_filter_not_exam
                   7372: 
1.424     albertel 7373:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7374:    filter out resources that are not marked as 'exam' mode
                   7375: 
1.423     albertel 7376: =cut
                   7377: 
1.334     albertel 7378: sub scantron_filter_not_exam {
                   7379:     my ($curres)=@_;
                   7380:     
                   7381:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7382: 	# if the user has asked to not have either hidden
                   7383: 	# or 'randomout' controlled resources to be graded
                   7384: 	# don't include them
                   7385: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7386: 	    && $curres->randomout) {
                   7387: 	    return 0;
                   7388: 	}
                   7389: 	return 1;
                   7390:     }
                   7391:     return 0;
                   7392: }
                   7393: 
1.423     albertel 7394: =pod
                   7395: 
                   7396: =item scantron_validate_sequence
                   7397: 
1.424     albertel 7398:     Validates the selected sequence, checking for resource that are
                   7399:     not set to exam mode.
                   7400: 
1.423     albertel 7401: =cut
                   7402: 
1.334     albertel 7403: sub scantron_validate_sequence {
                   7404:     my ($r,$currentphase) = @_;
                   7405: 
                   7406:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7407:     unless (ref($navmap)) {
                   7408:         $r->print(&navmap_errormsg());
                   7409:         return (1,$currentphase);
                   7410:     }
1.334     albertel 7411:     my (undef,undef,$sequence)=
                   7412: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7413: 
                   7414:     my $map=$navmap->getResourceByUrl($sequence);
                   7415: 
                   7416:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7417:                                     value="ignore" />');
                   7418:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7419: 	my @resources=
                   7420: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7421: 	if (@resources) {
1.596.2.12.2.  0(raebur 7422:2): 	    $r->print('<p class="LC_warning">'
                   7423:2):                .&mt('Some resources in the sequence currently are not set to'
                   7424:2):                    .' exam mode. Grading these resources currently may not'
                   7425:2):                    .' work correctly.')
                   7426:2):                .'</p>'
                   7427:2):             );
1.334     albertel 7428: 	    return (1,$currentphase);
                   7429: 	}
                   7430:     }
                   7431: 
                   7432:     return (0,$currentphase+1);
                   7433: }
                   7434: 
1.423     albertel 7435: 
                   7436: 
1.157     albertel 7437: sub scantron_validate_ID {
                   7438:     my ($r,$currentphase) = @_;
                   7439:     
                   7440:     #get student info
                   7441:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7442:     my %idmap=&username_to_idmap($classlist);
                   7443: 
                   7444:     #get scantron line setup
1.257     albertel 7445:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7446:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7447: 
                   7448:     my $nav_error;
1.596.2.12.2.  (raeburn 7449:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7450:     if ($nav_error) {
                   7451:         $r->print(&navmap_errormsg());
                   7452:         return(1,$currentphase);
                   7453:     }
1.157     albertel 7454: 
                   7455:     my %found=('ids'=>{},'usernames'=>{});
                   7456:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7457: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7458: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7459: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7460: 						 $scan_data);
                   7461: 	my $id=$$scan_record{'scantron.ID'};
                   7462: 	my $found;
                   7463: 	foreach my $checkid (keys(%idmap)) {
                   7464: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7465: 	}
                   7466: 	if ($found) {
                   7467: 	    my $username=$idmap{$found};
                   7468: 	    if ($found{'ids'}{$found}) {
                   7469: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7470: 					 $line,'duplicateID',$found);
1.194     albertel 7471: 		return(1,$currentphase);
1.157     albertel 7472: 	    } elsif ($found{'usernames'}{$username}) {
                   7473: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7474: 					 $line,'duplicateID',$username);
1.194     albertel 7475: 		return(1,$currentphase);
1.157     albertel 7476: 	    }
1.186     albertel 7477: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7478: 	    $found{'ids'}{$found}++;
                   7479: 	    $found{'usernames'}{$username}++;
                   7480: 	} else {
                   7481: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7482: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7483: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7484: 		    &scantron_get_correction($r,$i,$scan_record,
                   7485: 					     \%scantron_config,
                   7486: 					     $line,'duplicateID',$username);
1.194     albertel 7487: 		    return(1,$currentphase);
1.157     albertel 7488: 		} elsif (!defined($username)) {
                   7489: 		    &scantron_get_correction($r,$i,$scan_record,
                   7490: 					     \%scantron_config,
                   7491: 					     $line,'incorrectID');
1.194     albertel 7492: 		    return(1,$currentphase);
1.157     albertel 7493: 		}
                   7494: 		$found{'usernames'}{$username}++;
                   7495: 	    } else {
                   7496: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7497: 					 $line,'incorrectID');
1.194     albertel 7498: 		return(1,$currentphase);
1.157     albertel 7499: 	    }
                   7500: 	}
                   7501:     }
                   7502: 
                   7503:     return (0,$currentphase+1);
                   7504: }
                   7505: 
1.423     albertel 7506: 
1.157     albertel 7507: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7508:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7509:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7510: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7511: #to show both the current line and the previous one and allow skipping
                   7512: #the previous one or the current one
                   7513: 
1.333     albertel 7514:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7515:         $r->print(
                   7516:             '<p class="LC_warning">'
                   7517:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7518:                 "<b>$error</b>",
                   7519:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7520:            ."</p> \n");
1.157     albertel 7521:     } else {
1.596.2.6  raeburn  7522:         $r->print(
                   7523:             '<p class="LC_warning">'
                   7524:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7525:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7526:            ."</p> \n");
                   7527:     }
                   7528:     my $message =
                   7529:         '<p>'
                   7530:        .&mt('The ID on the form is [_1]',
                   7531:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7532:        .'<br />'
1.596.2.12  raeburn  7533:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7534:             $$scan_record{'scantron.LastName'},
                   7535:             $$scan_record{'scantron.FirstName'})
                   7536:        .'</p>';
1.242     albertel 7537: 
1.157     albertel 7538:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7539:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7540:                            # Array populated for doublebubble or
                   7541:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7542:                            # to validate radio button checking   
                   7543: 
1.157     albertel 7544:     if ($error =~ /ID$/) {
1.186     albertel 7545: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7546: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7547: 		      "</p>\n");
1.157     albertel 7548: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7549: 	    $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 7550: 	}
1.242     albertel 7551: 	$r->print($message);
1.492     albertel 7552: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7553: 	$r->print("\n<ul><li> ");
                   7554: 	#FIXME it would be nice if this sent back the user ID and
                   7555: 	#could do partial userID matches
                   7556: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7557: 				       'scantron_username','scantron_domain'));
                   7558: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7559:3): 	$r->print("\n:\n".
1.257     albertel 7560: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7561: 
                   7562: 	$r->print('</li>');
1.186     albertel 7563:     } elsif ($error =~ /CODE$/) {
                   7564: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7565: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7566: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7567: 	    $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 7568: 	}
1.596.2.6  raeburn  7569:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7570:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7571:                  ."</p>\n");
1.242     albertel 7572: 	$r->print($message);
1.596.2.6  raeburn  7573: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7574: 	$r->print("\n<br /> ");
1.194     albertel 7575: 	my $i=0;
1.273     albertel 7576: 	if ($error eq 'incorrectCODE' 
                   7577: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7578: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7579: 	    if ($closest > 0) {
                   7580: 		foreach my $testcode (@{$closest}) {
                   7581: 		    my $checked='';
1.569     bisitz   7582: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7583: 		    $r->print("
                   7584:    <label>
1.569     bisitz   7585:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7586:        ".&mt("Use the similar CODE [_1] instead.",
                   7587: 	    "<b><tt>".$testcode."</tt></b>")."
                   7588:     </label>
                   7589:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7590: 		    $r->print("\n<br />");
                   7591: 		    $i++;
                   7592: 		}
1.194     albertel 7593: 	    }
                   7594: 	}
1.273     albertel 7595: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7596: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7597: 	    $r->print("
                   7598:     <label>
1.569     bisitz   7599:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7600:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7601: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7602:     </label>");
1.273     albertel 7603: 	    $r->print("\n<br />");
                   7604: 	}
1.194     albertel 7605: 
1.188     albertel 7606: 	$r->print(<<ENDSCRIPT);
                   7607: <script type="text/javascript">
                   7608: function change_radio(field) {
1.190     albertel 7609:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7610:     var i;
                   7611:     for (i=0;i<slct.length;i++) {
                   7612:         if (slct[i].value==field) { slct[i].checked=true; }
                   7613:     }
                   7614: }
                   7615: </script>
                   7616: ENDSCRIPT
1.187     albertel 7617: 	my $href="/adm/pickcode?".
1.359     www      7618: 	   "form=".&escape("scantronupload").
                   7619: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7620: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7621: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7622: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7623: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7624: 	    $r->print("
                   7625:     <label>
                   7626:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7627:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7628: 	     "<a target='_blank' href='$href'>","</a>")."
                   7629:     </label> 
1.558     bisitz   7630:     ".&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 7631: 	    $r->print("\n<br />");
                   7632: 	}
1.492     albertel 7633: 	$r->print("
                   7634:     <label>
                   7635:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7636:        ".&mt("Use [_1] as the CODE.",
                   7637: 	     "</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 7638: 	$r->print("\n<br /><br />");
1.157     albertel 7639:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7640: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7641: 
                   7642: 	# The form field scantron_questions is acutally a list of line numbers.
                   7643: 	# represented by this form so:
                   7644: 
1.596.2.12.2.  6(raebur 7645:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7646:3):                                                 $respnumlookup,$startline);
1.497     foxr     7647: 
1.157     albertel 7648: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7649: 		  $line_list.'" />');
1.242     albertel 7650: 	$r->print($message);
1.492     albertel 7651: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7652: 	foreach my $question (@{$arg}) {
1.503     raeburn  7653: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7654:3):                                                    $scan_record, $error,
                   7655:3):                                                    $randomorder,$randompick,
                   7656:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7657:             push(@lines_to_correct,@linenums);
1.157     albertel 7658: 	}
1.503     raeburn  7659:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7660:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7661: 	$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 7662: 	$r->print($message);
1.492     albertel 7663: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7664: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7665: 
1.503     raeburn  7666: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7667: 	# a list of question numbers. Therefore:
                   7668: 	#
                   7669: 	
1.596.2.12.2.  6(raebur 7670:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7671:3):                                                 $respnumlookup,$startline);
1.497     foxr     7672: 
1.157     albertel 7673: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7674: 		  $line_list.'" />');
1.157     albertel 7675: 	foreach my $question (@{$arg}) {
1.503     raeburn  7676: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7677:3):                                                    $scan_record, $error,
                   7678:3):                                                    $randomorder,$randompick,
                   7679:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7680:             push(@lines_to_correct,@linenums);
1.157     albertel 7681: 	}
1.503     raeburn  7682:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7683:     } else {
                   7684: 	$r->print("\n<ul>");
                   7685:     }
                   7686:     $r->print("\n</li></ul>");
1.497     foxr     7687: }
                   7688: 
1.503     raeburn  7689: sub verify_bubbles_checked {
                   7690:     my (@ansnums) = @_;
                   7691:     my $ansnumstr = join('","',@ansnums);
                   7692:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   7693:     my $output = (<<ENDSCRIPT);
                   7694: <script type="text/javascript">
                   7695: function verify_bubble_radio(form) {
                   7696:     var ansnumArray = new Array ("$ansnumstr");
                   7697:     var need_bubble_count = 0;
                   7698:     for (var i=0; i<ansnumArray.length; i++) {
                   7699:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7700:             var bubble_picked = 0; 
                   7701:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7702:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7703:                     bubble_picked = 1;
                   7704:                 }
                   7705:             }
                   7706:             if (bubble_picked == 0) {
                   7707:                 need_bubble_count ++;
                   7708:             }
                   7709:         }
                   7710:     }
                   7711:     if (need_bubble_count) {
                   7712:         alert("$warning");
                   7713:         return;
                   7714:     }
                   7715:     form.submit(); 
                   7716: }
                   7717: </script>
                   7718: ENDSCRIPT
                   7719:     return $output;
                   7720: }
                   7721: 
1.497     foxr     7722: =pod
                   7723: 
                   7724: =item  questions_to_line_list
1.157     albertel 7725: 
1.497     foxr     7726: Converts a list of questions into a string of comma separated
                   7727: line numbers in the answer sheet used by the questions.  This is
                   7728: used to fill in the scantron_questions form field.
                   7729: 
                   7730:   Arguments:
                   7731:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7732:3):      randomorder  - True if randomorder in use.
                   7733:3):      randompick   - True if randompick in use.
                   7734:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7735:3):                      for current line to question number used for same question
                   7736:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7737:3):      startline    - Reference to hash where key is question number (0 is first)
                   7738:3):                     and key is number of first bubble line for current student
                   7739:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7740: 
                   7741: =cut
                   7742: 
                   7743: 
                   7744: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7745:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7746:     my @lines;
                   7747: 
1.503     raeburn  7748:     foreach my $item (@{$questions}) {
                   7749:         my $question = $item;
                   7750:         my ($first,$count,$last);
                   7751:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7752:             $question = $1;
                   7753:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7754:3):             my $responsenum = $question-1;
                   7755:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7756:3):                 $responsenum = $respnumlookup->{$question-1};
                   7757:3):                 if (ref($startline) eq 'HASH') {
                   7758:3):                     $first = $startline->{$question-1} + 1;
                   7759:3):                 }
                   7760:3):             } else {
                   7761:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7762:3):             }
          7(raebur 7763:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7764:             my $subcount = 1;
                   7765:             while ($subcount<$subquestion) {
                   7766:                 $first += $subans[$subcount-1];
                   7767:                 $subcount ++;
                   7768:             }
                   7769:             $count = $subans[$subquestion-1];
                   7770:         } else {
1.596.2.12.2.  7(raebur 7771:3):             my $responsenum = $question-1;
                   7772:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7773:3):                 $responsenum = $respnumlookup->{$question-1};
                   7774:3):                 if (ref($startline) eq 'HASH') {
                   7775:3):                     $first = $startline->{$question-1} + 1;
                   7776:3):                 }
                   7777:3):             } else {
                   7778:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7779:3):             }
                   7780:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7781:         }
1.506     raeburn  7782:         $last = $first+$count-1;
1.503     raeburn  7783:         push(@lines, ($first..$last));
1.497     foxr     7784:     }
                   7785:     return join(',', @lines);
                   7786: }
                   7787: 
                   7788: =pod 
                   7789: 
                   7790: =item prompt_for_corrections
                   7791: 
                   7792: Prompts for a potentially multiline correction to the
                   7793: user's bubbling (factors out common code from scantron_get_correction
                   7794: for multi and missing bubble cases).
                   7795: 
                   7796:  Arguments:
                   7797:    $r           - Apache request object.
                   7798:    $question    - The question number to prompt for.
                   7799:    $scan_config - The scantron file configuration hash.
                   7800:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7801:    $error       - Type of error
1.596.2.12.2.  7(raebur 7802:3):    $randomorder - True if randomorder in use.
                   7803:3):    $randompick  - True if randompick in use.
                   7804:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7805:3):                     for current line to question number used for same question
                   7806:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   7807:3):    $startline   - Reference to hash where key is question number (0 is first)
                   7808:3):                   and value is number of first bubble line for current student
                   7809:3):                   or code-based randompick and/or randomorder.
1.497     foxr     7810: 
                   7811:  Implicit inputs:
                   7812:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7813:                                   Numbered from 0 (but question numbers are from
                   7814:                                   1.
                   7815:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7816:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7817:                                   type problems render as separate sub-questions, 
1.503     raeburn  7818:                                   in exam mode. This hash contains a 
                   7819:                                   comma-separated list of the lines per 
                   7820:                                   sub-question.
1.510     raeburn  7821:    %responsetype_per_response   - essayresponse, formularesponse,
                   7822:                                   stringresponse, imageresponse, reactionresponse,
                   7823:                                   and organicresponse type problem parts can have
1.503     raeburn  7824:                                   multiple lines per response if the weight
                   7825:                                   assigned exceeds 10.  In this case, only
                   7826:                                   one bubble per line is permitted, but more 
                   7827:                                   than one line might contain bubbles, e.g.
                   7828:                                   bubbling of: line 1 - J, line 2 - J, 
                   7829:                                   line 3 - B would assign 22 points.  
1.497     foxr     7830: 
                   7831: =cut
                   7832: 
                   7833: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 7834:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7835:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7836:     my ($current_line,$lines);
                   7837:     my @linenums;
                   7838:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 7839:3):     my ($first,$responsenum);
1.503     raeburn  7840:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7841:         $question = $1;
                   7842:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 7843:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7844:3):             $responsenum = $respnumlookup->{$question-1};
                   7845:3):             if (ref($startline) eq 'HASH') {
                   7846:3):                 $first = $startline->{$question-1};
                   7847:3):             }
                   7848:3):         } else {
                   7849:3):             $responsenum = $question-1;
          7(raebur 7850:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 7851:3):         }
                   7852:3):         $current_line = $first + 1 ;
                   7853:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7854:         my $subcount = 1;
                   7855:         while ($subcount<$subquestion) {
                   7856:             $current_line += $subans[$subcount-1];
                   7857:             $subcount ++;
                   7858:         }
                   7859:         $lines = $subans[$subquestion-1];
                   7860:     } else {
1.596.2.12.2.  6(raebur 7861:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7862:3):             $responsenum = $respnumlookup->{$question-1};
                   7863:3):             if (ref($startline) eq 'HASH') {
                   7864:3):                 $first = $startline->{$question-1};
                   7865:3):             }
                   7866:3):         } else {
                   7867:3):             $responsenum = $question-1;
                   7868:3):             $first = $first_bubble_line{$responsenum};
                   7869:3):         }
                   7870:3):         $current_line = $first + 1;
                   7871:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7872:     }
1.497     foxr     7873:     if ($lines > 1) {
1.503     raeburn  7874:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 7875:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7876:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7877:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7878:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7879:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7880:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 7881:3):             $r->print(&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).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&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.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7882:         } else {
                   7883:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7884:         }
1.497     foxr     7885:     }
                   7886:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7887:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 7888:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7889: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7890:         push(@linenums,$current_line);
1.497     foxr     7891: 	$current_line++;
                   7892:     }
                   7893:     if ($lines > 1) {
                   7894: 	$r->print("<hr /><br />");
                   7895:     }
1.503     raeburn  7896:     return @linenums;
1.157     albertel 7897: }
1.423     albertel 7898: 
                   7899: =pod
                   7900: 
                   7901: =item scantron_bubble_selector
                   7902:   
                   7903:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7904:    possibly showing the existing the selected bubbles if known
1.423     albertel 7905: 
                   7906:  Arguments:
                   7907:     $r           - Apache request object
                   7908:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7909:     $line        - Number of the line being displayed.
1.503     raeburn  7910:     $questionnum - Question number (may include subquestion)
                   7911:     $error       - Type of error.
1.497     foxr     7912:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7913: 
                   7914: =cut
                   7915: 
1.157     albertel 7916: sub scantron_bubble_selector {
1.503     raeburn  7917:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7918:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7919: 
                   7920:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 7921:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   7922:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7923:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7924:):             $max=$$scan_config{'BubblesPerRow'};
                   7925:):             if (($scmode eq 'number') && ($max > 10)) {
                   7926:):                 $max = 10;
                   7927:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   7928:):                 $max = 26;
                   7929:):             }
                   7930:):         } else {
                   7931:):             $max = 10;
                   7932:):         }
                   7933:):     }
1.274     albertel 7934: 
1.157     albertel 7935:     my @alphabet=('A'..'Z');
1.503     raeburn  7936:     $r->print(&Apache::loncommon::start_data_table().
                   7937:               &Apache::loncommon::start_data_table_row());
                   7938:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7939:     for (my $i=0;$i<$max+1;$i++) {
                   7940: 	$r->print("\n".'<td align="center">');
                   7941: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7942: 	else { $r->print('&nbsp;'); }
                   7943: 	$r->print('</td>');
                   7944:     }
1.503     raeburn  7945:     $r->print(&Apache::loncommon::end_data_table_row().
                   7946:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7947:     for (my $i=0;$i<$max;$i++) {
                   7948: 	$r->print("\n".
                   7949: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7950: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7951:     }
1.503     raeburn  7952:     my $nobub_checked = ' ';
                   7953:     if ($error eq 'missingbubble') {
                   7954:         $nobub_checked = ' checked = "checked" ';
                   7955:     }
                   7956:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7957: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7958:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7959:               $line.'" value="'.$questionnum.'" /></td>');
                   7960:     $r->print(&Apache::loncommon::end_data_table_row().
                   7961:               &Apache::loncommon::end_data_table());
1.157     albertel 7962: }
                   7963: 
1.423     albertel 7964: =pod
                   7965: 
                   7966: =item num_matches
                   7967: 
1.424     albertel 7968:    Counts the number of characters that are the same between the two arguments.
                   7969: 
                   7970:  Arguments:
                   7971:    $orig - CODE from the scanline
                   7972:    $code - CODE to match against
                   7973: 
                   7974:  Returns:
                   7975:    $count - integer count of the number of same characters between the
                   7976:             two arguments
                   7977: 
1.423     albertel 7978: =cut
                   7979: 
1.194     albertel 7980: sub num_matches {
                   7981:     my ($orig,$code) = @_;
                   7982:     my @code=split(//,$code);
                   7983:     my @orig=split(//,$orig);
                   7984:     my $same=0;
                   7985:     for (my $i=0;$i<scalar(@code);$i++) {
                   7986: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7987:     }
                   7988:     return $same;
                   7989: }
                   7990: 
1.423     albertel 7991: =pod
                   7992: 
                   7993: =item scantron_get_closely_matching_CODEs
                   7994: 
1.424     albertel 7995:    Cycles through all CODEs and finds the set that has the greatest
                   7996:    number of same characters as the provided CODE
                   7997: 
                   7998:  Arguments:
                   7999:    $allcodes - hash ref returned by &get_codes()
                   8000:    $CODE     - CODE from the current scanline
                   8001: 
                   8002:  Returns:
                   8003:    2 element list
                   8004:     - first elements is number of how closely matching the best fit is 
                   8005:       (5 means best set has 5 matching characters)
                   8006:     - second element is an arrary ref containing the set of valid CODEs
                   8007:       that best fit the passed in CODE
                   8008: 
1.423     albertel 8009: =cut
                   8010: 
1.194     albertel 8011: sub scantron_get_closely_matching_CODEs {
                   8012:     my ($allcodes,$CODE)=@_;
                   8013:     my @CODEs;
                   8014:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8015: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8016:     }
                   8017: 
                   8018:     return ($#CODEs,$CODEs[-1]);
                   8019: }
                   8020: 
1.423     albertel 8021: =pod
                   8022: 
                   8023: =item get_codes
                   8024: 
1.424     albertel 8025:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8026:    set of remembered CODEs.
                   8027: 
                   8028:  Arguments:
                   8029:   $old_name - name of the set of remembered CODEs
                   8030:   $cdom     - domain of the course
                   8031:   $cnum     - internal course name
                   8032: 
                   8033:  Returns:
                   8034:   %allcodes - keys are the valid CODEs, values are all 1
                   8035: 
1.423     albertel 8036: =cut
                   8037: 
1.194     albertel 8038: sub get_codes {
1.280     foxr     8039:     my ($old_name, $cdom, $cnum) = @_;
                   8040:     if (!$old_name) {
                   8041: 	$old_name=$env{'form.scantron_CODElist'};
                   8042:     }
                   8043:     if (!$cdom) {
                   8044: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8045:     }
                   8046:     if (!$cnum) {
                   8047: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8048:     }
1.278     albertel 8049:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8050: 				    $cdom,$cnum);
                   8051:     my %allcodes;
                   8052:     if ($result{"type\0$old_name"} eq 'number') {
                   8053: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8054:     } else {
                   8055: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8056:     }
1.194     albertel 8057:     return %allcodes;
                   8058: }
                   8059: 
1.423     albertel 8060: =pod
                   8061: 
                   8062: =item scantron_validate_CODE
                   8063: 
1.424     albertel 8064:    Validates all scanlines in the selected file to not have any
                   8065:    invalid or underspecified CODEs and that none of the codes are
                   8066:    duplicated if this was requested.
                   8067: 
1.423     albertel 8068: =cut
                   8069: 
1.157     albertel 8070: sub scantron_validate_CODE {
                   8071:     my ($r,$currentphase) = @_;
1.257     albertel 8072:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8073:     if ($scantron_config{'CODElocation'} &&
                   8074: 	$scantron_config{'CODEstart'} &&
                   8075: 	$scantron_config{'CODElength'}) {
1.257     albertel 8076: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8077: 	    &FIXME_blow_up()
                   8078: 	}
                   8079:     } else {
                   8080: 	return (0,$currentphase+1);
                   8081:     }
                   8082:     
                   8083:     my %usedCODEs;
                   8084: 
1.194     albertel 8085:     my %allcodes=&get_codes();
1.186     albertel 8086: 
1.582     raeburn  8087:     my $nav_error;
1.596.2.12.2.  (raeburn 8088:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8089:     if ($nav_error) {
                   8090:         $r->print(&navmap_errormsg());
                   8091:         return(1,$currentphase);
                   8092:     }
1.447     foxr     8093: 
1.186     albertel 8094:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8095:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8096: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8097: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8098: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8099: 						 $scan_data);
                   8100: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8101: 	my $error=0;
1.224     albertel 8102: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8103: 	    &scantron_get_correction($r,$i,$scan_record,
                   8104: 				     \%scantron_config,
                   8105: 				     $line,'incorrectCODE',\%allcodes);
                   8106: 	    return(1,$currentphase);
                   8107: 	}
1.221     albertel 8108: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8109: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8110: 	    &scantron_get_correction($r,$i,$scan_record,
                   8111: 				     \%scantron_config,
1.194     albertel 8112: 				     $line,'incorrectCODE',\%allcodes);
                   8113: 	    return(1,$currentphase);
1.186     albertel 8114: 	}
1.214     albertel 8115: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8116: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8117: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8118: 	    &scantron_get_correction($r,$i,$scan_record,
                   8119: 				     \%scantron_config,
1.194     albertel 8120: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8121: 	    return(1,$currentphase);
1.186     albertel 8122: 	}
1.524     raeburn  8123: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8124:     }
1.157     albertel 8125:     return (0,$currentphase+1);
                   8126: }
                   8127: 
1.423     albertel 8128: =pod
                   8129: 
                   8130: =item scantron_validate_doublebubble
                   8131: 
1.424     albertel 8132:    Validates all scanlines in the selected file to not have any
                   8133:    bubble lines with multiple bubbles marked.
                   8134: 
1.423     albertel 8135: =cut
                   8136: 
1.157     albertel 8137: sub scantron_validate_doublebubble {
                   8138:     my ($r,$currentphase) = @_;
                   8139:     #get student info
                   8140:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8141:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8142:3):     my (undef,undef,$sequence)=
                   8143:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8144: 
                   8145:     #get scantron line setup
1.257     albertel 8146:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8147:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8148:3): 
                   8149:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8150:3):     unless (ref($navmap)) {
                   8151:3):         $r->print(&navmap_errormsg());
                   8152:3):         return(1,$currentphase);
                   8153:3):     }
                   8154:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8155:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8156:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8157:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8158:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8159:3): 
1.583     raeburn  8160:     my $nav_error;
1.596.2.12.2.  6(raebur 8161:3):     if (ref($map)) {
                   8162:3):         $randomorder = $map->randomorder();
                   8163:3):         $randompick = $map->randompick();
                   8164:3):         if ($randomorder || $randompick) {
                   8165:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8166:3):             if ($nav_error) {
                   8167:3):                 $r->print(&navmap_errormsg());
                   8168:3):                 return(1,$currentphase);
                   8169:3):             }
                   8170:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8171:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8172:3):         }
                   8173:3):     } else {
                   8174:3):         $r->print(&navmap_errormsg());
                   8175:3):         return(1,$currentphase);
                   8176:3):     }
                   8177:3): 
          (raeburn 8178:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8179:     if ($nav_error) {
                   8180:         $r->print(&navmap_errormsg());
                   8181:         return(1,$currentphase);
                   8182:     }
1.447     foxr     8183: 
1.157     albertel 8184:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8185: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8186: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8187: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8188:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8189:3):                                                  $randompick,$sequence,\@master_seq,
                   8190:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8191:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8192: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8193: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8194: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8195:3): 				 $$scan_record{'scantron.doubleerror'},
                   8196:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8197:     	return (1,$currentphase);
                   8198:     }
                   8199:     return (0,$currentphase+1);
                   8200: }
                   8201: 
1.423     albertel 8202: 
1.503     raeburn  8203: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8204:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8205:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8206: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8207: 	&restore_bubble_lines();
1.257     albertel 8208: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8209:     }
1.330     albertel 8210: 
1.447     foxr     8211:     my (undef, undef, $sequence) =
1.257     albertel 8212: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8213: 
1.447     foxr     8214:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8215:     unless (ref($navmap)) {
                   8216:         if (ref($nav_error)) {
                   8217:             $$nav_error = 1;
                   8218:         }
1.591     raeburn  8219:         return;
1.582     raeburn  8220:     }
1.191     albertel 8221:     my $map=$navmap->getResourceByUrl($sequence);
                   8222:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8223:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8224: 
                   8225:     &Apache::lonxml::clear_problem_counter();
                   8226: 
1.557     raeburn  8227:     my $uname       = $env{'user.name'};
                   8228:     my $udom        = $env{'user.domain'};
1.435     foxr     8229:     my $cid         = $env{'request.course.id'};
                   8230:     my $total_lines = 0;
                   8231:     %bubble_lines_per_response = ();
1.447     foxr     8232:     %first_bubble_line         = ();
1.503     raeburn  8233:     %subdivided_bubble_lines   = ();
                   8234:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8235:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8236: 
1.447     foxr     8237:     my $response_number = 0;
                   8238:     my $bubble_line     = 0;
1.191     albertel 8239:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8240:3):         my $resid = $resource->id();
          (raeburn 8241:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8242:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8243:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8244: 	    foreach my $part_id (@{$parts}) {
                   8245:                 my $lines;
                   8246: 
                   8247: 	        # TODO - make this a persistent hash not an array.
                   8248: 
                   8249:                 # optionresponse, matchresponse and rankresponse type items 
                   8250:                 # render as separate sub-questions in exam mode.
                   8251:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8252:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8253:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8254:                     my ($numbub,$numshown);
                   8255:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8256:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8257:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8258:                         }
                   8259:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8260:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8261:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8262:                         }
                   8263:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8264:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8265:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8266:                         }
                   8267:                     }
                   8268:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8269:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8270:                     }
1.596.2.12.2.  (raeburn 8271:):                     my $bubbles_per_row =
                   8272:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8273:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8274:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8275:                         $inner_bubble_lines++;
                   8276:                     }
                   8277:                     for (my $i=0; $i<$numshown; $i++) {
                   8278:                         $subdivided_bubble_lines{$response_number} .= 
                   8279:                             $inner_bubble_lines.',';
                   8280:                     }
                   8281:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8282:                     $lines = $numshown * $inner_bubble_lines;
                   8283:                 } else {
                   8284:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8285:):                 }
1.542     raeburn  8286: 
                   8287:                 $first_bubble_line{$response_number} = $bubble_line;
                   8288: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8289:                 $responsetype_per_response{$response_number} = 
                   8290:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8291:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8292: 	        $response_number++;
                   8293: 
                   8294: 	        $bubble_line +=  $lines;
                   8295: 	        $total_lines +=  $lines;
                   8296: 	    }
                   8297:         }
                   8298:     }
1.552     raeburn  8299:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8300: 
                   8301:     &save_bubble_lines();
                   8302:     $env{'form.scantron_maxbubble'} =
                   8303: 	$total_lines;
                   8304:     return $env{'form.scantron_maxbubble'};
                   8305: }
1.523     raeburn  8306: 
1.596.2.12.2.  (raeburn 8307:): sub bubblesheet_bubbles_per_row {
                   8308:):     my ($scantron_config) = @_;
                   8309:):     my $bubbles_per_row;
                   8310:):     if (ref($scantron_config) eq 'HASH') {
                   8311:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8312:):     }
                   8313:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8314:):         $bubbles_per_row = 10;
                   8315:):     }
                   8316:):     return $bubbles_per_row;
                   8317:): }
                   8318:): 
1.157     albertel 8319: sub scantron_validate_missingbubbles {
                   8320:     my ($r,$currentphase) = @_;
                   8321:     #get student info
                   8322:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8323:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8324:3):     my (undef,undef,$sequence)=
                   8325:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8326: 
                   8327:     #get scantron line setup
1.257     albertel 8328:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8329:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8330:3): 
                   8331:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8332:3):     unless (ref($navmap)) {
                   8333:3):         $r->print(&navmap_errormsg());
                   8334:3):         return(1,$currentphase);
                   8335:3):     }
                   8336:3): 
                   8337:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8338:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8339:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8340:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8341:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8342:3): 
1.582     raeburn  8343:     my $nav_error;
1.596.2.12.2.  6(raebur 8344:3):     if (ref($map)) {
                   8345:3):         $randomorder = $map->randomorder();
                   8346:3):         $randompick = $map->randompick();
          7(raebur 8347:3):         if ($randomorder || $randompick) {
                   8348:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8349:3):             if ($nav_error) {
                   8350:3):                 $r->print(&navmap_errormsg());
                   8351:3):                 return(1,$currentphase);
                   8352:3):             }
                   8353:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8354:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8355:3):         }
          6(raebur 8356:3):     } else {
                   8357:3):         $r->print(&navmap_errormsg());
          7(raebur 8358:3):         return(1,$currentphase);
          6(raebur 8359:3):     }
                   8360:3): 
                   8361:3): 
          (raeburn 8362:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8363:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8364:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8365:         return(1,$currentphase);
                   8366:     }
1.596.2.12.2.  6(raebur 8367:3): 
1.157     albertel 8368:     if (!$max_bubble) { $max_bubble=2**31; }
                   8369:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8370: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8371: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8372:3):         my $scan_record =
                   8373:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8374:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8375:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8376:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8377: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8378: 	my @to_correct;
1.470     foxr     8379: 	
                   8380: 	# Probably here's where the error is...
                   8381: 
1.157     albertel 8382: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8383:             my $lastbubble;
                   8384:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8385:3):                 my $question = $1;
                   8386:3):                 my $subquestion = $2;
                   8387:3):                 my ($first,$responsenum);
                   8388:3):                 if ($randomorder || $randompick) {
                   8389:3):                     $responsenum = $respnumlookup{$question-1};
                   8390:3):                     $first = $startline{$question-1};
                   8391:3):                 } else {
                   8392:3):                     $responsenum = $question-1;
                   8393:3):                     $first = $first_bubble_line{$responsenum};
                   8394:3):                 }
                   8395:3):                 if (!defined($first)) { next; }
          7(raebur 8396:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8397:3):                 my $subcount = 1;
                   8398:3):                 while ($subcount<$subquestion) {
                   8399:3):                     $first += $subans[$subcount-1];
                   8400:3):                     $subcount ++;
                   8401:3):                 }
                   8402:3):                 my $count = $subans[$subquestion-1];
                   8403:3):                 $lastbubble = $first + $count;
1.505     raeburn  8404:             } else {
1.596.2.12.2.  6(raebur 8405:3):                 my ($first,$responsenum);
                   8406:3):                 if ($randomorder || $randompick) {
                   8407:3):                     $responsenum = $respnumlookup{$missing-1};
                   8408:3):                     $first = $startline{$missing-1};
                   8409:3):                 } else {
                   8410:3):                     $responsenum = $missing-1;
                   8411:3):                     $first = $first_bubble_line{$responsenum};
                   8412:3):                 }
                   8413:3):                 if (!defined($first)) { next; }
                   8414:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8415:             }
                   8416:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8417: 	    push(@to_correct,$missing);
                   8418: 	}
                   8419: 	if (@to_correct) {
                   8420: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8421:3): 				     $line,'missingbubble',\@to_correct,
                   8422:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8423:3):                                      \%startline);
1.157     albertel 8424: 	    return (1,$currentphase);
                   8425: 	}
                   8426: 
                   8427:     }
                   8428:     return (0,$currentphase+1);
                   8429: }
                   8430: 
1.596.2.12.2.  (raeburn 8431:): sub hand_bubble_option {
                   8432:):     my (undef, undef, $sequence) =
                   8433:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8434:):     return if ($sequence eq '');
                   8435:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8436:):     unless (ref($navmap)) {
                   8437:):         return;
                   8438:):     }
                   8439:):     my $needs_hand_bubbles;
                   8440:):     my $map=$navmap->getResourceByUrl($sequence);
                   8441:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8442:):     foreach my $res (@resources) {
                   8443:):         if (ref($res)) {
                   8444:):             if ($res->is_problem()) {
                   8445:):                 my $partlist = $res->parts();
                   8446:):                 foreach my $part (@{ $partlist }) {
                   8447:):                     my @types = $res->responseType($part);
                   8448:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8449:):                         $needs_hand_bubbles = 1;
                   8450:):                         last;
                   8451:):                     }
                   8452:):                 }
                   8453:):             }
                   8454:):         }
                   8455:):     }
                   8456:):     if ($needs_hand_bubbles) {
                   8457:):         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8458:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8459:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8460:):                &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 />').
                   8461:):                '<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;'.
          8(raebur 8462:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8463:):     }
                   8464:):     return;
                   8465:): }
1.423     albertel 8466: 
1.82      albertel 8467: sub scantron_process_students {
1.75      albertel 8468:     my ($r) = @_;
1.513     foxr     8469: 
1.257     albertel 8470:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 8471:     my ($symb)=&get_symb($r);
1.513     foxr     8472:     if (!$symb) {
                   8473: 	return '';
                   8474:     }
1.324     albertel 8475:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8476: 
1.257     albertel 8477:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.596.2.12.2.  6(raebur 8478:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8479:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8480:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8481:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8482:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8483:     unless (ref($navmap)) {
                   8484:         $r->print(&navmap_errormsg());
                   8485:         return '';
1.596.2.12.2.  6(raebur 8486:3):     }
1.83      albertel 8487:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8488:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8489:3):         %grader_randomlists_by_symb);
          1(raebur 8490:2):     if (ref($map)) {
                   8491:2):         $randomorder = $map->randomorder();
          6(raebur 8492:3):         $randompick = $map->randompick();
                   8493:3):     } else {
                   8494:3):         $r->print(&navmap_errormsg());
                   8495:3):         return '';
          1(raebur 8496:2):     }
          6(raebur 8497:3):     my $nav_error;
1.83      albertel 8498:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8499:3):     if ($randomorder || $randompick) {
                   8500:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8501:3):         if ($nav_error) {
                   8502:3):             $r->print(&navmap_errormsg());
                   8503:3):             return '';
1.586     raeburn  8504:         }
                   8505:     }
1.596.2.12.2.  6(raebur 8506:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8507:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8508: 
1.554     raeburn  8509:     my ($uname,$udom);
1.82      albertel 8510:     my $result= <<SCANTRONFORM;
1.81      albertel 8511: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8512:   <input type="hidden" name="command" value="scantron_configphase" />
                   8513:   $default_form_data
                   8514: SCANTRONFORM
1.82      albertel 8515:     $r->print($result);
                   8516: 
                   8517:     my @delayqueue;
1.542     raeburn  8518:     my (%completedstudents,%scandata);
1.140     albertel 8519:     
1.520     www      8520:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8521:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8522:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.140     albertel 8523:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8524: 					  'Processing first student');
1.542     raeburn  8525:     $r->print('<br />');
1.140     albertel 8526:     my $start=&Time::HiRes::time();
1.158     albertel 8527:     my $i=-1;
1.542     raeburn  8528:     my $started;
1.447     foxr     8529: 
1.596.2.12.2.  (raeburn 8530:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8531:     if ($nav_error) {
                   8532:         $r->print(&navmap_errormsg());
                   8533:         return '';
                   8534:     }
                   8535: 
1.513     foxr     8536:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8537:     # the user and return.
                   8538: 
                   8539:     if ($ssi_error) {
                   8540: 	$r->print("</form>");
                   8541: 	&ssi_print_error($r);
                   8542: 	$r->print(&show_grading_menu_form($symb));
1.520     www      8543:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8544: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8545:     }
1.447     foxr     8546: 
1.542     raeburn  8547:     my %lettdig = &letter_to_digits();
                   8548:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8549:3):     my %orderedforcode;
1.542     raeburn  8550: 
1.157     albertel 8551:     while ($i<$scanlines->{'count'}) {
                   8552:  	($uname,$udom)=('','');
                   8553:  	$i++;
1.200     albertel 8554:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8555:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8556: 	if ($started) {
                   8557: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8558: 						     'last student');
                   8559: 	}
                   8560: 	$started=1;
1.596.2.12.2.  6(raebur 8561:3):         my %respnumlookup = ();
                   8562:3):         my %startline = ();
                   8563:3):         my $total;
1.157     albertel 8564:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8565:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8566:3):                                                  $randompick,$sequence,\@master_seq,
                   8567:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8568:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8569:3):                                                  \$total);
1.157     albertel 8570:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8571:  					      \%idmap,$i)) {
                   8572:   	    &scantron_add_delay(\@delayqueue,$line,
                   8573:  				'Unable to find a student that matches',1);
                   8574:  	    next;
                   8575:   	}
                   8576:  	if (exists $completedstudents{$uname}) {
                   8577:  	    &scantron_add_delay(\@delayqueue,$line,
                   8578:  				'Student '.$uname.' has multiple sheets',2);
                   8579:  	    next;
                   8580:  	}
1.596.2.12.2.  1(raebur 8581:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8582:2):         my $user = $uname.':'.$usec;
1.157     albertel 8583:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8584: 
1.596.2.12.2.  1(raebur 8585:2):         my $scancode;
                   8586:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8587:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8588:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8589:2):         } else {
                   8590:2):             $scancode = '';
                   8591:2):         }
                   8592:2): 
                   8593:2):         my @mapresources = @resources;
          6(raebur 8594:3):         if ($randomorder || $randompick) {
          1(raebur 8595:2):             @mapresources =
          6(raebur 8596:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8597:3):                              \%orderedforcode);
          1(raebur 8598:2):         }
1.586     raeburn  8599:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8600:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8601:             my $ressymb;
                   8602:             if (ref($resource)) {
                   8603:                 $ressymb = $resource->symb();
                   8604:             } else {
                   8605:                 $res_error = 1;
                   8606:                 last;
                   8607:             }
1.557     raeburn  8608:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8609:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8610:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8611:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8612:):                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8613:                 $partids_by_symb{$ressymb} = $parts;
                   8614:             } else {
                   8615:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8616:             }
1.554     raeburn  8617:         }
                   8618: 
1.586     raeburn  8619:         if ($res_error) {
                   8620:             &scantron_add_delay(\@delayqueue,$line,
                   8621:                                 'An error occurred while grading student '.$uname,2);
                   8622:             next;
                   8623:         }
                   8624: 
1.330     albertel 8625: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8626:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8627: 
                   8628: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8629: 	    &scantron_putfile($scanlines,$scan_data);
                   8630: 	}
1.161     albertel 8631: 	
1.542     raeburn  8632:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8633:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8634:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8635:3):                                    \%respnumlookup,\%startline) 
                   8636:3):             eq 'ssi_error') {
1.542     raeburn  8637:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8638:             $r->print("</form>");
                   8639:             &ssi_print_error($r);
                   8640:             $r->print(&show_grading_menu_form($symb));
                   8641:             &Apache::lonnet::remove_lock($lock);
                   8642:             return '';      # Why return ''?  Beats me.
                   8643:         }
1.513     foxr     8644: 
1.596.2.12.2.  6(raebur 8645:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8646:3):             my $parmresult =
                   8647:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8648:3):                                                        '0_examcode',2,$scancode,
                   8649:3):                                                        'string_examcode',$uname,
                   8650:3):                                                        $udom);
                   8651:3):         }
1.140     albertel 8652: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8653:         if ($env{'form.verifyrecord'}) {
                   8654:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8655:3):             if ($randompick) {
                   8656:3):                 if ($total) {
                   8657:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8658:3):                 }
                   8659:3):             }
                   8660:3): 
1.542     raeburn  8661:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8662:             chomp($studentdata);
                   8663:             $studentdata =~ s/\r$//;
                   8664:             my $studentrecord = '';
                   8665:             my $counter = -1;
1.596.2.12.2.  1(raebur 8666:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8667:                 my $ressymb = $resource->symb();
1.542     raeburn  8668:                 ($counter,my $recording) =
                   8669:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8670:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8671:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8672:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8673:                 $studentrecord .= $recording;
                   8674:             }
                   8675:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8676:                 &Apache::lonxml::clear_problem_counter();
                   8677:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8678:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8679:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8680:3):                                            \%respnumlookup,\%startline)
                   8681:3):                     eq 'ssi_error') {
1.554     raeburn  8682:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8683:                     $r->print("</form>");
                   8684:                     &ssi_print_error($r);
                   8685:                     $r->print(&show_grading_menu_form($symb));
                   8686:                     &Apache::lonnet::remove_lock($lock);
                   8687:                     delete($completedstudents{$uname});
                   8688:                     return '';
                   8689:                 }
1.542     raeburn  8690:                 $counter = -1;
                   8691:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8692:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8693:                     my $ressymb = $resource->symb();
1.542     raeburn  8694:                     ($counter,my $recording) =
                   8695:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8696:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8697:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8698:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8699:3):                                                  \%startline);
1.542     raeburn  8700:                     $studentrecord .= $recording;
                   8701:                 }
                   8702:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8703:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8704:                     if ($scancode eq '') {
1.596.2.6  raeburn  8705:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8706:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8707:                     } else {
1.596.2.6  raeburn  8708:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8709:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8710:                     }
                   8711:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8712:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8713:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8714:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8715:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8716:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8717:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8718:                               &Apache::loncommon::end_data_table_row().
                   8719:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8720:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8721:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8722:                               &Apache::loncommon::end_data_table_row().
                   8723:                               &Apache::loncommon::end_data_table().'</p>');
                   8724:                 } else {
                   8725:                     $r->print('<br /><span class="LC_warning">'.
                   8726:                              &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 />'.
                   8727:                              &mt("As a consequence, this user's submission history records two tries.").
                   8728:                                  '</span><br />');
                   8729:                 }
                   8730:             }
                   8731:         }
1.543     raeburn  8732:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8733:     } continue {
1.330     albertel 8734: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8735: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8736:     }
1.140     albertel 8737:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8738:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8739: #    my $lasttime = &Time::HiRes::time()-$start;
                   8740: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8741: 
1.200     albertel 8742:     $r->print("</form>");
1.324     albertel 8743:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8744:     return '';
1.75      albertel 8745: }
1.157     albertel 8746: 
1.557     raeburn  8747: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8748:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8749:):         $bubbles_per_row) = @_;
1.557     raeburn  8750:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8751:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8752:         foreach my $resource (@{$resources}) {
                   8753:             my $ressymb = $resource->symb();
                   8754:             my ($analysis,$parts) =
                   8755:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8756:):                                           $env{'user.name'},$env{'user.domain'},
                   8757:):                                           1,$bubbles_per_row);
1.557     raeburn  8758:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8759:             if (ref($analysis) eq 'HASH') {
                   8760:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8761:                     $grader_randomlists_by_symb->{$ressymb} =
                   8762:                         $analysis->{'parts_withrandomlist'};
                   8763:                 }
                   8764:             }
                   8765:         }
                   8766:     }
                   8767:     return;
                   8768: }
                   8769: 
1.596.2.12.2.  1(raebur 8770:2): =pod
                   8771:2): 
                   8772:2): =item users_order
                   8773:2): 
                   8774:2):   Returns array of resources in current map, ordered based on either CODE,
                   8775:2):   if this is a CODEd exam, or based on student's identity if this is a
                   8776:2):   "NAMEd" exam.
                   8777:2): 
          6(raebur 8778:3):   Should be used when randomorder and/or randompick applied when the 
                   8779:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   8780:3):   for the version of the exam the student received.
          1(raebur 8781:2): 
                   8782:2): =cut
                   8783:2): 
                   8784:2): sub users_order  {
          6(raebur 8785:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 8786:2):     my @mapresources;
          6(raebur 8787:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 8788:2):         return @mapresources;
                   8789:2):     }
          6(raebur 8790:3):     if ($scancode) {
                   8791:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8792:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   8793:3):         } else {
                   8794:3):             $env{'form.CODE'} = $scancode;
                   8795:3):             my $actual_seq =
                   8796:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8797:3):                                                                $master_seq,
                   8798:3):                                                                $user,$scancode,1);
                   8799:3):             if (ref($actual_seq) eq 'ARRAY') {
                   8800:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8801:3):                 if (ref($orderedforcode) eq 'HASH') {
                   8802:3):                     if (@mapresources > 0) {
                   8803:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   8804:3):                     }
                   8805:3):                 }
                   8806:3):             }
                   8807:3):             delete($env{'form.CODE'});
          1(raebur 8808:2):         }
                   8809:2):     } else {
                   8810:2):         my $actual_seq =
                   8811:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8812:2):                                                            $master_seq,
          5(raebur 8813:3):                                                            $user,undef,1);
          1(raebur 8814:2):         if (ref($actual_seq) eq 'ARRAY') {
                   8815:2):             @mapresources =
                   8816:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8817:2):         }
          6(raebur 8818:3):     }
                   8819:3):     return @mapresources;
          1(raebur 8820:2): }
                   8821:2): 
1.542     raeburn  8822: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 8823:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8824:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8825:3):     my $uselookup = 0;
                   8826:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8827:3):         (ref($startline) eq 'HASH')) {
                   8828:3):         $uselookup = 1;
                   8829:3):     }
                   8830:3): 
1.554     raeburn  8831:     if (ref($resources) eq 'ARRAY') {
                   8832:         my $count = 0;
                   8833:         foreach my $resource (@{$resources}) {
                   8834:             my $ressymb = $resource->symb();
                   8835:             my %form = ('submitted'      => 'scantron',
                   8836:                         'grade_target'   => 'grade',
                   8837:                         'grade_username' => $uname,
                   8838:                         'grade_domain'   => $udom,
                   8839:                         'grade_courseid' => $env{'request.course.id'},
                   8840:                         'grade_symb'     => $ressymb,
                   8841:                         'CODE'           => $scancode
                   8842:                        );
1.596.2.12.2.  (raeburn 8843:):             if ($bubbles_per_row ne '') {
                   8844:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8845:):             }
                   8846:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8847:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8848:):             }
1.554     raeburn  8849:             if (ref($parts) eq 'HASH') {
                   8850:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8851:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 8852:3):                         if ($uselookup) {
                   8853:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8854:3):                         } else {
                   8855:3):                             $form{'scantron_questnum_start.'.$part} =
                   8856:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8857:3):                         }
1.554     raeburn  8858:                         $count++;
                   8859:                     }
                   8860:                 }
                   8861:             }
                   8862:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8863:             return 'ssi_error' if ($ssi_error);
                   8864:             last if (&Apache::loncommon::connection_aborted($r));
                   8865:         }
1.542     raeburn  8866:     }
                   8867:     return;
                   8868: }
                   8869: 
1.157     albertel 8870: sub scantron_upload_scantron_data {
                   8871:     my ($r)=@_;
1.565     raeburn  8872:     my $dom = $env{'request.role.domain'};
                   8873:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8874:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8875:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8876: 							  'domainid',
1.565     raeburn  8877: 							  'coursename',$dom);
                   8878:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 8879:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   8880:):     my ($symb) = &get_symb($r,1);
                   8881:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8882:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8883:     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.492     albertel 8884:     $r->print('
1.157     albertel 8885: <script type="text/javascript" language="javascript">
                   8886:     function checkUpload(formname) {
                   8887: 	if (formname.upfile.value == "") {
1.579     raeburn  8888: 	    alert("'.$nofile_alert.'");
1.157     albertel 8889: 	    return false;
                   8890: 	}
1.565     raeburn  8891:         if (formname.courseid.value == "") {
1.579     raeburn  8892:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8893:             return false;
                   8894:         }
1.157     albertel 8895: 	formname.submit();
                   8896:     }
1.565     raeburn  8897: 
                   8898:     function ToSyllabus() {
                   8899:         var cdom = '."'$dom'".';
                   8900:         var cnum = document.rules.courseid.value;
                   8901:         if (cdom == "" || cdom == null) {
                   8902:             return;
                   8903:         }
                   8904:         if (cnum == "" || cnum == null) {
                   8905:            return;
                   8906:         }
                   8907:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8908:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8909:         return;
                   8910:     }
                   8911: 
1.157     albertel 8912: </script>
                   8913: 
1.596.2.4  raeburn  8914: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8915: 
1.492     albertel 8916: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8917: '.$default_form_data.
                   8918:   &Apache::lonhtmlcommon::start_pick_box().
                   8919:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8920:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8921:   &Apache::lonhtmlcommon::row_closure().
                   8922:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8923:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8924:   &Apache::lonhtmlcommon::row_closure().
                   8925:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8926:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8927:   &Apache::lonhtmlcommon::row_closure().
                   8928:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8929:   '<input type="file" name="upfile" size="50" />'.
                   8930:   &Apache::lonhtmlcommon::row_closure(1).
                   8931:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8932: 
1.492     albertel 8933: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8934: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8935: </form>
1.492     albertel 8936: ');
1.157     albertel 8937:     return '';
                   8938: }
                   8939: 
1.423     albertel 8940: 
1.157     albertel 8941: sub scantron_upload_scantron_data_save {
                   8942:     my($r)=@_;
1.324     albertel 8943:     my ($symb)=&get_symb($r,1);
1.182     albertel 8944:     my $doanotherupload=
                   8945: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8946: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8947: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8948: 	'</form>'."\n";
1.257     albertel 8949:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8950: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8951: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8952: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8953: 	if ($symb) {
1.324     albertel 8954: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8955: 	} else {
                   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.596.2.12.2.  5(raebur 8962:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 8963:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 8964:3):         $r->print(
                   8965:3):             &Apache::lonhtmlcommon::confirm_success(
                   8966:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8967:3):                         '<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'});
                   8972: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 8973:3):             $r->print(
                   8974:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8975:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8976:3):                         (length($env{'form.upfile'})-1),
                   8977:3):                         '<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.210     albertel 8981: 	} else {
1.596.2.12.2.  5(raebur 8982:3):             $r->print(
                   8983:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8984:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8985:3):                           $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.209     ng       8990: 	$r->print(&scantron_selectphase($r,$uploadedfile));
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.596.2.12.2.  5(raebur 9007:3):         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.596.2.12.2.  5(raebur 9050:3):                     $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.596.2.12.2.  5(raebur 9069:3):             $output .= '<br />';
                   9070:3):             if ($found_match_count == $max_match_count) {
                   9071:3):                 # 100% matching entries
                   9072:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9073:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9074:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9075:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9076:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9077:3):                     ' in the file (for the format defined for [_3]).',
                   9078:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9079:3):             } else {
                   9080:3):                 # Not all entries matching? -> Show warning and additional info
                   9081:3):                 $output .=
                   9082:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9083:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9084:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9085:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9086:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9087:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9088:3):                         ' in the file (for the format defined for [_3]).',
                   9089:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9090:3):                     '<p class="LC_info">'.
                   9091:3):                     &mt('A low percentage of matches results from one of the following:').
                   9092:3):                     '</p><ul>'.
                   9093:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9094:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9095:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9096:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9097:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9098:3):                     '</ul>';
                   9099:3):             }
1.567     raeburn  9100:         }
                   9101:     } else {
1.596.2.12.2.  5(raebur 9102:3):         $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 {
                   9116:     my ($r)=@_;
1.596.2.12.2.  (raeburn 9117:):     my ($symb) = &get_symb($r,1);
                   9118:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9119:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9120:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9121:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9122:     if (! &valid_file($file)) {
1.492     albertel 9123: 	$r->print('
1.202     albertel 9124: 	<p>
1.596.2.12.2.  3(raebur 9125:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9126:         </p>
1.492     albertel 9127: ');
1.596.2.12.2.  (raeburn 9128:): 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 9129: 	return;
                   9130:     }
                   9131:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9132:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9133:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9134:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9135:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9136:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9137:     $r->print('
1.202     albertel 9138:     <p>
1.596.2.12.2.  8(raebur 9139:4): 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
1.492     albertel 9140: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9141:     </p>
                   9142:     <p>
1.492     albertel 9143: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9144: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9145:     </p>
                   9146:     <p>
1.492     albertel 9147: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9148: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9149:     </p>
1.492     albertel 9150: ');
1.596.2.12.2.  (raeburn 9151:):     $r->print(&show_grading_menu_form($symb));
1.202     albertel 9152:     return '';
                   9153: }
1.157     albertel 9154: 
1.523     raeburn  9155: sub checkscantron_results {
                   9156:     my ($r) = @_;
                   9157:     my ($symb)=&get_symb($r);
                   9158:     if (!$symb) {return '';}
                   9159:     my $grading_menu_button=&show_grading_menu_form($symb);
                   9160:     my $cid = $env{'request.course.id'};
1.542     raeburn  9161:     my %lettdig = &letter_to_digits();
1.523     raeburn  9162:     my $numletts = scalar(keys(%lettdig));
                   9163:     my $cnum = $env{'course.'.$cid.'.num'};
                   9164:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9165:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9166:     my %record;
                   9167:     my %scantron_config =
                   9168:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.596.2.12.2.  (raeburn 9169:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9170:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9171:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9172:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9173:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9174:     unless (ref($navmap)) {
                   9175:         $r->print(&navmap_errormsg());
                   9176:         return '';
                   9177:     }
1.523     raeburn  9178:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9179:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9180:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9181:2):     if (ref($map)) {
                   9182:2):         $randomorder=$map->randomorder();
          7(raebur 9183:3):         $randompick=$map->randompick();
          1(raebur 9184:2):     }
1.557     raeburn  9185:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9186:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9187:3):     if ($nav_error) {
                   9188:3):         $r->print(&navmap_errormsg());
                   9189:3):         return '';
          1(raebur 9190:2):     }
          (raeburn 9191:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9192:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9193:     my ($uname,$udom);
1.523     raeburn  9194:     my (%scandata,%lastname,%bylast);
                   9195:     $r->print('
                   9196: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9197: 
                   9198:     my @delayqueue;
                   9199:     my %completedstudents;
                   9200: 
1.596.2.12.2.  6(raebur 9201:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9202:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9203:3):     my ($username,$domain,$started);
          (raeburn 9204:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9205:     if ($nav_error) {
                   9206:         $r->print(&navmap_errormsg());
                   9207:         return '';
                   9208:     }
1.523     raeburn  9209: 
                   9210:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9211:                                           'Processing first student');
                   9212:     my $start=&Time::HiRes::time();
                   9213:     my $i=-1;
                   9214: 
                   9215:     while ($i<$scanlines->{'count'}) {
                   9216:         ($username,$domain,$uname)=('','','');
                   9217:         $i++;
                   9218:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9219:         if ($line=~/^[\s\cz]*$/) { next; }
                   9220:         if ($started) {
                   9221:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9222:                                                      'last student');
                   9223:         }
                   9224:         $started=1;
                   9225:         my $scan_record=
                   9226:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9227:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9228:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9229:3):                                               \%idmap,$i)) {
1.523     raeburn  9230:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9231:                                 'Unable to find a student that matches',1);
                   9232:             next;
                   9233:         }
                   9234:         if (exists $completedstudents{$uname}) {
                   9235:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9236:                                 'Student '.$uname.' has multiple sheets',2);
                   9237:             next;
                   9238:         }
                   9239:         my $pid = $scan_record->{'scantron.ID'};
                   9240:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9241:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9242:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9243:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9244:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9245:2): 
                   9246:2):         my $scancode;
                   9247:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9248:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9249:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9250:2):         } else {
                   9251:2):             $scancode = '';
                   9252:2):         }
                   9253:2): 
                   9254:2):         my @mapresources = @resources;
          6(raebur 9255:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9256:3):         my %respnumlookup=();
                   9257:3):         my %startline=();
                   9258:3):         if ($randomorder || $randompick) {
          1(raebur 9259:2):             @mapresources =
          6(raebur 9260:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9261:3):                              \%orderedforcode);
                   9262:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9263:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9264:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9265:3):                                              \%respnumlookup,\%startline);
                   9266:3):             if ($randompick && $total) {
                   9267:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9268:3):             }
          1(raebur 9269:2):         }
          6(raebur 9270:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9271:3):         chomp($scandata{$pid});
                   9272:3):         $scandata{$pid} =~ s/\r$//;
                   9273:3): 
1.523     raeburn  9274:         my $counter = -1;
1.596.2.12.2.  1(raebur 9275:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9276:             my $parts;
1.554     raeburn  9277:             my $ressymb = $resource->symb();
1.557     raeburn  9278:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9279:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9280:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9281:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9282:):                                               $username,$domain,undef,
                   9283:):                                               $bubbles_per_row);
1.557     raeburn  9284:             } else {
                   9285:                 $parts = $grader_partids_by_symb{$ressymb};
                   9286:             }
1.542     raeburn  9287:             ($counter,my $recording) =
                   9288:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9289:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9290:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9291:3):                                          $randomorder,$randompick,
                   9292:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9293:             $record{$pid} .= $recording;
1.523     raeburn  9294:         }
                   9295:     }
                   9296:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9297:     $r->print('<br />');
                   9298:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9299:     $passed = 0;
                   9300:     $failed = 0;
                   9301:     $numstudents = 0;
                   9302:     foreach my $last (sort(keys(%bylast))) {
                   9303:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9304:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9305:                 my $showscandata = $scandata{$pid};
                   9306:                 my $showrecord = $record{$pid};
                   9307:                 $showscandata =~ s/\s/&nbsp;/g;
                   9308:                 $showrecord =~ s/\s/&nbsp;/g;
                   9309:                 if ($scandata{$pid} eq $record{$pid}) {
                   9310:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9311:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9312: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9313: '</tr>'."\n".
                   9314: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9315:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9316:                     $passed ++;
                   9317:                 } else {
                   9318:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9319:                     $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  9320: '</tr>'."\n".
                   9321: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9322:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9323: '</tr>'."\n";
                   9324:                     $failed ++;
                   9325:                 }
                   9326:                 $numstudents ++;
                   9327:             }
                   9328:         }
                   9329:     }
1.596.2.4  raeburn  9330:     $r->print('<p>'.
1.596.2.8  raeburn  9331:               &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).',
1.596.2.4  raeburn  9332:                   '<b>',
                   9333:                   $numstudents,
                   9334:                   '</b>',
                   9335:                   $env{'form.scantron_maxbubble'}).
                   9336:               '</p>'
                   9337:     );
1.596.2.12.2.  2(raebur 9338:2):     $r->print('<p>'
                   9339:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9340:2):              .'<br />'
                   9341:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9342:2):              .'</p>');
1.523     raeburn  9343:     if ($passed) {
1.572     www      9344:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9345:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9346:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9347:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9348:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9349:                  $okstudents."\n".
                   9350:                  &Apache::loncommon::end_data_table().'<br />');
                   9351:     }
                   9352:     if ($failed) {
1.572     www      9353:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9354:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9355:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9356:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9357:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9358:                  $badstudents."\n".
                   9359:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9360:                  &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  9361:     }
                   9362:     $r->print('</form><br />'.$grading_menu_button);
                   9363:     return;
                   9364: }
                   9365: 
1.542     raeburn  9366: sub verify_scantron_grading {
1.554     raeburn  9367:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9368:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9369:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9370:     my ($record,%expected,%startpos);
                   9371:     return ($counter,$record) if (!ref($resource));
                   9372:     return ($counter,$record) if (!$resource->is_problem());
                   9373:     my $symb = $resource->symb();
1.554     raeburn  9374:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9375:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9376:         $counter ++;
                   9377:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9378:3):         my $respnum = $counter;
                   9379:3):         if ($randomorder || $randompick) {
                   9380:3):             $respnum = $respnumlookup->{$counter};
                   9381:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9382:3):         } else {
                   9383:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9384:3):         }
                   9385:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9386:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9387:             foreach my $item (@sub_lines) {
                   9388:                 $expected{$part_id} += $item;
                   9389:             }
                   9390:         } else {
1.596.2.12.2.  6(raebur 9391:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9392:         }
                   9393:     }
                   9394:     if ($symb) {
                   9395:         my %recorded;
                   9396:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9397:         if ($returnhash{'version'}) {
                   9398:             my %lasthash=();
                   9399:             my $version;
                   9400:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9401:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9402:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9403:                 }
                   9404:             }
                   9405:             foreach my $key (keys(%lasthash)) {
                   9406:                 if ($key =~ /\.scantron$/) {
                   9407:                     my $value = &unescape($lasthash{$key});
                   9408:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9409:                     if ($value eq '') {
                   9410:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9411:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9412:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9413:                             }
                   9414:                         }
                   9415:                     } else {
                   9416:                         my @tocheck;
                   9417:                         my @items = split(//,$value);
                   9418:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9419:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9420:                             if (@items < $expected{$part_id}) {
                   9421:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9422:                                 my @singles = split(//,$fragment);
                   9423:                                 foreach my $pos (@singles) {
                   9424:                                     if ($pos eq ' ') {
                   9425:                                         push(@tocheck,$pos);
                   9426:                                     } else {
                   9427:                                         my $next = shift(@items);
                   9428:                                         push(@tocheck,$next);
                   9429:                                     }
                   9430:                                 }
                   9431:                             } else {
                   9432:                                 @tocheck = @items;
                   9433:                             }
                   9434:                             foreach my $letter (@tocheck) {
                   9435:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9436:                                     if ($letter !~ /^[A-J]$/) {
                   9437:                                         $letter = $scantron_config->{'Qoff'};
                   9438:                                     }
                   9439:                                     $recorded{$part_id} .= $letter;
                   9440:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9441:                                     my $digit;
                   9442:                                     if ($letter !~ /^[A-J]$/) {
                   9443:                                         $digit = $scantron_config->{'Qoff'};
                   9444:                                     } else {
                   9445:                                         $digit = $lettdig->{$letter};
                   9446:                                     }
                   9447:                                     $recorded{$part_id} .= $digit;
                   9448:                                 }
                   9449:                             }
                   9450:                         } else {
                   9451:                             @tocheck = @items;
                   9452:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9453:                                 my $curr_sub = shift(@tocheck);
                   9454:                                 my $digit;
                   9455:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9456:                                     $digit = $lettdig->{$curr_sub}-1;
                   9457:                                 }
                   9458:                                 if ($curr_sub eq 'J') {
                   9459:                                     $digit += scalar($numletts);
                   9460:                                 }
                   9461:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9462:                                     if ($j == $digit) {
                   9463:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9464:                                     } else {
                   9465:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9466:                                     }
                   9467:                                 }
                   9468:                             }
                   9469:                         }
                   9470:                     }
                   9471:                 }
                   9472:             }
                   9473:         }
1.554     raeburn  9474:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9475:             if ($recorded{$part_id} eq '') {
                   9476:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9477:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9478:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9479:                     }
                   9480:                 }
                   9481:             }
                   9482:             $record .= $recorded{$part_id};
                   9483:         }
                   9484:     }
                   9485:     return ($counter,$record);
                   9486: }
                   9487: 
1.596.2.12.2.  6(raebur 9488:3): sub letter_to_digits {
1.542     raeburn  9489:     my %lettdig = (
                   9490:                     A => 1,
                   9491:                     B => 2,
                   9492:                     C => 3,
                   9493:                     D => 4,
                   9494:                     E => 5,
                   9495:                     F => 6,
                   9496:                     G => 7,
                   9497:                     H => 8,
                   9498:                     I => 9,
                   9499:                     J => 0,
                   9500:                   );
                   9501:     return %lettdig;
                   9502: }
                   9503: 
1.423     albertel 9504: 
1.75      albertel 9505: #-------- end of section for handling grading scantron forms -------
                   9506: #
                   9507: #-------------------------------------------------------------------
                   9508: 
1.72      ng       9509: #-------------------------- Menu interface -------------------------
                   9510: #
                   9511: #--- Show a Grading Menu button - Calls the next routine ---
                   9512: sub show_grading_menu_form {
1.324     albertel 9513:     my ($symb)=@_;
1.125     ng       9514:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 9515: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 9516: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       9517: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 9518: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       9519: 	'</form>'."\n";
                   9520:     return $result;
                   9521: }
                   9522: 
1.77      ng       9523: # -- Retrieve choices for grading form
                   9524: sub savedState {
                   9525:     my %savedState = ();
1.257     albertel 9526:     if ($env{'form.saveState'}) {
                   9527: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       9528: 	    my ($key,$value) = split(/=/,$_,2);
                   9529: 	    $savedState{$key} = $value;
                   9530: 	}
                   9531:     }
                   9532:     return \%savedState;
                   9533: }
1.76      ng       9534: 
1.596.2.12.2.  (raeburn 9535:): #--- Href with symb and command ---
                   9536:): 
                   9537:): sub href_symb_cmd {
                   9538:):     my ($symb,$cmd)=@_;
                   9539:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9540:): }
                   9541:): 
1.443     banghart 9542: sub grading_menu {
                   9543:     my ($request) = @_;
                   9544:     my ($symb)=&get_symb($request);
                   9545:     if (!$symb) {return '';}
                   9546:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   9547:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   9548: 
1.444     banghart 9549:     $request->print($table);
1.443     banghart 9550:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   9551:                   'handgrade'=>$hdgrade,
                   9552:                   'probTitle'=>$probTitle,
                   9553:                   'command'=>'submit_options',
                   9554:                   'saveState'=>"",
                   9555:                   'gradingMenu'=>1,
                   9556:                   'showgrading'=>"yes");
1.538     schulted 9557:     
                   9558:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9559:     
1.443     banghart 9560:     $fields{'command'} = 'csvform';
1.538     schulted 9561:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9562:     
1.443     banghart 9563:     $fields{'command'} = 'processclicker';
1.538     schulted 9564:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9565:     
1.443     banghart 9566:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9567:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9568:     
                   9569:     my @menu = ({	categorytitle=>'Course Grading',
                   9570:             items =>[
                   9571:                         {	linktext => 'Manual Grading/View Submissions',
                   9572:                     		url => $url1,
                   9573:                     		permission => 'F',
                   9574:                     		icon => 'edit-find-replace.png',
                   9575:                     		linktitle => 'Start the process of hand grading submissions.'
                   9576:                         },
                   9577:                 	    {	linktext => 'Upload Scores',
                   9578:                     		url => $url2,
                   9579:                     		permission => 'F',
                   9580:                     		icon => 'uploadscores.png',
                   9581:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9582:                 	    },
                   9583:                 	    {	linktext => 'Process Clicker',
                   9584:                     		url => $url3,
                   9585:                     		permission => 'F',
                   9586:                     		icon => 'addClickerInfoFile.png',
                   9587:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9588:                 	    },
1.587     raeburn  9589:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9590:                     		url => $url4,
                   9591:                     		permission => 'F',
                   9592:                     		icon => 'stat.png',
1.596.2.4  raeburn  9593:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 9594:                 	    }
                   9595:                     ]
                   9596:             });
                   9597: 
                   9598:     #$fields{'command'} = 'verify';
                   9599:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 9600:     #
                   9601:     # Create the menu
                   9602:     my $Str;
1.444     banghart 9603:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 9604:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9605:     $Str .= '<input type="hidden" name="command" value="" />'.
                   9606:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   9607: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 9608: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 9609: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   9610: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   9611: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9612: 
1.538     schulted 9613:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   9614:     #$menudata->{'jscript'}
1.584     bisitz   9615:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   9616:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 9617:         ' /> '.
                   9618:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   9619:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 9620: 
1.444     banghart 9621:     $Str .="</form>\n";
1.539     riegler  9622:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 9623:     $request->print(<<GRADINGMENUJS);
                   9624: <script type="text/javascript" language="javascript">
                   9625:     function checkChoice(formname,val,cmdx) {
                   9626: 	if (val <= 2) {
                   9627: 	    var cmd = radioSelection(formname.radioChoice);
                   9628: 	    var cmdsave = cmd;
                   9629: 	} else {
                   9630: 	    cmd = cmdx;
                   9631: 	    cmdsave = 'submission';
                   9632: 	}
                   9633: 	formname.command.value = cmd;
                   9634: 	if (val < 5) formname.submit();
                   9635: 	if (val == 5) {
1.458     banghart 9636: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   9637: 	        return false;
                   9638: 	    } else {
                   9639: 	        formname.submit();
                   9640: 	    }
1.445     banghart 9641: 	}
                   9642:     }
1.443     banghart 9643: 
                   9644:     function checkReceiptNo(formname,nospace) {
                   9645: 	var receiptNo = formname.receipt.value;
                   9646: 	var checkOpt = false;
                   9647: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9648: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9649: 	if (checkOpt) {
1.539     riegler  9650: 	    alert("$receiptalert");
1.443     banghart 9651: 	    formname.receipt.value = "";
                   9652: 	    formname.receipt.focus();
                   9653: 	    return false;
                   9654: 	}
                   9655: 	return true;
                   9656:     }
                   9657: </script>
                   9658: GRADINGMENUJS
                   9659:     &commonJSfunctions($request);
                   9660:     return $Str;    
                   9661: }
                   9662: 
                   9663: 
                   9664: #--- Displays the submissions first page -------
                   9665: sub submit_options {
1.72      ng       9666:     my ($request) = @_;
1.324     albertel 9667:     my ($symb)=&get_symb($request);
1.72      ng       9668:     if (!$symb) {return '';}
1.76      ng       9669:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       9670: 
1.539     riegler  9671:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       9672:     $request->print(<<GRADINGMENUJS);
                   9673: <script type="text/javascript" language="javascript">
1.116     ng       9674:     function checkChoice(formname,val,cmdx) {
                   9675: 	if (val <= 2) {
                   9676: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       9677: 	    var cmdsave = cmd;
1.116     ng       9678: 	} else {
                   9679: 	    cmd = cmdx;
1.118     ng       9680: 	    cmdsave = 'submission';
1.116     ng       9681: 	}
                   9682: 	formname.command.value = cmd;
1.118     ng       9683: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 9684: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       9685: 	if (val < 5) formname.submit();
                   9686: 	if (val == 5) {
1.72      ng       9687: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   9688: 	    formname.submit();
                   9689: 	}
1.238     albertel 9690: 	if (val < 7) formname.submit();
1.72      ng       9691:     }
                   9692: 
                   9693:     function checkReceiptNo(formname,nospace) {
                   9694: 	var receiptNo = formname.receipt.value;
                   9695: 	var checkOpt = false;
                   9696: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9697: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9698: 	if (checkOpt) {
1.539     riegler  9699: 	    alert("$receiptalert");
1.72      ng       9700: 	    formname.receipt.value = "";
                   9701: 	    formname.receipt.focus();
                   9702: 	    return false;
                   9703: 	}
                   9704: 	return true;
                   9705:     }
                   9706: </script>
                   9707: GRADINGMENUJS
1.118     ng       9708:     &commonJSfunctions($request);
1.324     albertel 9709:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 9710:     my $result;
1.76      ng       9711:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       9712:     my $savedState = &savedState();
1.118     ng       9713:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       9714:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       9715:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       9716:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       9717: 
1.533     bisitz   9718:     # Preselect sections
                   9719:     my $selsec="";
                   9720:     if (ref($sections)) {
                   9721:         foreach my $section (sort(@$sections)) {
                   9722:             $selsec.='<option value="'.$section.'" '.
                   9723:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   9724:         }
                   9725:     }
                   9726: 
1.72      ng       9727:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 9728: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       9729: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   9730: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       9731: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       9732: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       9733: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       9734: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9735: 
1.472     albertel 9736:     $result.='
1.533     bisitz   9737: <h2>
                   9738:   '.&mt('Grade Current Resource').'
                   9739: </h2>
                   9740: <div>
                   9741:   '.$table.'
                   9742: </div>
                   9743: 
1.537     harmsja  9744: <div class="LC_columnSection">
                   9745:   
1.533     bisitz   9746:     <fieldset>
                   9747:       <legend>
                   9748:        '.&mt('Sections').'
                   9749:       </legend>
                   9750:       <select name="section" multiple="multiple" size="5">'."\n";
                   9751:     $result.= $selsec;
1.401     albertel 9752:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 9753:     $result.='
1.533     bisitz   9754:     </fieldset>
1.537     harmsja  9755:   
1.533     bisitz   9756:     <fieldset>
                   9757:       <legend>
                   9758:         '.&mt('Groups').'
                   9759:       </legend>
                   9760:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9761:     </fieldset>
1.537     harmsja  9762:   
1.533     bisitz   9763:     <fieldset>
                   9764:       <legend>
                   9765:         '.&mt('Access Status').'
                   9766:       </legend>
                   9767:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   9768:     </fieldset>
1.537     harmsja  9769:   
1.533     bisitz   9770:     <fieldset>
                   9771:       <legend>
                   9772:         '.&mt('Submission Status').'
                   9773:       </legend>
                   9774:       <select name="submitonly" size="5">
1.473     albertel 9775: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   9776: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   9777: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   9778: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   9779:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   9780:       </select>
                   9781:     </fieldset>
1.537     harmsja  9782:   
1.533     bisitz   9783: </div>
                   9784: 
                   9785: <br />
                   9786:           <div>
                   9787:             <div>
1.473     albertel 9788:               <label>
                   9789:                 <input type="radio" name="radioChoice" value="submission" '.
                   9790:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   9791:              &mt('Select individual students to grade and view submissions.').'
                   9792: 	      </label> 
                   9793:             </div>
1.533     bisitz   9794:             <div>
1.473     albertel 9795: 	      <label>
                   9796:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   9797:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   9798:                     &mt('Grade all selected students in a grading table.').'
                   9799:               </label>
                   9800:             </div>
1.533     bisitz   9801:             <div>
1.589     bisitz   9802: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9803:             </div>
1.472     albertel 9804:           </div>
1.533     bisitz   9805: 
                   9806: 
1.473     albertel 9807:         <h2>
                   9808:          '.&mt('Grade Complete Folder for One Student').'
                   9809:         </h2>
1.533     bisitz   9810:         <div>
                   9811:             <div>
1.473     albertel 9812:               <label>
                   9813:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   9814: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   9815:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   9816:               </label>
                   9817:             </div>
1.533     bisitz   9818:             <div>
1.589     bisitz   9819: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9820:             </div>
1.472     albertel 9821:         </div>
                   9822:   </form>';
1.499     albertel 9823:     $result .= &show_grading_menu_form($symb);
1.44      ng       9824:     return $result;
1.2       albertel 9825: }
                   9826: 
1.285     albertel 9827: sub reset_perm {
                   9828:     undef(%perm);
                   9829: }
                   9830: 
                   9831: sub init_perm {
                   9832:     &reset_perm();
1.300     albertel 9833:     foreach my $test_perm ('vgr','mgr','opa') {
                   9834: 
                   9835: 	my $scope = $env{'request.course.id'};
                   9836: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9837: 
                   9838: 	    $scope .= '/'.$env{'request.course.sec'};
                   9839: 	    if ( $perm{$test_perm}=
                   9840: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9841: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9842: 	    } else {
                   9843: 		delete($perm{$test_perm});
                   9844: 	    }
1.285     albertel 9845: 	}
                   9846:     }
                   9847: }
                   9848: 
1.596.2.12.2.  (raeburn 9849:): sub init_old_essays {
                   9850:):     my ($symb,$apath,$adom,$aname) = @_;
                   9851:):     if ($symb ne '') {
                   9852:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9853:):         if (keys(%essays) > 0) {
                   9854:):             $old_essays{$symb} = \%essays;
                   9855:):         }
                   9856:):     }
                   9857:):     return;
                   9858:): }
                   9859:): 
                   9860:): sub reset_old_essays {
                   9861:):     undef(%old_essays);
                   9862:): }
                   9863:): 
1.400     www      9864: sub gather_clicker_ids {
1.408     albertel 9865:     my %clicker_ids;
1.400     www      9866: 
                   9867:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9868: 
                   9869:     # Set up a couple variables.
1.407     albertel 9870:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9871:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9872:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9873: 
1.407     albertel 9874:     foreach my $student (keys(%$classlist)) {
1.438     www      9875:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9876:         my $username = $classlist->{$student}->[$username_idx];
                   9877:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9878:         my $clickers =
1.408     albertel 9879: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9880:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9881:             $id=~s/^[\#0]+//;
1.421     www      9882:             $id=~s/[\-\:]//g;
1.407     albertel 9883:             if (exists($clicker_ids{$id})) {
1.408     albertel 9884: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9885:             } else {
1.408     albertel 9886: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9887:             }
                   9888:         }
                   9889:     }
1.407     albertel 9890:     return %clicker_ids;
1.400     www      9891: }
                   9892: 
1.402     www      9893: sub gather_adv_clicker_ids {
1.408     albertel 9894:     my %clicker_ids;
1.402     www      9895:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9896:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9897:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9898:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9899:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9900:             my ($puname,$pudom)=split(/\:/,$person);
                   9901:             my $clickers =
1.408     albertel 9902: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9903:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9904: 		$id=~s/^[\#0]+//;
1.421     www      9905:                 $id=~s/[\-\:]//g;
1.408     albertel 9906: 		if (exists($clicker_ids{$id})) {
                   9907: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9908: 		} else {
                   9909: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9910: 		}
1.405     www      9911:             }
1.402     www      9912:         }
                   9913:     }
1.407     albertel 9914:     return %clicker_ids;
1.402     www      9915: }
                   9916: 
1.413     www      9917: sub clicker_grading_parameters {
                   9918:     return ('gradingmechanism' => 'scalar',
                   9919:             'upfiletype' => 'scalar',
                   9920:             'specificid' => 'scalar',
                   9921:             'pcorrect' => 'scalar',
                   9922:             'pincorrect' => 'scalar');
                   9923: }
                   9924: 
1.400     www      9925: sub process_clicker {
                   9926:     my ($r)=@_;
                   9927:     my ($symb)=&get_symb($r);
                   9928:     if (!$symb) {return '';}
                   9929:     my $result=&checkforfile_js();
                   9930:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   9931:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   9932:     $result.=$table;
                   9933:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   9934:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 9935:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   9936:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  9937:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      9938: # Attempt to restore parameters from last session, set defaults if not present
                   9939:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9940:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9941:                                                  \%Saveable_Parameters);
                   9942:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9943:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9944:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9945:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9946: 
                   9947:     my %checked;
1.521     www      9948:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9949:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9950:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9951:        }
                   9952:     }
                   9953: 
1.400     www      9954:     my $upload=&mt("Upload File");
                   9955:     my $type=&mt("Type");
1.402     www      9956:     my $attendance=&mt("Award points just for participation");
                   9957:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9958:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9959:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9960:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9961:     my $pcorrect=&mt("Percentage points for correct solution");
                   9962:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9963:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  9964:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 9965:):                                                     'interwrite' => 'interwrite PRS',
                   9966:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9967:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      9968:     $result.=<<ENDUPFORM;
1.402     www      9969: <script type="text/javascript">
                   9970: function sanitycheck() {
                   9971: // Accept only integer percentages
                   9972:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9973:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9974: // Find out grading choice
                   9975:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9976:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9977:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9978:       }
                   9979:    }
                   9980: // By default, new choice equals user selection
                   9981:    newgradingchoice=gradingchoice;
                   9982: // Not good to give more points for false answers than correct ones
                   9983:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9984:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9985:    }
                   9986: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9987:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9988:       document.forms.gradesupload.pcorrect.value=100;
                   9989:       document.forms.gradesupload.pincorrect.value=100;
                   9990:    }
                   9991: // If the values are different, cannot be attendance only
                   9992:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9993:        (gradingchoice=='attendance')) {
                   9994:        newgradingchoice='personnel';
                   9995:    }
                   9996: // Change grading choice to new one
                   9997:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9998:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9999:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10000:       } else {
                   10001:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10002:       }
                   10003:    }
                   10004: // Remember the old state
                   10005:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10006: }
                   10007: </script>
1.400     www      10008: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10009: <input type="hidden" name="symb" value="$symb" />
                   10010: <input type="hidden" name="command" value="processclickerfile" />
                   10011: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10012: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   10013: <input type="file" name="upfile" size="50" />
                   10014: <br /><label>$type: $selectform</label>
1.589     bisitz   10015: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   10016: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10017: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10018: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10019: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10020: <br />&nbsp;&nbsp;&nbsp;
                   10021: <input type="text" name="givenanswer" size="50" />
1.413     www      10022: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   10023: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   10024: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10025: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10026: </form>
                   10027: ENDUPFORM
                   10028:     $result.='</td></tr></table>'."\n".
                   10029:              '</td></tr></table><br /><br />'."\n";
                   10030:     $result.=&show_grading_menu_form($symb);
                   10031:     return $result;
                   10032: }
                   10033: 
                   10034: sub process_clicker_file {
                   10035:     my ($r)=@_;
                   10036:     my ($symb)=&get_symb($r);
                   10037:     if (!$symb) {return '';}
1.413     www      10038: 
                   10039:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10040:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10041:                                               \%Saveable_Parameters);
                   10042: 
1.400     www      10043:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      10044:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10045: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   10046: 	return $result.&show_grading_menu_form($symb);
1.404     www      10047:     }
1.522     www      10048:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10049:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   10050:         return $result.&show_grading_menu_form($symb);
                   10051:     }
1.522     www      10052:     my $foundgiven=0;
1.521     www      10053:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10054:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10055:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10056:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10057:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10058:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10059:         $foundgiven=$#answers+1;
1.521     www      10060:     }
1.407     albertel 10061:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10062:     my %correct_ids;
1.404     www      10063:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10064: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10065:     }
                   10066:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10067: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10068: 	   $correct_id=~tr/a-z/A-Z/;
                   10069: 	   $correct_id=~s/\s//gs;
                   10070: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10071:            $correct_id=~s/[\-\:]//g;
1.414     www      10072:            if ($correct_id) {
                   10073: 	      $correct_ids{$correct_id}='specified';
                   10074:            }
                   10075:         }
1.400     www      10076:     }
1.404     www      10077:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10078: 	$result.=&mt('Score based on attendance only');
1.521     www      10079:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10080:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10081:     } else {
1.408     albertel 10082: 	my $number=0;
1.411     www      10083: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10084: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10085: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10086: 	    if ($correct_ids{$id} eq 'specified') {
                   10087: 		$result.=&mt('specified');
                   10088: 	    } else {
                   10089: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10090: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10091: 	    }
                   10092: 	    $number++;
                   10093: 	}
1.411     www      10094:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10095:3):         if ($number==0) {
                   10096:3):             $result .=
                   10097:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10098:3):                      &mt('No IDs found to determine correct answer'),1);
                   10099:3):             return $result,.&show_grading_menu_form($symb);
                   10100:3):         }
1.404     www      10101:     }
1.405     www      10102:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10103:3):         $result .=
                   10104:3):             &Apache::lonhtmlcommon::confirm_success(
                   10105:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10106:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.405     www      10107:         return $result.&show_grading_menu_form($symb);
                   10108:     }
1.410     www      10109: 
                   10110: # Were able to get all the info needed, now analyze the file
                   10111: 
1.411     www      10112:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10113:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      10114:     my $heading=&mt('Scanning clicker file');
                   10115:     $result.=(<<ENDHEADER);
                   10116: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   10117: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  10118: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      10119: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10120: <input type="hidden" name="symb" value="$symb" />
                   10121: <input type="hidden" name="command" value="assignclickergrades" />
                   10122: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10123: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      10124: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10125: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10126: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10127: ENDHEADER
1.522     www      10128:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10129:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10130:     } 
1.408     albertel 10131:     my %responses;
                   10132:     my @questiontitles;
1.405     www      10133:     my $errormsg='';
                   10134:     my $number=0;
                   10135:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10136: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10137:     }
1.419     www      10138:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10139:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10140:     }
1.596.2.12.2.  (raeburn 10141:):     if ($env{'form.upfiletype'} eq 'turning') {
                   10142:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10143:):     }
1.411     www      10144:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10145:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10146:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10147:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10148:              '<br />';
1.522     www      10149:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10150:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   10151:        return $result.&show_grading_menu_form($symb);
                   10152:     } 
1.414     www      10153: # Remember Question Titles
                   10154: # FIXME: Possibly need delimiter other than ":"
                   10155:     for (my $i=0;$i<$number;$i++) {
                   10156:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10157:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10158:     }
1.411     www      10159:     my $correct_count=0;
                   10160:     my $student_count=0;
                   10161:     my $unknown_count=0;
1.414     www      10162: # Match answers with usernames
                   10163: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10164:     foreach my $id (keys(%responses)) {
1.410     www      10165:        if ($correct_ids{$id}) {
1.414     www      10166:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10167:           $correct_count++;
1.410     www      10168:        } elsif ($clicker_ids{$id}) {
1.437     www      10169:           if ($clicker_ids{$id}=~/\,/) {
                   10170: # More than one user with the same clicker!
                   10171:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   10172:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10173:                            "<select name='multi".$id."'>";
                   10174:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10175:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10176:              }
                   10177:              $result.='</select>';
                   10178:              $unknown_count++;
                   10179:           } else {
                   10180: # Good: found one and only one user with the right clicker
                   10181:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10182:              $student_count++;
                   10183:           }
1.410     www      10184:        } else {
1.411     www      10185:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   10186:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10187:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10188:                    "\n".&mt("Domain").": ".
                   10189:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  10190:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10191:           $unknown_count++;
1.410     www      10192:        }
1.405     www      10193:     }
1.412     www      10194:     $result.='<hr />'.
                   10195:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10196:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10197:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10198:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10199:        } elsif ($correct_count>1) {
1.414     www      10200:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10201:        }
                   10202:     }
1.428     www      10203:     if ($number<1) {
                   10204:        $errormsg.="Found no questions.";
                   10205:     }
1.412     www      10206:     if ($errormsg) {
                   10207:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10208:     } else {
                   10209:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10210:     }
                   10211:     $result.='</form></td></tr></table>'."\n".
1.410     www      10212:              '</td></tr></table><br /><br />'."\n";
1.404     www      10213:     return $result.&show_grading_menu_form($symb);
1.400     www      10214: }
                   10215: 
1.405     www      10216: sub iclicker_eval {
1.406     www      10217:     my ($questiontitles,$responses)=@_;
1.405     www      10218:     my $number=0;
                   10219:     my $errormsg='';
                   10220:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10221:         my %components=&Apache::loncommon::record_sep($line);
                   10222:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10223: 	if ($entries[0] eq 'Question') {
                   10224: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10225: 		$$questiontitles[$number]=$entries[$i];
                   10226: 		$number++;
                   10227: 	    }
                   10228: 	}
                   10229: 	if ($entries[0]=~/^\#/) {
                   10230: 	    my $id=$entries[0];
                   10231: 	    my @idresponses;
                   10232: 	    $id=~s/^[\#0]+//;
                   10233: 	    for (my $i=0;$i<$number;$i++) {
                   10234: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10235:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10236: 		push(@idresponses,$entries[$idx]);
                   10237: 	    }
                   10238: 	    $$responses{$id}=join(',',@idresponses);
                   10239: 	}
1.405     www      10240:     }
                   10241:     return ($errormsg,$number);
                   10242: }
                   10243: 
1.419     www      10244: sub interwrite_eval {
                   10245:     my ($questiontitles,$responses)=@_;
                   10246:     my $number=0;
                   10247:     my $errormsg='';
1.420     www      10248:     my $skipline=1;
                   10249:     my $questionnumber=0;
                   10250:     my %idresponses=();
1.419     www      10251:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10252:         my %components=&Apache::loncommon::record_sep($line);
                   10253:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10254:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10255:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10256:         next if $skipline;
                   10257:         if ($entries[0]!=$questionnumber) {
                   10258:            $questionnumber=$entries[0];
                   10259:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10260:            $number++;
1.419     www      10261:         }
1.420     www      10262:         my $id=$entries[4];
                   10263:         $id=~s/^[\#0]+//;
1.421     www      10264:         $id=~s/^v\d*\://i;
                   10265:         $id=~s/[\-\:]//g;
1.420     www      10266:         $idresponses{$id}[$number]=$entries[6];
                   10267:     }
1.524     raeburn  10268:     foreach my $id (keys(%idresponses)) {
1.420     www      10269:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10270:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10271:     }
                   10272:     return ($errormsg,$number);
                   10273: }
                   10274: 
1.596.2.12.2.  (raeburn 10275:): sub turning_eval {
                   10276:):     my ($questiontitles,$responses)=@_;
                   10277:):     my $number=0;
                   10278:):     my $errormsg='';
                   10279:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10280:):         my %components=&Apache::loncommon::record_sep($line);
                   10281:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10282:):         if ($#entries>$number) { $number=$#entries; }
                   10283:):         my $id=$entries[0];
                   10284:):         my @idresponses;
                   10285:):         $id=~s/^[\#0]+//;
                   10286:):         unless ($id) { next; }
                   10287:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10288:):             $entries[$idx]=~s/\,/\;/g;
                   10289:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10290:):             push(@idresponses,$entries[$idx]);
                   10291:):         }
                   10292:):         $$responses{$id}=join(',',@idresponses);
                   10293:):     }
                   10294:):     for (my $i=1; $i<=$number; $i++) {
                   10295:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10296:):     }
                   10297:):     return ($errormsg,$number);
                   10298:): }
                   10299:): 
1.414     www      10300: sub assign_clicker_grades {
                   10301:     my ($r)=@_;
                   10302:     my ($symb)=&get_symb($r);
                   10303:     if (!$symb) {return '';}
1.416     www      10304: # See which part we are saving to
1.582     raeburn  10305:     my $res_error;
                   10306:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10307:     if ($res_error) {
                   10308:         return &navmap_errormsg();
                   10309:     }
1.416     www      10310: # FIXME: This should probably look for the first handgradeable part
                   10311:     my $part=$$partlist[0];
                   10312: # Start screen output
1.596.2.10  raeburn  10313:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  10314: 
1.596.2.10  raeburn  10315:     $result .= '<br />'.
                   10316:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  10317:                &Apache::loncommon::start_data_table_header_row().
                   10318:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10319:                &Apache::loncommon::end_data_table_header_row().
                   10320:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      10321: 
1.414     www      10322: # Get correct result
                   10323: # FIXME: Possibly need delimiter other than ":"
                   10324:     my @correct=();
1.415     www      10325:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10326:     my $number=$env{'form.number'};
                   10327:     if ($gradingmechanism ne 'attendance') {
1.414     www      10328:        foreach my $key (keys(%env)) {
                   10329:           if ($key=~/^form\.correct\:/) {
                   10330:              my @input=split(/\,/,$env{$key});
                   10331:              for (my $i=0;$i<=$#input;$i++) {
                   10332:                  if (($correct[$i]) && ($input[$i]) &&
                   10333:                      ($correct[$i] ne $input[$i])) {
                   10334:                     $result.='<br /><span class="LC_warning">'.
                   10335:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10336:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10337:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10338:                     $correct[$i]=$input[$i];
                   10339:                  }
                   10340:              }
                   10341:           }
                   10342:        }
1.415     www      10343:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10344:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10345:              $result.='<br /><span class="LC_error">'.
                   10346:                       &mt('No correct result given for question "[_1]"!',
                   10347:                           $env{'form.question:'.$i}).'</span>';
                   10348:           }
                   10349:        }
1.596.2.4  raeburn  10350:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10351:     }
                   10352: # Start grading
1.415     www      10353:     my $pcorrect=$env{'form.pcorrect'};
                   10354:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10355:     my $storecount=0;
1.596.2.4  raeburn  10356:     my %users=();
1.415     www      10357:     foreach my $key (keys(%env)) {
1.420     www      10358:        my $user='';
1.415     www      10359:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10360:           $user=$1;
                   10361:        }
                   10362:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10363:           my $id=$1;
                   10364:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10365:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10366:           } elsif ($env{'form.multi'.$id}) {
                   10367:              $user=$env{'form.multi'.$id};
1.420     www      10368:           }
                   10369:        }
1.596.2.4  raeburn  10370:        if ($user) {
                   10371:           if ($users{$user}) {
                   10372:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10373:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10374:                       '</span><br />';
                   10375:           }
                   10376:           $users{$user}=1;
1.415     www      10377:           my @answer=split(/\,/,$env{$key});
                   10378:           my $sum=0;
1.522     www      10379:           my $realnumber=$number;
1.415     www      10380:           for (my $i=0;$i<$number;$i++) {
1.576     www      10381:              if  ($correct[$i] eq '-') {
                   10382:                 $realnumber--;
                   10383:              } elsif ($answer[$i]) {
1.415     www      10384:                 if ($gradingmechanism eq 'attendance') {
                   10385:                    $sum+=$pcorrect;
1.576     www      10386:                 } elsif ($correct[$i] eq '*') {
1.522     www      10387:                    $sum+=$pcorrect;
1.415     www      10388:                 } else {
1.596.2.4  raeburn  10389: # We actually grade if correct or not
                   10390:                    my $increment=$pincorrect;
                   10391: # Special case: numerical answer "0"
                   10392:                    if ($correct[$i] eq '0') {
                   10393:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10394:                          $increment=$pcorrect;
                   10395:                       }
                   10396: # General numerical answer, both evaluate to something non-zero
                   10397:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10398:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10399:                          $increment=$pcorrect;
                   10400:                       }
                   10401: # Must be just alphanumeric
                   10402:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10403:                       $increment=$pcorrect;
1.415     www      10404:                    }
1.596.2.4  raeburn  10405:                    $sum+=$increment;
1.415     www      10406:                 }
                   10407:              }
                   10408:           }
1.522     www      10409:           my $ave=$sum/(100*$realnumber);
1.416     www      10410: # Store
                   10411:           my ($username,$domain)=split(/\:/,$user);
                   10412:           my %grades=();
                   10413:           $grades{"resource.$part.solved"}='correct_by_override';
                   10414:           $grades{"resource.$part.awarded"}=$ave;
                   10415:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10416:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10417:                                                  $env{'request.course.id'},
                   10418:                                                  $domain,$username);
                   10419:           if ($returncode ne 'ok') {
                   10420:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10421:           } else {
                   10422:              $storecount++;
                   10423:           }
1.415     www      10424:        }
                   10425:     }
                   10426: # We are done
1.549     hauer    10427:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10428:              '</td>'.
                   10429:              &Apache::loncommon::end_data_table_row().
                   10430:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      10431:     return $result.&show_grading_menu_form($symb);
                   10432: }
                   10433: 
1.582     raeburn  10434: sub navmap_errormsg {
                   10435:     return '<div class="LC_error">'.
                   10436:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10437:            &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  10438:            '</div>';
                   10439: }
                   10440: 
1.596.2.12.2.  (raeburn 10441:): sub startpage {
                   10442:):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10443:):     if ($nomenu) {
                   10444:):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10445:):     } else {
                   10446:):         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10447:):                                                  {'bread_crumbs' => $crumbs}));
                   10448:):     }
                   10449:):     unless ($nodisplayflag) {
                   10450:):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
                   10451:):     }
                   10452:): }
                   10453:): 
1.1       albertel 10454: sub handler {
1.41      ng       10455:     my $request=$_[0];
1.434     albertel 10456:     &reset_caches();
1.596.2.4  raeburn  10457:     if ($request->header_only) {
                   10458:         &Apache::loncommon::content_type($request,'text/html');
                   10459:         $request->send_http_header;
                   10460:         return OK;
1.41      ng       10461:     }
                   10462:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10463: 
1.324     albertel 10464:     my $symb=&get_symb($request,1);
1.160     albertel 10465:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10466:     my $command=$commands[0];
1.447     foxr     10467: 
1.160     albertel 10468:     if ($#commands > 0) {
                   10469: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10470:     }
1.447     foxr     10471: 
1.513     foxr     10472:     $ssi_error = 0;
1.535     raeburn  10473:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  10474:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.12.2.  (raeburn 10475:):                                                     {'bread_crumbs' => $brcrum});
1.324     albertel 10476:     if ($symb eq '' && $command eq '') {
1.257     albertel 10477: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  10478:             &Apache::loncommon::content_type($request,'text/html');
                   10479:             $request->send_http_header;
                   10480:             $request->print($start_page);
1.257     albertel 10481: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   10482: 		($env{'form.codethree'})) {
                   10483: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   10484: 		    $env{'form.codethree'};
1.41      ng       10485: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   10486: 		    &Apache::lonnet::checkin($token);
                   10487: 		if ($tsymb) {
1.137     albertel 10488: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       10489: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     10490: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 10491: 					  ('grade_username' => $tuname,
                   10492: 					   'grade_domain' => $tudom,
                   10493: 					   'grade_courseid' => $tcrsid,
                   10494: 					   'grade_symb' => $tsymb)));
1.41      ng       10495: 		    } else {
1.45      ng       10496: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 10497: 		    }
1.41      ng       10498: 		} else {
1.45      ng       10499: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       10500: 		}
1.14      www      10501: 	    } else {
1.41      ng       10502: 		$request->print(&Apache::lonxml::tokeninputfield());
                   10503: 	    }
1.596.2.4  raeburn  10504:         } elsif ($env{'request.course.id'}) {
                   10505:             &init_perm(); 
                   10506:             if (!%perm) {
                   10507:                 $request->internal_redirect('/adm/quickgrades');
1.596.2.12.2.  3(raebur 10508:3):                 return OK;
1.596.2.4  raeburn  10509:             } else {
                   10510:                 &Apache::loncommon::content_type($request,'text/html');
                   10511:                 $request->send_http_header;
                   10512:                 $request->print($start_page);
                   10513:             }
                   10514:         }
1.41      ng       10515:     } else {
1.596.2.4  raeburn  10516:         &init_perm();
                   10517:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  10518:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10519:                     ($command =~ /^scantronupload/)) {
                   10520:                 # Not in a course.
                   10521:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10522:                 return HTTP_NOT_ACCEPTABLE;
                   10523:             }
1.596.2.4  raeburn  10524:         } elsif (!%perm) {
                   10525:             $request->internal_redirect('/adm/quickgrades');
                   10526:         }
                   10527:         &Apache::loncommon::content_type($request,'text/html');
                   10528:         $request->send_http_header;
1.596.2.12.2.  (raeburn 10529:):         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
                   10530:):             $request->print($start_page); 
                   10531:):         }
1.104     albertel 10532: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.596.2.12.2.  (raeburn 10533:):             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10534:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10535:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10536:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10537:):                                               $env{'form.userdom'});
                   10538:):             }
                   10539:):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10540:):             if ($versionform) {
                   10541:):                 $request->print($versionform);
                   10542:):             }
                   10543:):             $request->print('<br clear="all" />');
1.257     albertel 10544: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.596.2.12.2.  (raeburn 10545:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10546:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10547:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10548:):                                           $env{'form.userdom'},
                   10549:):                                           $env{'form.inhibitmenu'});
                   10550:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10551:):             if ($versionform) {
                   10552:):                 $request->print($versionform);
                   10553:):             }
                   10554:):             $request->print('<br clear="all" />');
                   10555:):             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10556: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       10557: 	    &pickStudentPage($request);
1.103     albertel 10558: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       10559: 	    &displayPage($request);
1.104     albertel 10560: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       10561: 	    &updateGradeByPage($request);
1.104     albertel 10562: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       10563: 	    &processGroup($request);
1.104     albertel 10564: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 10565: 	    $request->print(&grading_menu($request));
                   10566: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   10567: 	    $request->print(&submit_options($request));
1.104     albertel 10568: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       10569: 	    $request->print(&viewgrades($request));
1.104     albertel 10570: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       10571: 	    $request->print(&processHandGrade($request));
1.106     albertel 10572: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       10573: 	    $request->print(&editgrades($request));
1.106     albertel 10574: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       10575: 	    $request->print(&verifyreceipt($request));
1.400     www      10576:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   10577:             $request->print(&process_clicker($request));
                   10578:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   10579:             $request->print(&process_clicker_file($request));
1.414     www      10580:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   10581:             $request->print(&assign_clicker_grades($request));
1.106     albertel 10582: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       10583: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 10584: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       10585: 	    $request->print(&csvupload($request));
1.106     albertel 10586: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       10587: 	    $request->print(&csvuploadmap($request));
1.246     albertel 10588: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10589: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 10590: 		$request->print(&csvuploadoptions($request));
1.41      ng       10591: 	    } else {
1.257     albertel 10592: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10593: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10594: 		} else {
1.257     albertel 10595: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10596: 		}
                   10597: 		$request->print(&csvuploadmap($request));
                   10598: 	    }
1.246     albertel 10599: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10600: 	    $request->print(&csvuploadassign($request));
1.106     albertel 10601: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 10602: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 10603:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10604:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 10605: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   10606: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 10607: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 10608: 	    $request->print(&scantron_process_students($request));
1.157     albertel 10609:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10610:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10611: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 10612:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 10613:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10614:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10615: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 10616:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 10617:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10618: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 10619:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  10620:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   10621:             $request->print(&checkscantron_results($request));     
1.106     albertel 10622: 	} elsif ($command) {
1.562     bisitz   10623: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10624: 	}
1.2       albertel 10625:     }
1.513     foxr     10626:     if ($ssi_error) {
                   10627: 	&ssi_print_error($request);
                   10628:     }
1.353     albertel 10629:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 10630:     &reset_caches();
1.596.2.4  raeburn  10631:     return OK;
1.44      ng       10632: }
                   10633: 
1.1       albertel 10634: 1;
                   10635: 
1.13      albertel 10636: __END__;
1.531     jms      10637: 
                   10638: 
                   10639: =head1 NAME
                   10640: 
                   10641: Apache::grades
                   10642: 
                   10643: =head1 SYNOPSIS
                   10644: 
                   10645: Handles the viewing of grades.
                   10646: 
                   10647: This is part of the LearningOnline Network with CAPA project
                   10648: described at http://www.lon-capa.org.
                   10649: 
                   10650: =head1 OVERVIEW
                   10651: 
                   10652: Do an ssi with retries:
                   10653: While I'd love to factor out this with the vesrion in lonprintout,
                   10654: 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
                   10655: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10656: 
                   10657: At least the logic that drives this has been pulled out into loncommon.
                   10658: 
                   10659: 
                   10660: 
                   10661: ssi_with_retries - Does the server side include of a resource.
                   10662:                      if the ssi call returns an error we'll retry it up to
                   10663:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 10664:4):                      If we still have a problem, no text is appended to the
1.531     jms      10665:                      output and we set some global variables.
                   10666:                      to indicate to the caller an SSI error occurred.  
                   10667:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 10668:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      10669:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10670:                      by informing the user that this happened.
                   10671: 
                   10672: Parameters:
                   10673:   resource   - The resource to include.  This is passed directly, without
                   10674:                interpretation to lonnet::ssi.
                   10675:   form       - The form hash parameters that guide the interpretation of the resource
                   10676:                
                   10677:   retries    - Number of retries allowed before giving up completely.
                   10678: Returns:
                   10679:   On success, returns the rendered resource identified by the resource parameter.
                   10680: Side Effects:
                   10681:   The following global variables can be set:
                   10682:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10683:                               It is up to the caller to initialize this to false
                   10684:                               if desired.
                   10685:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10686:                               of the resource that could not be rendered by the ssi
                   10687:                               call.
                   10688:    ssi_error_message   - The error string fetched from the ssi response
                   10689:                               in the event of an error.
                   10690: 
                   10691: 
                   10692: =head1 HANDLER SUBROUTINE
                   10693: 
                   10694: ssi_with_retries()
                   10695: 
                   10696: =head1 SUBROUTINES
                   10697: 
                   10698: =over
                   10699: 
                   10700: =item scantron_get_correction() : 
                   10701: 
                   10702:    Builds the interface screen to interact with the operator to fix a
                   10703:    specific error condition in a specific scanline
                   10704: 
                   10705:  Arguments:
                   10706:     $r           - Apache request object
                   10707:     $i           - number of the current scanline
                   10708:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10709:     $scan_config - hash ref as returned from &get_scantron_config()
                   10710:     $line        - full contents of the current scanline
                   10711:     $error       - error condition, valid values are
                   10712:                    'incorrectCODE', 'duplicateCODE',
                   10713:                    'doublebubble', 'missingbubble',
                   10714:                    'duplicateID', 'incorrectID'
                   10715:     $arg         - extra information needed
                   10716:        For errors:
                   10717:          - duplicateID   - paper number that this studentID was seen before on
                   10718:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10719:                            seen on before
                   10720:          - incorrectCODE - current incorrect CODE 
                   10721:          - doublebubble  - array ref of the bubble lines that have double
                   10722:                            bubble errors
                   10723:          - missingbubble - array ref of the bubble lines that have missing
                   10724:                            bubble errors
                   10725: 
1.596.2.12.2.  6(raebur 10726:3):    $randomorder - True if exam folder has randomorder set
                   10727:3):    $randompick  - True if exam folder has randompick set
                   10728:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10729:3):                      for current line to question number used for same question
                   10730:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   10731:3):    $startline   - Reference to hash where key is question number (0 is first)
                   10732:3):                   and value is number of first bubble line for current student
                   10733:3):                   or code-based randompick and/or randomorder.
                   10734:3): 
                   10735:3): 
1.531     jms      10736: =item  scantron_get_maxbubble() : 
                   10737: 
1.582     raeburn  10738:    Arguments:
                   10739:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10740:                       failure to retrieve a navmap object.
                   10741:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10742:        calling routine should trap the error condition and display the warning
                   10743:        found in &navmap_errormsg().
                   10744: 
1.596.2.12.2.  (raeburn 10745:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   10746:): 
1.531     jms      10747:    Returns the maximum number of bubble lines that are expected to
                   10748:    occur. Does this by walking the selected sequence rendering the
                   10749:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10750:    for what the current value of the problem counter is.
                   10751: 
                   10752:    Caches the results to $env{'form.scantron_maxbubble'},
                   10753:    $env{'form.scantron.bubble_lines.n'}, 
                   10754:    $env{'form.scantron.first_bubble_line.n'} and
                   10755:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 10756:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      10757:    lines for response n and number of the first bubble line for response n,
                   10758:    and a comma separated list of numbers of bubble lines for sub-questions
                   10759:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10760: 
                   10761: 
                   10762: =item  scantron_validate_missingbubbles() : 
                   10763: 
                   10764:    Validates all scanlines in the selected file to not have any
                   10765:     answers that don't have bubbles that have not been verified
                   10766:     to be bubble free.
                   10767: 
                   10768: =item  scantron_process_students() : 
                   10769: 
1.596.2.6  raeburn  10770:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10771: 
                   10772:    The parsed scanline hash is added to %env 
                   10773: 
                   10774:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10775:    foreach resource , with the form data of
                   10776: 
                   10777: 	'submitted'     =>'scantron' 
                   10778: 	'grade_target'  =>'grade',
                   10779: 	'grade_username'=> username of student
                   10780: 	'grade_domain'  => domain of student
                   10781: 	'grade_courseid'=> of course
                   10782: 	'grade_symb'    => symb of resource to grade
                   10783: 
                   10784:     This triggers a grading pass. The problem grading code takes care
                   10785:     of converting the bubbled letter information (now in %env) into a
                   10786:     valid submission.
                   10787: 
                   10788: =item  scantron_upload_scantron_data() :
                   10789: 
1.596.2.6  raeburn  10790:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10791: 
                   10792: =item  scantron_upload_scantron_data_save() : 
                   10793: 
                   10794:    Adds a provided bubble information data file to the course if user
                   10795:    has the correct privileges to do so. 
                   10796: 
                   10797: =item  valid_file() :
                   10798: 
                   10799:    Validates that the requested bubble data file exists in the course.
                   10800: 
                   10801: =item  scantron_download_scantron_data() : 
                   10802: 
                   10803:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  10804:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10805:    course.
                   10806: 
                   10807: =item  scantron_validate_ID() : 
                   10808: 
                   10809:    Validates all scanlines in the selected file to not have any
1.556     weissno  10810:    invalid or underspecified student/employee IDs
1.531     jms      10811: 
1.582     raeburn  10812: =item navmap_errormsg() :
                   10813: 
                   10814:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   10815:    Should be called whenever the request to instantiate a navmap object fails.  
                   10816: 
1.531     jms      10817: =back
                   10818: 
                   10819: =cut

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