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

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.  0(raebur    4:4): # $Id: grades.pm,v 1.596.2.12.2.29 2014/02/27 02:52:22 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.  8(raebur  468:4): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($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: 	    }
                   1378: 	    
                   1379: 	}
1.121     ng       1380: 	if (val == "Grade Student") {
                   1381: 	    formname.showgrading.value = "yes";
                   1382: 	    if (formname.Status.value == "") {
                   1383: 		formname.Status.value = "Active";
                   1384: 	    }
                   1385: 	    formname.studentNo.value = total;
                   1386: 	}
1.120     ng       1387: 	formname.submit();
                   1388:     }
                   1389: 
1.71      ng       1390: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1391:     function checkSubmitPage(formname,total) {
                   1392: 	noscore = new Array(100);
                   1393: 	var ptr = 0;
                   1394: 	for (i=1;i<total;i++) {
1.125     ng       1395: 	    var partid = formname["q_"+i].value;
1.127     ng       1396: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1397: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1398: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1399: 		if (points == "" && status != "correct_by_student") {
                   1400: 		    noscore[ptr] = i;
                   1401: 		    ptr++;
                   1402: 		}
                   1403: 	    }
                   1404: 	}
                   1405: 	if (ptr != 0) {
                   1406: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1407: 	    var prolist = "";
                   1408: 	    if (ptr == 1) {
                   1409: 		prolist = noscore[0];
                   1410: 	    } else {
                   1411: 		var i = 0;
                   1412: 		while (i < ptr-1) {
                   1413: 		    prolist += noscore[i]+", ";
                   1414: 		    i++;
                   1415: 		}
                   1416: 		prolist += "and "+noscore[i];
                   1417: 	    }
                   1418: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1419: 	    if (resp == false) {
                   1420: 		return false;
                   1421: 	    }
                   1422: 	}
1.45      ng       1423: 
1.71      ng       1424: 	formname.submit();
                   1425:     }
                   1426: </script>
                   1427: SUBJAVASCRIPT
                   1428: }
1.45      ng       1429: 
1.71      ng       1430: #--- javascript for essay type problem --
                   1431: sub sub_page_kw_js {
                   1432:     my $request = shift;
1.80      ng       1433:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1434:     &commonJSfunctions($request);
1.350     albertel 1435: 
1.351     albertel 1436:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1437:     <script text="text/javascript">
                   1438:     function checkInput() {
                   1439:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1440:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1441:       var usrctr = document.msgcenter.usrctr.value;
                   1442:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1443:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1444: 
                   1445:       var msgchk = "";
                   1446:       if (document.msgcenter.subchk.checked) {
                   1447:          msgchk = "msgsub,";
                   1448:       }
                   1449:       var includemsg = 0;
                   1450:       for (var i=1; i<=nmsg; i++) {
                   1451:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1452:           var frmmsg = document.msgcenter["msg"+i];
                   1453:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1454:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1455:           showflg.value = "1";
                   1456:           var chkbox = document.msgcenter["msgn"+i];
                   1457:           if (chkbox.checked) {
                   1458:              msgchk += "savemsg"+i+",";
                   1459:              includemsg = 1;
                   1460:           }
                   1461:       }
                   1462:       if (document.msgcenter.newmsgchk.checked) {
                   1463:          msgchk += "newmsg"+usrctr;
                   1464:          includemsg = 1;
                   1465:       }
                   1466:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1467:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1468:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1469:       includemsg.value = msgchk;
                   1470: 
                   1471:       self.close()
                   1472: 
                   1473:     }
                   1474:     </script>
                   1475: INNERJS
                   1476: 
1.351     albertel 1477:     my $inner_js_highlight_central=<<INNERJS;
                   1478:  <script type="text/javascript">
                   1479:     function updateChoice(flag) {
                   1480:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1481:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1482:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1483:       opener.document.SCORE.refresh.value = "on";
                   1484:       if (opener.document.SCORE.keywords.value!=""){
                   1485:          opener.document.SCORE.submit();
                   1486:       }
                   1487:       self.close()
                   1488:     }
                   1489: </script>
                   1490: INNERJS
                   1491: 
                   1492:     my $start_page_msg_central = 
                   1493:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1494: 				       {'js_ready'  => 1,
                   1495: 					'only_body' => 1,
                   1496: 					'bgcolor'   =>'#FFFFFF',});
                   1497:     my $end_page_msg_central = 
                   1498: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1499: 
                   1500: 
                   1501:     my $start_page_highlight_central = 
                   1502:         &Apache::loncommon::start_page('Highlight Central',
                   1503: 				       $inner_js_highlight_central,
1.350     albertel 1504: 				       {'js_ready'  => 1,
                   1505: 					'only_body' => 1,
                   1506: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1507:     my $end_page_highlight_central = 
1.350     albertel 1508: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1509: 
1.219     www      1510:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1511:     $docopen=~s/^document\.//;
1.596.2.4  raeburn  1512:     my %lt = &Apache::lonlocal::texthash(
                   1513:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1514:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1515:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1516:                 comp => 'Compose Message for: ',
                   1517:                 incl => 'Include',
                   1518:                 type => 'Type',
                   1519:                 subj => 'Subject',
                   1520:                 mesa => 'Message',
                   1521:                 new  => 'New',
                   1522:                 save => 'Save',
                   1523:                 canc => 'Cancel',
                   1524:                 kehi => 'Keyword Highlight Options',
                   1525:                 txtc => 'Text Color',
                   1526:                 font => 'Font Size',
                   1527:                 fnst => 'Font Style',
1.596.2.12.2.  8(raebur 1528:4):                 col1 => 'red',
                   1529:4):                 col2 => 'green',
                   1530:4):                 col3 => 'blue',
                   1531:4):                 siz1 => 'normal',
                   1532:4):                 siz2 => '+1',
                   1533:4):                 siz3 => '+2',
                   1534:4):                 sty1 => 'normal',
                   1535:4):                 sty2 => 'italic',
                   1536:4):                 sty3 => 'bold',
1.596.2.4  raeburn  1537:              );
1.71      ng       1538:     $request->print(<<SUBJAVASCRIPT);
                   1539: <script type="text/javascript" language="javascript">
1.45      ng       1540: 
1.44      ng       1541: //===================== Show list of keywords ====================
1.122     ng       1542:   function keywords(formname) {
1.596.2.4  raeburn  1543:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1544:     if (nret==null) return;
1.122     ng       1545:     formname.keywords.value = nret;
1.44      ng       1546: 
1.122     ng       1547:     if (formname.keywords.value != "") {
1.128     ng       1548: 	formname.refresh.value = "on";
1.122     ng       1549: 	formname.submit();
1.44      ng       1550:     }
                   1551:     return;
                   1552:   }
                   1553: 
                   1554: //===================== Script to view submitted by ==================
                   1555:   function viewSubmitter(submitter) {
                   1556:     document.SCORE.refresh.value = "on";
                   1557:     document.SCORE.NCT.value = "1";
                   1558:     document.SCORE.unamedom0.value = submitter;
                   1559:     document.SCORE.submit();
                   1560:     return;
                   1561:   }
                   1562: 
                   1563: //===================== Script to add keyword(s) ==================
                   1564:   function getSel() {
                   1565:     if (document.getSelection) txt = document.getSelection();
                   1566:     else if (document.selection) txt = document.selection.createRange().text;
                   1567:     else return;
                   1568:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1569:     if (cleantxt=="") {
1.596.2.4  raeburn  1570: 	alert("$lt{'plse'}");
1.44      ng       1571: 	return;
                   1572:     }
1.596.2.4  raeburn  1573:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1574:     if (nret==null) return;
1.127     ng       1575:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1576:     if (document.SCORE.keywords.value != "") {
1.127     ng       1577: 	document.SCORE.refresh.value = "on";
1.44      ng       1578: 	document.SCORE.submit();
                   1579:     }
                   1580:     return;
                   1581:   }
                   1582: 
                   1583: //====================== Script for composing message ==============
1.80      ng       1584:    // preload images
                   1585:    img1 = new Image();
                   1586:    img1.src = "$iconpath/mailbkgrd.gif";
                   1587:    img2 = new Image();
                   1588:    img2.src = "$iconpath/mailto.gif";
                   1589: 
1.44      ng       1590:   function msgCenter(msgform,usrctr,fullname) {
                   1591:     var Nmsg  = msgform.savemsgN.value;
                   1592:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1593:     var subject = msgform.msgsub.value;
1.127     ng       1594:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1595:     re = /msgsub/;
                   1596:     var shwsel = "";
                   1597:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1598:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1599:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1600:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1601: 	var testmsg = "savemsg"+i+",";
                   1602: 	re = new RegExp(testmsg,"g");
1.44      ng       1603: 	shwsel = "";
                   1604: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1605: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1606: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1607: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1608: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1609:     }
1.125     ng       1610:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1611:     shwsel = "";
                   1612:     re = /newmsg/;
                   1613:     if (re.test(msgchk)) { shwsel = "checked" }
                   1614:     newMsg(newmsg,shwsel);
                   1615:     msgTail(); 
                   1616:     return;
                   1617:   }
                   1618: 
1.123     ng       1619:   function checkEntities(strx) {
                   1620:     if (strx.length == 0) return strx;
                   1621:     var orgStr = ["&", "<", ">", '"']; 
                   1622:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1623:     var counter = 0;
                   1624:     while (counter < 4) {
                   1625: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1626: 	counter++;
                   1627:     }
                   1628:     return strx;
                   1629:   }
                   1630: 
                   1631:   function strReplace(strx, orgStr, newStr) {
                   1632:     return strx.split(orgStr).join(newStr);
                   1633:   }
                   1634: 
1.44      ng       1635:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1636:     var height = 70*Nmsg+250;
1.44      ng       1637:     if (height > 600) {
                   1638: 	height = 600;
                   1639:     }
1.118     ng       1640:     var xpos = (screen.width-600)/2;
                   1641:     xpos = (xpos < 0) ? '0' : xpos;
                   1642:     var ypos = (screen.height-height)/2-30;
                   1643:     ypos = (ypos < 0) ? '0' : ypos;
                   1644: 
1.596.2.12.2.  (raeburn 1645:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1646:     pWin.focus();
                   1647:     pDoc = pWin.document;
1.219     www      1648:     pDoc.$docopen;
1.351     albertel 1649:     pDoc.write('$start_page_msg_central');
1.76      ng       1650: 
                   1651:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1652:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.4  raeburn  1653:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1654: 
1.564     bisitz   1655:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1656:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.4  raeburn  1657:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1658: }
                   1659:     function displaySubject(msg,shwsel) {
1.76      ng       1660:     pDoc = pWin.document;
                   1661:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1662:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1663:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1664:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1665: }
                   1666: 
1.72      ng       1667:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1668:     pDoc = pWin.document;
                   1669:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1670:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1671:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1672:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1673: }
                   1674: 
                   1675:   function newMsg(newmsg,shwsel) {
1.76      ng       1676:     pDoc = pWin.document;
                   1677:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1678:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1679:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1680:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1681: }
                   1682: 
                   1683:   function msgTail() {
1.76      ng       1684:     pDoc = pWin.document;
1.465     albertel 1685:     pDoc.write("<\\/table>");
                   1686:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.4  raeburn  1687:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1688:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1689:     pDoc.write("<\\/form>");
1.351     albertel 1690:     pDoc.write('$end_page_msg_central');
1.128     ng       1691:     pDoc.close();
1.44      ng       1692: }
                   1693: 
                   1694: //====================== Script for keyword highlight options ==============
                   1695:   function kwhighlight() {
                   1696:     var kwclr    = document.SCORE.kwclr.value;
                   1697:     var kwsize   = document.SCORE.kwsize.value;
                   1698:     var kwstyle  = document.SCORE.kwstyle.value;
                   1699:     var redsel = "";
                   1700:     var grnsel = "";
                   1701:     var blusel = "";
1.596.2.12.2.  8(raebur 1702:4):     var txtcol1 = "$lt{'col1'}";
                   1703:4):     var txtcol2 = "$lt{'col2'}";
                   1704:4):     var txtcol3 = "$lt{'col3'}";
                   1705:4):     var txtsiz1 = "$lt{'siz1'}";
                   1706:4):     var txtsiz2 = "$lt{'siz2'}";
                   1707:4):     var txtsiz3 = "$lt{'siz3'}";
                   1708:4):     var txtsty1 = "$lt{'sty1'}";
                   1709:4):     var txtsty2 = "$lt{'sty2'}";
                   1710:4):     var txtsty3 = "$lt{'sty3'}";
                   1711:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1712:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1713:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1714:     var sznsel = "";
                   1715:     var sz1sel = "";
                   1716:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1717:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1718:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1719:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1720:     var synsel = "";
                   1721:     var syisel = "";
                   1722:     var sybsel = "";
1.596.2.12.2.  8(raebur 1723:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1724:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1725:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1726:     highlightCentral();
1.596.2.12.2.  8(raebur 1727:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1728:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1729:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1730:     highlightend();
                   1731:     return;
                   1732:   }
                   1733: 
                   1734:   function highlightCentral() {
1.76      ng       1735: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1736:     var xpos = (screen.width-400)/2;
                   1737:     xpos = (xpos < 0) ? '0' : xpos;
                   1738:     var ypos = (screen.height-330)/2-30;
                   1739:     ypos = (ypos < 0) ? '0' : ypos;
                   1740: 
1.206     albertel 1741:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1742:     hwdWin.focus();
                   1743:     var hDoc = hwdWin.document;
1.219     www      1744:     hDoc.$docopen;
1.351     albertel 1745:     hDoc.write('$start_page_highlight_central');
1.76      ng       1746:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  8(raebur 1747:4):     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1.76      ng       1748: 
1.596.2.12.2.  8(raebur 1749:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
                   1750:4):     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1751:   }
                   1752: 
                   1753:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1754:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1755:4):     hDoc.write("<tr>");
1.76      ng       1756:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1757:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1758:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1759:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1760:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1761:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1762:     hDoc.write("<\\/tr>");
1.44      ng       1763:   }
                   1764: 
                   1765:   function highlightend() { 
1.76      ng       1766:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1767:4):     hDoc.write("<\\/table><br \\/>");
                   1768:4):     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1769:4):     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1770:     hDoc.write("<\\/form>");
1.351     albertel 1771:     hDoc.write('$end_page_highlight_central');
1.128     ng       1772:     hDoc.close();
1.44      ng       1773:   }
                   1774: 
                   1775: </script>
                   1776: SUBJAVASCRIPT
                   1777: }
                   1778: 
1.349     albertel 1779: sub get_increment {
1.348     bowersj2 1780:     my $increment = $env{'form.increment'};
                   1781:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1782:         $increment != .1) {
                   1783:         $increment = 1;
                   1784:     }
                   1785:     return $increment;
                   1786: }
                   1787: 
1.585     bisitz   1788: sub gradeBox_start {
                   1789:     return (
                   1790:         &Apache::loncommon::start_data_table()
                   1791:        .&Apache::loncommon::start_data_table_header_row()
                   1792:        .'<th>'.&mt('Part').'</th>'
                   1793:        .'<th>'.&mt('Points').'</th>'
                   1794:        .'<th>&nbsp;</th>'
                   1795:        .'<th>'.&mt('Assign Grade').'</th>'
                   1796:        .'<th>'.&mt('Weight').'</th>'
                   1797:        .'<th>'.&mt('Grade Status').'</th>'
                   1798:        .&Apache::loncommon::end_data_table_header_row()
                   1799:     );
                   1800: }
                   1801: 
                   1802: sub gradeBox_end {
                   1803:     return (
                   1804:         &Apache::loncommon::end_data_table()
                   1805:     );
                   1806: }
1.71      ng       1807: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1808: sub gradeBox {
1.322     albertel 1809:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1810:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1811: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1812:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1813:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1814:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1815:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1816:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1817: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1818:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1819:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1820:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1821: 				       [$partid]);
                   1822:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1823:     if ($last_resets{$partid}) {
                   1824:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1825:     }
1.596.2.12.2.  8(raebur 1826:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1827:     my $ctr = 0;
1.348     bowersj2 1828:     my $thisweight = 0;
1.349     albertel 1829:     my $increment = &get_increment();
1.485     albertel 1830: 
                   1831:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1832:     while ($thisweight<=$wgt) {
1.532     bisitz   1833: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1834:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1835: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1836: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1837: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1838:         $thisweight += $increment;
1.71      ng       1839: 	$ctr++;
                   1840:     }
1.485     albertel 1841:     $radio.='</tr></table>';
                   1842: 
                   1843:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1844: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1845: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1846: 	$wgt.')" /></td>'."\n";
1.485     albertel 1847:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1848: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1849: 	' </td>'."\n";
                   1850:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1851: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1852:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1853: 	$line.='<option></option>'.
                   1854: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1855:     } else {
1.485     albertel 1856: 	$line.='<option selected="selected"></option>'.
                   1857: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1858:     }
1.485     albertel 1859:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1860: 
                   1861: 
                   1862:     $result .= 
1.596.2.12.2.  8(raebur 1863:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1864:3):     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1.71      ng       1865:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1866: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1867: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1868: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1869:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1870:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1871:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1872:         $aggtries.'" />'."\n";
1.582     raeburn  1873:     my $res_error;
                   1874:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 1875:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1876:     if ($res_error) {
                   1877:         return &navmap_errormsg();
                   1878:     }
1.318     banghart 1879:     return $result;
                   1880: }
1.322     albertel 1881: 
                   1882: sub handback_box {
1.582     raeburn  1883:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1884:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1885:     my (@respids);
1.596.2.4  raeburn  1886:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1887:     foreach my $part_response_id (@part_response_id) {
                   1888:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1889:         if ($part eq $partid) {
1.375     albertel 1890:             push(@respids,$resp);
1.323     banghart 1891:         }
                   1892:     }
1.318     banghart 1893:     my $result;
1.323     banghart 1894:     foreach my $respid (@respids) {
1.322     albertel 1895: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1896: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1897: 	next if (!@$files);
1.596.2.4  raeburn  1898: 	my $file_counter = 0;
1.313     banghart 1899: 	foreach my $file (@$files) {
1.368     banghart 1900: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1901:                 $file_counter++;
1.368     banghart 1902:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1903:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1904:     	        $file_disp = "$name.$ext";
                   1905:     	        $file = $file_path.$file_disp;
                   1906:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1907:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1908:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1909:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1910: 	    }
1.322     albertel 1911: 	}
1.596.2.4  raeburn  1912:         if ($file_counter) {
                   1913:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1914:                        '<span class="LC_info">'.
                   1915:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1916:         }
1.313     banghart 1917:     }
1.318     banghart 1918:     return $result;    
1.71      ng       1919: }
1.44      ng       1920: 
1.58      albertel 1921: sub show_problem {
1.382     albertel 1922:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1923:     my $rendered;
1.382     albertel 1924:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1925:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1926:     if ($mode eq 'both' or $mode eq 'text') {
                   1927: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1928: 						       $env{'request.course.id'},
                   1929: 						       undef,\%form);
1.144     albertel 1930:     }
1.58      albertel 1931:     if ($removeform) {
                   1932: 	$rendered=~s|<form(.*?)>||g;
                   1933: 	$rendered=~s|</form>||g;
1.374     albertel 1934: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1935:     }
1.144     albertel 1936:     my $companswer;
                   1937:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1938: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1939: 	$companswer=
                   1940: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1941: 						    $env{'request.course.id'},
                   1942: 						    %form);
1.144     albertel 1943:     }
1.58      albertel 1944:     if ($removeform) {
                   1945: 	$companswer=~s|<form(.*?)>||g;
                   1946: 	$companswer=~s|</form>||g;
1.144     albertel 1947: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1948:     }
1.596.2.12.2.  (raeburn 1949:):     my $renderheading = &mt('View of the problem');
                   1950:):     my $answerheading = &mt('Correct answer');
                   1951:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1952:):         my $stu_fullname = $env{'form.fullname'};
                   1953:):         if ($stu_fullname eq '') {
                   1954:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1955:):         }
                   1956:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1957:):         if ($forwhom ne '') {
                   1958:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1959:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1960:):         }
                   1961:):     }
1.468     albertel 1962:     $rendered=
1.588     bisitz   1963:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1964:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1965:        .$rendered
                   1966:        .'</div>';
1.468     albertel 1967:     $companswer=
1.588     bisitz   1968:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1969:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1970:        .$companswer
                   1971:        .'</div>';
1.468     albertel 1972:     my $result;
1.144     albertel 1973:     if ($mode eq 'both') {
1.588     bisitz   1974:         $result=$rendered.$companswer;
1.144     albertel 1975:     } elsif ($mode eq 'text') {
1.588     bisitz   1976:         $result=$rendered;
1.144     albertel 1977:     } elsif ($mode eq 'answer') {
1.588     bisitz   1978:         $result=$companswer;
1.144     albertel 1979:     }
1.71      ng       1980:     return $result;
1.58      albertel 1981: }
1.397     albertel 1982: 
1.396     banghart 1983: sub files_exist {
                   1984:     my ($r, $symb) = @_;
                   1985:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1986: 
1.396     banghart 1987:     foreach my $student (@students) {
                   1988:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1989:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1990: 					      $udom,$uname);
1.396     banghart 1991:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1992:         foreach my $submission (@$string) {
                   1993:             my ($partid,$respid) =
                   1994: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1995:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1996: 					   \%record);
                   1997:             return 1 if (@$files);
1.396     banghart 1998:         }
                   1999:     }
1.397     albertel 2000:     return 0;
1.396     banghart 2001: }
1.397     albertel 2002: 
1.394     banghart 2003: sub download_all_link {
                   2004:     my ($r,$symb) = @_;
1.395     albertel 2005:     my $all_students = 
                   2006: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2007: 
                   2008:     my $parts =
                   2009: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2010: 
1.394     banghart 2011:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2012:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2013:                              'cgi.'.$identifier.'.symb' => $symb,
                   2014:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2015:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2016: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 2017:     return
                   2018: }
1.395     albertel 2019: 
1.432     banghart 2020: sub build_section_inputs {
                   2021:     my $section_inputs;
                   2022:     if ($env{'form.section'} eq '') {
                   2023:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2024:     } else {
                   2025:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2026:         foreach my $section (@sections) {
1.432     banghart 2027:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2028:         }
                   2029:     }
                   2030:     return $section_inputs;
                   2031: }
                   2032: 
1.44      ng       2033: # --------------------------- show submissions of a student, option to grade 
                   2034: sub submission {
                   2035:     my ($request,$counter,$total) = @_;
1.257     albertel 2036:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2037:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2038:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2039:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  (raeburn 2040:):     my ($symb) = &get_symb($request); 
1.324     albertel 2041:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2042: 
                   2043:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2044:4):         $request->print(
                   2045:4):             '<span class="LC_warning">'.
                   2046:4):             &mt('Unable to view requested student.').
                   2047:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2048:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2049:4):             '</span>');
1.324     albertel 2050: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2051: 	return;
                   2052:     }
                   2053: 
1.257     albertel 2054:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2055:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2056:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2057:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2058:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2059: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2060: 	'/check.gif" height="16" border="0" />';
1.41      ng       2061: 
                   2062:     # header info
                   2063:     if ($counter == 0) {
                   2064: 	&sub_page_js($request);
1.257     albertel 2065: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2066: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2067: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2068: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2069: 	    &download_all_link($request, $symb);
                   2070: 	}
1.485     albertel 2071: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1.596.2.12.2.  2(raebur 2072:3): 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2073: 
1.44      ng       2074: 	# option to display problem, only once else it cause problems 
                   2075:         # with the form later since the problem has a form.
1.257     albertel 2076: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2077: 	    my $mode;
1.257     albertel 2078: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2079: 		$mode='both';
1.257     albertel 2080: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2081: 		$mode='text';
1.257     albertel 2082: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2083: 		$mode='answer';
                   2084: 	    }
1.329     albertel 2085: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2086: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2087: 	}
1.441     www      2088: 
1.596.2.12.2.  0(raebur 2089:3): 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2090:         # if this subroutine has been called once.
1.41      ng       2091: 	my %keyhash = ();
1.257     albertel 2092: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2093: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2094: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2095: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2096: 
1.257     albertel 2097: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2098: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2099: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2100: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2101: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2102: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2103: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2104: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2105: 	}
1.257     albertel 2106: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2107: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2108: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2109: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2110: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2111: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2112: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2113: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2114: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2115: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2116: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2117: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2118: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2119: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2120: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2121: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2122: 			&build_section_inputs().
1.326     albertel 2123: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2124: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2125: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2126: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2127: 	if ($env{'form.handgrade'} eq 'yes') {
                   2128: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2129: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2130: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2131: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2132: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2133: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2134: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2135: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2136: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2137: 	    }
1.123     ng       2138: 	}
1.41      ng       2139: 	
                   2140: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2141: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2142: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2143: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2144: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2145: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2146: 		'" />'."\n".
                   2147: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2148: 	    $cts++;
                   2149: 	}
                   2150: 	$request->print($prnmsg);
1.32      ng       2151: 
1.257     albertel 2152: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2153: 
                   2154:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2155:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2156:                           keyw => 'Keyword Options',
                   2157:                           list => 'List',
                   2158:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2159:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2160:                      );
1.88      www      2161: #
                   2162: # Print out the keyword options line
                   2163: #
1.596.2.12.2.  8(raebur 2164:4):             $request->print(
                   2165:4):                 '<div class="LC_columnSection">'
                   2166:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2167:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2168:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2169:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2170:4):  class="page">'.$lt{'past'}.'</a>',
                   2171:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2172:4):                     {legend => $lt{'keyw'}})
                   2173:4):                .'</fieldset></div>'
                   2174:4):             );
                   2175:4): 
1.88      www      2176: #
                   2177: # Load the other essays for similarity check
                   2178: #
1.324     albertel 2179:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2180: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2181: 	    $apath=&escape($apath);
1.88      www      2182: 	    $apath=~s/\W/\_/gs;
1.596.2.12.2.  (raeburn 2183:):             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2184:         }
                   2185:     }
1.44      ng       2186: 
1.441     www      2187: # This is where output for one specific student would start
1.592     bisitz   2188:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2189:     $request->print(
                   2190:         "\n\n"
                   2191:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2192:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2193:        ."\n"
                   2194:     );
1.441     www      2195: 
1.592     bisitz   2196:     # Show additional functions if allowed
                   2197:     if ($perm{'vgr'}) {
                   2198:         $request->print(
                   2199:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2200:3):                 'View recent activity',
1.592     bisitz   2201:                 $uname,$udom,'check')
                   2202:            .' '
                   2203:         );
                   2204:     }
                   2205:     if ($perm{'opa'}) {
                   2206:         $request->print(
                   2207:             &Apache::loncommon::pprmlink(
                   2208:                 &mt('Set/Change parameters'),
                   2209:                 $uname,$udom,$symb,'check'));
                   2210:     }
                   2211: 
                   2212:     # Show Problem
1.257     albertel 2213:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2214: 	my $mode;
1.257     albertel 2215: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2216: 	    $mode='both';
1.257     albertel 2217: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2218: 	    $mode='text';
1.257     albertel 2219: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2220: 	    $mode='answer';
                   2221: 	}
1.329     albertel 2222: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2223: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2224:     }
1.144     albertel 2225: 
1.257     albertel 2226:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2227:     my $res_error;
                   2228:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2229:     if ($res_error) {
                   2230:         $request->print(&navmap_errormsg());
                   2231:         return;
                   2232:     }
1.41      ng       2233: 
1.44      ng       2234:     # Display student info
1.41      ng       2235:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2236: 
                   2237:     my $result='<div class="LC_Box">'
                   2238:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2239:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2240:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2241:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2242:         $result.='<p class="LC_info">'
                   2243:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2244:                 ."</p>\n";
1.469     albertel 2245:     }
                   2246: 
1.118     ng       2247:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2248:     my $fullname;
                   2249:     my $col_fullnames = [];
1.257     albertel 2250:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2251: 	(my $sub_result,$fullname,$col_fullnames)=
                   2252: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2253: 				 $counter);
                   2254: 	$result.=$sub_result;
1.41      ng       2255:     }
1.44      ng       2256:     $request->print($result."\n");
1.588     bisitz   2257: 
1.44      ng       2258:     # print student answer/submission
1.588     bisitz   2259:     # Options are (1) Handgraded submission only
1.44      ng       2260:     #             (2) Last submission, includes submission that is not handgraded 
                   2261:     #                  (for multi-response type part)
                   2262:     #             (3) Last submission plus the parts info
                   2263:     #             (4) The whole record for this student
1.596.2.12.2.  1(raebur 2264:3): 
1.151     albertel 2265: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2266: 	
                   2267: 	my $lastsubonly;
                   2268: 
1.588     bisitz   2269:         if ($$timestamp eq '') {
                   2270:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2271:         } else {
1.592     bisitz   2272:             $lastsubonly =
                   2273:                 '<div class="LC_grade_submissions_body">'
                   2274:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2275: 
1.151     albertel 2276: 	    my %seenparts;
1.375     albertel 2277: 	    my @part_response_id = &flatten_responseType($responseType);
                   2278: 	    foreach my $part (@part_response_id) {
1.393     albertel 2279: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2280: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2281: 
1.375     albertel 2282: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2283: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2284: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2285: 		    if (exists($seenparts{$partid})) { next; }
                   2286: 		    $seenparts{$partid}=1;
1.596.2.12.2.  8(raebur 2287:3):                     $request->print(
                   2288:3):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2289:3):                         ' <b>'.&mt('Collaborative submission by: [_1]',
                   2290:3):                                    '<a href="javascript:viewSubmitter(\''.
                   2291:3):                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2292:3):                                    '\');" target="_self">'.
                   2293:3):                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2294:3):                         '<br />');
1.151     albertel 2295: 		    next;
                   2296: 		}
                   2297: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2298: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2299:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2300:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2301:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2302:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2303:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2304: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2305: 		    next;
                   2306: 		}
1.468     albertel 2307: 		foreach my $submission (@$string) {
                   2308: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2309: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596.2.12.2.  0(raebur 2310:4): 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.151     albertel 2311: 		    # Similarity check
                   2312: 		    my $similar='';
1.596.2.2  raeburn  2313:                     my ($type,$trial,$rndseed);
                   2314:                     if ($hide eq 'rand') {
                   2315:                         $type = 'randomizetry';
                   2316:                         $trial = $record{"resource.$partid.tries"};
                   2317:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2318:                     }
1.596.2.12.2.  1(raebur 2319:3): 		    if ($env{'form.checkPlag'}) {
1.151     albertel 2320: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.596.2.12.2.  (raeburn 2321:): 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2322: 			if ($osim) {
                   2323: 			    $osim=int($osim*100.0);
1.426     albertel 2324: 			    my %old_course_desc = 
                   2325: 				&Apache::lonnet::coursedescription($ocrsid,
                   2326: 								   {'one_time' => 1});
                   2327: 
1.596.2.2  raeburn  2328:                             if ($hide eq 'anon') {
1.596     raeburn  2329:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2330:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2331:                             } else {
                   2332: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2333: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2334: 				        $osim,
                   2335: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2336: 				        $old_course_desc{'description'},
                   2337: 				        $old_course_desc{'num'},
                   2338: 				        $old_course_desc{'domain'}).
                   2339: 				    '</span></h3><blockquote><i>'.
                   2340: 				    &keywords_highlight($oessay).
                   2341: 				    '</i></blockquote><hr />';
                   2342:                             }
1.151     albertel 2343: 			}
1.150     albertel 2344: 		    }
1.596.2.2  raeburn  2345: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2346:                                          undef,$type,$trial,$rndseed);
1.596.2.12.2.  1(raebur 2347:3):                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
                   2348:3):                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2349: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2350:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2351:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2352:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2353:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2354:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2355: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2356: 			if (@$files) {
1.596.2.2  raeburn  2357:                             if ($hide eq 'anon') {
1.596     raeburn  2358:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2359:                             } else {
1.596.2.12.2.  8(raebur 2360:3):                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2361:3):                                             .'<br /><span class="LC_warning">';
                   2362:3):                                 if(@$files == 1) {
                   2363:3):                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2364:3):                                 } else {
                   2365:3):                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2366:3):                                 }
                   2367:3):                                 $lastsubonly .= '</span>';
                   2368:3): 
1.596     raeburn  2369:                                 foreach my $file (@$files) {
                   2370:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
1.596.2.12.2.  8(raebur 2371:3):                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2372:                                 }
                   2373:                             }
1.236     albertel 2374: 			    $lastsubonly.='<br />';
1.41      ng       2375: 			}
1.596.2.2  raeburn  2376:                         if ($hide eq 'anon') {
1.596.2.12.2.  8(raebur 2377:3):                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
1.596     raeburn  2378:                         } else {
1.596.2.12.2.  0(raebur 2379:4): 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2380:4):                             if ($draft) {
                   2381:4):                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2382:4):                             }
                   2383:4):                             $subval =
1.596     raeburn  2384: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2385: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596.2.12.2.  0(raebur 2386:4):                             if ($responsetype eq 'essay') {
                   2387:4):                                 $subval =~ s{\n}{<br />}g;
                   2388:4):                             }
                   2389:4):                             $lastsubonly.=$subval."\n";
1.596     raeburn  2390:                         }
1.151     albertel 2391: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2392: 			$lastsubonly.='</div>';
1.41      ng       2393: 		    }
                   2394: 		}
                   2395: 	    }
1.588     bisitz   2396: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2397: 	}
                   2398: 	$request->print($lastsubonly);
1.596.2.12.2.  1(raebur 2399:3):    if ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2400: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2401: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2402:3):     }
                   2403:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2404: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2405: 								 $env{'request.course.id'},
1.44      ng       2406: 								 $last,'.submission',
                   2407: 								 'Apache::grades::keywords_highlight'));
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) {
                   2635:                     foreach my $id (@hidden) {
                   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.324     albertel 2866: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2867: 	    if ($errorflag eq 'no_score') {
                   2868: 		$ctr++;
                   2869: 		next;
                   2870: 	    }
1.104     albertel 2871: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 2872:4):                 $request->print(
                   2873:4):                     '<span class="LC_error">'
                   2874:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2875:4):                    .'</span>');
1.104     albertel 2876: 		$ctr++;
                   2877: 		next;
                   2878: 	    }
1.257     albertel 2879: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2880: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2881: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2882:             my ($feedurl,$showsymb) =
                   2883: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2884: 	    my $messagetail;
1.62      albertel 2885: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2886: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2887: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2888: 		$subject.=' ['.$restitle.']';
1.44      ng       2889: 		my (@msgnum) = split(/,/,$includemsg);
                   2890: 		foreach (@msgnum) {
1.257     albertel 2891: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2892: 		}
1.80      ng       2893: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2894: 		if ($env{'form.withgrades'.$ctr}) {
                   2895: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2896: 		    $messagetail = " for <a href=\"".
1.418     albertel 2897: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2898: 		}
                   2899: 		$msgstatus = 
                   2900:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2901: 						     $message.$messagetail,
1.418     albertel 2902:                                                      undef,$feedurl,undef,
1.386     raeburn  2903:                                                      undef,undef,$showsymb,
                   2904:                                                      $restitle);
1.574     bisitz   2905: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2906: 				$msgstatus.'<br />');
1.44      ng       2907: 	    }
1.257     albertel 2908: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2909: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2910: 		foreach my $collabstr (@collabstrs) {
                   2911: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2912: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2913: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2914: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2915: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2916: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2917: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2918: 			    next;
1.418     albertel 2919: 			} elsif ($message ne '') {
                   2920: 			    my ($baseurl,$showsymb) = 
                   2921: 				&get_feedurl_and_symb($symb,$collaborator,
                   2922: 						      $udom);
                   2923: 			    if ($env{'form.withgrades'.$ctr}) {
                   2924: 				$messagetail = " for <a href=\"".
1.386     raeburn  2925:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2926: 			    }
1.418     albertel 2927: 			    $msgstatus = 
                   2928: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2929: 			}
1.44      ng       2930: 		    }
                   2931: 		}
                   2932: 	    }
                   2933: 	    $ctr++;
                   2934: 	}
                   2935:     }
                   2936: 
1.257     albertel 2937:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2938: 	# Keywords sorted in alphabatical order
1.257     albertel 2939: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2940: 	my %keyhash = ();
1.257     albertel 2941: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2942: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2943: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2944: 	$env{'form.keywords'} = join(' ',@keywords);
                   2945: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2946: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2947: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2948: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2949: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2950: 
                   2951: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2952: 	# New messages are saved in env for the next student.
1.119     ng       2953: 	# All messages are saved in nohist_handgrade.db
                   2954: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2955: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2956: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2957: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2958: 		$idx++;
                   2959: 	    }
                   2960: 	    $ctr++;
1.41      ng       2961: 	}
1.119     ng       2962: 	$ctr = 0;
                   2963: 	while ($ctr < $ngrade) {
1.257     albertel 2964: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2965: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2966: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2967: 		$idx++;
                   2968: 	    }
                   2969: 	    $ctr++;
1.41      ng       2970: 	}
1.257     albertel 2971: 	$env{'form.savemsgN'} = --$idx;
                   2972: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2973: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2974: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2975:     }
1.44      ng       2976:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2977:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2978:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2979: 	my ($ctr,$total) = (0,0);
                   2980: 	while ($ctr < $ngrade) {
1.257     albertel 2981: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2982: 	    $ctr++;
                   2983: 	}
1.257     albertel 2984: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2985: 	$ctr = 0;
                   2986: 	while ($ctr < $total) {
1.257     albertel 2987: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2988: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2989: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2990: 	    &submission($request,$ctr,$total-1);
1.41      ng       2991: 	    $ctr++;
                   2992: 	}
                   2993: 	return '';
                   2994:     }
1.36      ng       2995: 
1.121     ng       2996: # Go directly to grade student - from submission or link from chart page
1.120     ng       2997:     if ($button eq 'Grade Student') {
1.324     albertel 2998: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2999: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   3000: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3001: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       3002: 	&submission($request,0,0);
                   3003: 	return '';
                   3004:     }
                   3005: 
1.44      ng       3006:     # Get the next/previous one or group of students
1.257     albertel 3007:     my $firststu = $env{'form.unamedom0'};
                   3008:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3009:     my $ctr = 2;
1.41      ng       3010:     while ($laststu eq '') {
1.257     albertel 3011: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3012: 	$ctr++;
                   3013: 	$laststu = $firststu if ($ctr > $ngrade);
                   3014:     }
1.44      ng       3015: 
1.41      ng       3016:     my (@parsedlist,@nextlist);
                   3017:     my ($nextflg) = 0;
1.524     raeburn  3018:     foreach my $item (sort 
1.294     albertel 3019: 	     {
                   3020: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3021: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3022: 		 }
                   3023: 		 return $a cmp $b;
                   3024: 	     } (keys(%$fullname))) {
1.41      ng       3025: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3026: 	    push(@parsedlist,$item);
1.41      ng       3027: 	}
1.524     raeburn  3028: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3029: 	if ($button eq 'Previous') {
1.524     raeburn  3030: 	    last if ($item eq $firststu);
                   3031: 	    push(@parsedlist,$item);
1.41      ng       3032: 	}
                   3033:     }
                   3034:     $ctr = 0;
                   3035:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3036:     my $res_error;
                   3037:     my ($partlist) = &response_type($symb,\$res_error);
                   3038:     if ($res_error) {
                   3039:         $request->print(&navmap_errormsg());
                   3040:         return;
                   3041:     }
1.41      ng       3042:     foreach my $student (@parsedlist) {
1.257     albertel 3043: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3044: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3045: 	
                   3046: 	if ($submitonly eq 'queued') {
                   3047: 	    my %queue_status = 
                   3048: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3049: 							$udom,$uname);
                   3050: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3051: 	}
                   3052: 
1.156     albertel 3053: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3054: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3055: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3056: 	    my $submitted = 0;
1.248     albertel 3057: 	    my $ungraded = 0;
                   3058: 	    my $incorrect = 0;
1.524     raeburn  3059: 	    foreach my $item (keys(%status)) {
                   3060: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3061: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3062: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3063: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3064: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3065: 		    $submitted = 0;
                   3066: 		}
1.41      ng       3067: 	    }
1.156     albertel 3068: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3069: 				     $submitonly eq 'incorrect' ||
                   3070: 				     $submitonly eq 'graded'));
1.248     albertel 3071: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3072: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3073: 	}
1.524     raeburn  3074: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3075: 	last if ($ctr == $ntstu);
1.41      ng       3076: 	$ctr++;
                   3077:     }
1.36      ng       3078: 
1.41      ng       3079:     $ctr = 0;
                   3080:     my $total = scalar(@nextlist)-1;
1.39      ng       3081: 
1.524     raeburn  3082:     foreach (sort(@nextlist)) {
1.41      ng       3083: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3084: 	$env{'form.student'}  = $uname;
                   3085: 	$env{'form.userdom'}  = $udom;
                   3086: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       3087: 	&submission($request,$ctr,$total);
                   3088: 	$ctr++;
                   3089:     }
                   3090:     if ($total < 0) {
1.485     albertel 3091: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  3092: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 3093: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 3094: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       3095: 	$request->print($the_end);
                   3096:     }
                   3097:     return '';
1.38      ng       3098: }
1.36      ng       3099: 
1.44      ng       3100: #---- Save the score and award for each student, if changed
1.38      ng       3101: sub saveHandGrade {
1.324     albertel 3102:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3103:     my @version_parts;
1.104     albertel 3104:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3105: 					   $env{'request.course.id'});
1.104     albertel 3106:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3107:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3108:     my @parts_graded;
1.77      ng       3109:     my %newrecord  = ();
                   3110:     my ($pts,$wgt) = ('','');
1.269     raeburn  3111:     my %aggregate = ();
                   3112:     my $aggregateflag = 0;
1.301     albertel 3113:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3114:     foreach my $new_part (@parts) {
1.337     banghart 3115: 	#collaborator ($submi may vary for different parts
1.259     banghart 3116: 	if ($submitter && $new_part ne $part) { next; }
                   3117: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3118: 	if ($dropMenu eq 'excused') {
1.259     banghart 3119: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3120: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3121: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3122: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3123: 		}
1.364     banghart 3124: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3125: 	    }
1.125     ng       3126: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3127: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3128: 	    foreach my $key (keys(%record)) {
1.259     banghart 3129: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3130: 	    }
1.259     banghart 3131: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3132: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3133:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3134: 
                   3135:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3136: 					       [$new_part]);
                   3137:             my $aggtries =$totaltries;
1.269     raeburn  3138:             if ($last_resets{$new_part}) {
1.270     albertel 3139:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3140: 					   $new_part);
1.269     raeburn  3141:             }
1.270     albertel 3142: 
                   3143:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3144:             if ($aggtries > 0) {
1.327     albertel 3145:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3146:                 $aggregateflag = 1;
                   3147:             }
1.125     ng       3148: 	} elsif ($dropMenu eq '') {
1.259     banghart 3149: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3150: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3151: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3152: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3153: 		next;
                   3154: 	    }
1.259     banghart 3155: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3156: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3157: 	    my $partial= $pts/$wgt;
1.259     banghart 3158: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3159: 		#do not update score for part if not changed.
1.346     banghart 3160:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3161: 		next;
1.251     banghart 3162: 	    } else {
1.524     raeburn  3163: 	        push(@parts_graded,$new_part);
1.153     albertel 3164: 	    }
1.259     banghart 3165: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3166: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3167: 	    }
1.259     banghart 3168: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3169: 	    if ($partial == 0) {
1.153     albertel 3170: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3171: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3172: 		}
1.41      ng       3173: 	    } else {
1.153     albertel 3174: 		if ($record{$reckey} ne 'correct_by_override') {
                   3175: 		    $newrecord{$reckey} = 'correct_by_override';
                   3176: 		}
                   3177: 	    }	    
                   3178: 	    if ($submitter && 
1.259     banghart 3179: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3180: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3181: 	    }
1.259     banghart 3182: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3183: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3184: 	}
1.259     banghart 3185: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3186: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3187: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3188: 	        $dropMenu eq 'reset status')
                   3189: 	   {
1.524     raeburn  3190: 	    push(@version_parts,$new_part);
1.259     banghart 3191: 	}
1.41      ng       3192:     }
1.301     albertel 3193:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3194:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3195: 
1.344     albertel 3196:     if (%newrecord) {
                   3197:         if (@version_parts) {
1.364     banghart 3198:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3199:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3200: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3201: 	    foreach my $new_part (@version_parts) {
                   3202: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3203: 				$new_part,\%newrecord);
                   3204: 	    }
1.259     banghart 3205:         }
1.44      ng       3206: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3207: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3208: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3209: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3210:     }
1.269     raeburn  3211:     if ($aggregateflag) {
                   3212:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3213: 			      $cdom,$cnum);
1.269     raeburn  3214:     }
1.301     albertel 3215:     return ('',$pts,$wgt);
1.36      ng       3216: }
1.322     albertel 3217: 
1.380     albertel 3218: sub check_and_remove_from_queue {
                   3219:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3220:     my @ungraded_parts;
                   3221:     foreach my $part (@{$parts}) {
                   3222: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3223: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3224: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3225: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3226: 		) {
                   3227: 	    push(@ungraded_parts, $part);
                   3228: 	}
                   3229:     }
                   3230:     if ( !@ungraded_parts ) {
                   3231: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3232: 					       $cnum,$domain,$stuname);
                   3233:     }
                   3234: }
                   3235: 
1.337     banghart 3236: sub handback_files {
                   3237:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3238:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3239:     my $res_error;
                   3240:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3241:     if ($res_error) {
                   3242:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3243:         return;
                   3244:     }
1.596.2.4  raeburn  3245:     my @handedback;
                   3246:     my $file_msg;
1.375     albertel 3247:     my @part_response_id = &flatten_responseType($responseType);
                   3248:     foreach my $part_response_id (@part_response_id) {
                   3249:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3250: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3251:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3252:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3253:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3254: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3255:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3256:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3257:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3258:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3259: 		        &file_name_version_ext($answer_file);
1.355     banghart 3260: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3261:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3262:):                     my ($dir_list,$listerror) =
                   3263:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3264:):                                                  $domain,$stuname,$getpropath);
                   3265:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3266:3):                     # fix filename
1.355     banghart 3267:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3268:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3269:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3270:             	                                $save_file_name);
1.337     banghart 3271:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3272:                         $request->print('<br /><span class="LC_error">'.
                   3273:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3274:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3275:                                         '</span>');
1.356     banghart 3276:                     } else {
1.360     banghart 3277:                         # mark the file as read only
1.596.2.4  raeburn  3278:                         push(@handedback,$save_file_name);
1.367     albertel 3279: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3280: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3281: 			}
                   3282:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3283: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3284: 
1.337     banghart 3285:                     }
1.596.2.12.2.  3(raebur 3286: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 3287:                 }
                   3288:             }
                   3289:         }
1.596.2.4  raeburn  3290:     }
                   3291:     if (@handedback > 0) {
                   3292:         $request->print('<br />');
                   3293:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3294:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3295:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3296:         my ($subject,$message);
                   3297:         if (scalar(@handedback) == 1) {
                   3298:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3299:         } else {
                   3300:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3301:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3302:         }
                   3303:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3304:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3305:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3306:         my ($feedurl,$showsymb) =
                   3307:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3308:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3309:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3310:         my $msgstatus =
                   3311:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3312:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3313:                  $restitle);
                   3314:         if ($msgstatus) {
                   3315:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3316:         }
                   3317:     }
1.338     banghart 3318:     return;
1.337     banghart 3319: }
                   3320: 
1.418     albertel 3321: sub get_feedurl_and_symb {
                   3322:     my ($symb,$uname,$udom) = @_;
                   3323:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3324:     $url = &Apache::lonnet::clutter($url);
                   3325:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3326: 					$symb,$udom,$uname);
                   3327:     if ($encrypturl =~ /^yes$/i) {
                   3328: 	&Apache::lonenc::encrypted(\$url,1);
                   3329: 	&Apache::lonenc::encrypted(\$symb,1);
                   3330:     }
                   3331:     return ($url,$symb);
                   3332: }
                   3333: 
1.313     banghart 3334: sub get_submitted_files {
                   3335:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3336:     my @files;
                   3337:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3338:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3339:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3340:     	    push(@files,$file_url.$file);
                   3341:         }
                   3342:     }
                   3343:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3344:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3345:     }
                   3346:     return (\@files);
                   3347: }
1.322     albertel 3348: 
1.269     raeburn  3349: # ----------- Provides number of tries since last reset.
                   3350: sub get_num_tries {
                   3351:     my ($record,$last_reset,$part) = @_;
                   3352:     my $timestamp = '';
                   3353:     my $num_tries = 0;
                   3354:     if ($$record{'version'}) {
                   3355:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3356:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3357:                 $timestamp = $$record{$version.':timestamp'};
                   3358:                 if ($timestamp > $last_reset) {
                   3359:                     $num_tries ++;
                   3360:                 } else {
                   3361:                     last;
                   3362:                 }
                   3363:             }
                   3364:         }
                   3365:     }
                   3366:     return $num_tries;
                   3367: }
                   3368: 
                   3369: # ----------- Determine decrements required in aggregate totals 
                   3370: sub decrement_aggs {
                   3371:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3372:     my %decrement = (
                   3373:                         attempts => 0,
                   3374:                         users => 0,
                   3375:                         correct => 0
                   3376:                     );
                   3377:     $decrement{'attempts'} = $aggtries;
                   3378:     if ($solvedstatus =~ /^correct/) {
                   3379:         $decrement{'correct'} = 1;
                   3380:     }
                   3381:     if ($aggtries == $totaltries) {
                   3382:         $decrement{'users'} = 1;
                   3383:     }
1.524     raeburn  3384:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3385:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3386:     }
                   3387:     return;
                   3388: }
                   3389: 
                   3390: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3391: sub get_last_resets {
1.270     albertel 3392:     my ($symb,$courseid,$partids) =@_;
                   3393:     my %last_resets;
1.269     raeburn  3394:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3395:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3396:     my @keys;
                   3397:     foreach my $part (@{$partids}) {
                   3398: 	push(@keys,"$symb\0$part\0resettime");
                   3399:     }
                   3400:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3401: 				     $cdom,$cname);
                   3402:     foreach my $part (@{$partids}) {
                   3403: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3404:     }
1.270     albertel 3405:     return %last_resets;
1.269     raeburn  3406: }
                   3407: 
1.251     banghart 3408: # ----------- Handles creating versions for portfolio files as answers
                   3409: sub version_portfiles {
1.343     banghart 3410:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3411:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3412:     my @returned_keys;
1.255     banghart 3413:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3414:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3415:     foreach my $key (keys(%$record)) {
1.259     banghart 3416:         my $new_portfiles;
1.263     banghart 3417:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3418:             my @versioned_portfiles;
1.367     albertel 3419:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3420:             foreach my $file (@portfiles) {
1.306     banghart 3421:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3422:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3423: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3424: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3425:):                 my $getpropath = 1;
                   3426:):                 my ($dir_list,$listerror) =
                   3427:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3428:):                                              $stu_name,$getpropath);
                   3429:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3430:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3431:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3432:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3433:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3434:                         [$directory.$new_answer],
1.306     banghart 3435:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3436:                 }
1.252     banghart 3437:             }
1.343     banghart 3438:             $$record{$key} = join(',',@versioned_portfiles);
                   3439:             push(@returned_keys,$key);
1.251     banghart 3440:         }
                   3441:     } 
1.343     banghart 3442:     return (@returned_keys);   
1.305     banghart 3443: }
                   3444: 
1.307     banghart 3445: sub get_next_version {
1.341     banghart 3446:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3447:     my $version;
1.596.2.12.2.  (raeburn 3448:):     if (ref($dir_list) eq 'ARRAY') {
                   3449:):         foreach my $row (@{$dir_list}) {
                   3450:):             my ($file) = split(/\&/,$row,2);
                   3451:):             my ($file_name,$file_version,$file_ext) =
                   3452:): 	        &file_name_version_ext($file);
                   3453:):             if (($file_name eq $answer_name) && 
                   3454:): 	        ($file_ext eq $answer_ext)) {
                   3455:):                 # gets here if filename and extension match, 
                   3456:):                 # regardless of version
1.307     banghart 3457:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3458:):                     # a versioned file is found  so save it for later
                   3459:):                     if ($file_version > $version) {
                   3460:): 		        $version = $file_version;
                   3461:):                     }
1.307     banghart 3462: 	        }
                   3463:             }
                   3464:         }
1.596.2.12.2.  (raeburn 3465:):     }
1.307     banghart 3466:     $version ++;
                   3467:     return($version);
                   3468: }
                   3469: 
1.305     banghart 3470: sub version_selected_portfile {
1.306     banghart 3471:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3472:     my ($answer_name,$answer_ver,$answer_ext) =
                   3473:         &file_name_version_ext($file_name);
                   3474:     my $new_answer;
                   3475:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3476:     if($env{'form.copy'} eq '-1') {
                   3477:         $new_answer = 'problem getting file';
                   3478:     } else {
                   3479:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3480:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3481:                             $stu_name,$domain,'copy',
                   3482: 		        '/portfolio'.$directory.$new_answer);
                   3483:     }    
                   3484:     return ($new_answer);
1.251     banghart 3485: }
                   3486: 
1.304     albertel 3487: sub file_name_version_ext {
                   3488:     my ($file)=@_;
                   3489:     my @file_parts = split(/\./, $file);
                   3490:     my ($name,$version,$ext);
                   3491:     if (@file_parts > 1) {
                   3492: 	$ext=pop(@file_parts);
                   3493: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3494: 	    $version=pop(@file_parts);
                   3495: 	}
                   3496: 	$name=join('.',@file_parts);
                   3497:     } else {
                   3498: 	$name=join('.',@file_parts);
                   3499:     }
                   3500:     return($name,$version,$ext);
                   3501: }
                   3502: 
1.44      ng       3503: #--------------------------------------------------------------------------------------
                   3504: #
                   3505: #-------------------------- Next few routines handles grading by section or whole class
                   3506: #
                   3507: #--- Javascript to handle grading by section or whole class
1.42      ng       3508: sub viewgrades_js {
                   3509:     my ($request) = shift;
                   3510: 
1.539     riegler  3511:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3512:     $request->print(<<VIEWJAVASCRIPT);
                   3513: <script type="text/javascript" language="javascript">
1.45      ng       3514:    function writePoint(partid,weight,point) {
1.125     ng       3515: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3516: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3517: 	if (point == "textval") {
1.125     ng       3518: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3519: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3520: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3521: 		var resetbox = false;
                   3522: 		for (var i=0; i<radioButton.length; i++) {
                   3523: 		    if (radioButton[i].checked) {
                   3524: 			textbox.value = i;
                   3525: 			resetbox = true;
                   3526: 		    }
                   3527: 		}
                   3528: 		if (!resetbox) {
                   3529: 		    textbox.value = "";
                   3530: 		}
                   3531: 		return;
                   3532: 	    }
1.109     matthew  3533: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3534: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3535: 				   ") greater than the weight for the part. Accept?");
                   3536: 		if (resp == false) {
                   3537: 		    textbox.value = "";
                   3538: 		    return;
                   3539: 		}
                   3540: 	    }
1.42      ng       3541: 	    for (var i=0; i<radioButton.length; i++) {
                   3542: 		radioButton[i].checked=false;
1.109     matthew  3543: 		if (parseFloat(point) == i) {
1.42      ng       3544: 		    radioButton[i].checked=true;
                   3545: 		}
                   3546: 	    }
1.41      ng       3547: 
1.42      ng       3548: 	} else {
1.125     ng       3549: 	    textbox.value = parseFloat(point);
1.42      ng       3550: 	}
1.41      ng       3551: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3552: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3553: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3554: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3555: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3556: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3557: 	    if (saveval != "correct") {
                   3558: 		scorename.value = point;
1.43      ng       3559: 		if (selname[0].selected != true) {
                   3560: 		    selname[0].selected = true;
                   3561: 		}
1.42      ng       3562: 	    }
                   3563: 	}
1.125     ng       3564: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3565:     }
                   3566: 
                   3567:     function writeRadText(partid,weight) {
1.125     ng       3568: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3569: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3570:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3571: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3572: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3573: 	    for (var i=0; i<radioButton.length; i++) {
                   3574: 		radioButton[i].checked=false;
                   3575: 
                   3576: 	    }
                   3577: 	    textbox.value = "";
                   3578: 
                   3579: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3580: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3581: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3582: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3583: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3584: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3585: 		if ((saveval != "correct") || override) {
1.42      ng       3586: 		    scorename.value = "";
1.125     ng       3587: 		    if (selval[1].selected) {
                   3588: 			selname[1].selected = true;
                   3589: 		    } else {
                   3590: 			selname[2].selected = true;
                   3591: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3592: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3593: 		    }
1.42      ng       3594: 		}
                   3595: 	    }
1.43      ng       3596: 	} else {
                   3597: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3598: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3599: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3600: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3601: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3602: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3603: 		if ((saveval != "correct") || override) {
1.125     ng       3604: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3605: 		    selname[0].selected = true;
                   3606: 		}
                   3607: 	    }
                   3608: 	}	    
1.42      ng       3609:     }
                   3610: 
                   3611:     function changeSelect(partid,user) {
1.125     ng       3612: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3613: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3614: 	var point  = textbox.value;
1.125     ng       3615: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3616: 
1.109     matthew  3617: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3618: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3619: 	    textbox.value = "";
                   3620: 	    return;
                   3621: 	}
1.109     matthew  3622: 	if (parseFloat(point) > parseFloat(weight)) {
                   3623: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3624: 			       ") greater than the weight of the part. Accept?");
                   3625: 	    if (resp == false) {
                   3626: 		textbox.value = "";
                   3627: 		return;
                   3628: 	    }
                   3629: 	}
1.42      ng       3630: 	selval[0].selected = true;
                   3631:     }
                   3632: 
                   3633:     function changeOneScore(partid,user) {
1.125     ng       3634: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3635: 	if (selval[1].selected || selval[2].selected) {
                   3636: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3637: 	    if (selval[2].selected) {
                   3638: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3639: 	    }
1.269     raeburn  3640:         }
1.42      ng       3641:     }
                   3642: 
                   3643:     function resetEntry(numpart) {
                   3644: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3645: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3646: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3647: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3648: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3649: 	    for (var i=0; i<radioButton.length; i++) {
                   3650: 		radioButton[i].checked=false;
                   3651: 
                   3652: 	    }
                   3653: 	    textbox.value = "";
                   3654: 	    selval[0].selected = true;
                   3655: 
                   3656: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3657: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3658: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3659: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3660: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3661: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3662: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3663: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3664: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3665: 		if (saveselval == "excused") {
1.43      ng       3666: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3667: 		} else {
1.43      ng       3668: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3669: 		}
                   3670: 	    }
1.41      ng       3671: 	}
1.42      ng       3672:     }
                   3673: 
1.41      ng       3674: </script>
                   3675: VIEWJAVASCRIPT
1.42      ng       3676: }
                   3677: 
1.44      ng       3678: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3679: sub viewgrades {
                   3680:     my ($request) = shift;
                   3681:     &viewgrades_js($request);
1.41      ng       3682: 
1.324     albertel 3683:     my ($symb) = &get_symb($request);
1.168     albertel 3684:     #need to make sure we have the correct data for later EXT calls, 
                   3685:     #thus invalidate the cache
                   3686:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3687:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3688:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3689:     &Apache::lonnet::clear_EXT_cache_status();
                   3690: 
1.398     albertel 3691:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.596.2.12.2.  9(raebur 3692:3):     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3693: 
                   3694:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3695:     $result.=&jscriptNform($symb);
1.41      ng       3696: 
1.44      ng       3697:     #beginning of class grading form
1.442     banghart 3698:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3699:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3700: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3701: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3702: 	&build_section_inputs().
1.257     albertel 3703: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3704: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3705: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3706: 
1.560     raeburn  3707:     my ($common_header,$specific_header);
1.257     albertel 3708:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3709: 	$common_header = &mt('Assign Common Grade to Class');
                   3710:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3711:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3712:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3713: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3714:     } else {
1.560     raeburn  3715:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3716:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3717: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3718:     }
1.560     raeburn  3719:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3720:     #radio buttons/text box for assigning points for a section or class.
                   3721:     #handles different parts of a problem
1.582     raeburn  3722:     my $res_error;
                   3723:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3724:     if ($res_error) {
                   3725:         return &navmap_errormsg();
                   3726:     }
1.42      ng       3727:     my %weight = ();
                   3728:     my $ctsparts = 0;
1.45      ng       3729:     my %seen = ();
1.375     albertel 3730:     my @part_response_id = &flatten_responseType($responseType);
                   3731:     foreach my $part_response_id (@part_response_id) {
                   3732:     	my ($partid,$respid) = @{ $part_response_id };
                   3733: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3734: 	next if $seen{$partid};
                   3735: 	$seen{$partid}++;
1.375     albertel 3736: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3737: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3738: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3739: 
1.324     albertel 3740: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3741: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3742: 	my $ctr = 0;
1.42      ng       3743: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3744: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3745: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3746: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3747: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3748: 	    $ctr++;
                   3749: 	}
1.485     albertel 3750: 	$radio.='</tr></table>';
                   3751: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3752: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3753: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3754: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 3755:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3756:3):                 '<select name="SELVAL_'.$partid.'" '.
                   3757:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3758: 		$weight{$partid}.')"> '.
1.401     albertel 3759: 	    '<option selected="selected"> </option>'.
1.485     albertel 3760: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3761: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3762: 	    '</select></td>'.
                   3763:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3764: 	$line.='<input type="hidden" name="partid_'.
                   3765: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3766: 	$line.='<input type="hidden" name="weight_'.
                   3767: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3768: 
                   3769: 	$result.=
                   3770: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3771: 	    '<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 3772: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3773: 	$ctsparts++;
1.41      ng       3774:     }
1.474     albertel 3775:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3776: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3777:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3778: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3779: 
1.44      ng       3780:     #table listing all the students in a section/class
                   3781:     #header of table
1.560     raeburn  3782:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3783:               &Apache::loncommon::start_data_table().
                   3784: 	      &Apache::loncommon::start_data_table_header_row().
                   3785: 	      '<th>'.&mt('No.').'</th>'.
                   3786: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3787:     my $partserror;
                   3788:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3789:     if ($partserror) {
                   3790:         return &navmap_errormsg();
                   3791:     }
1.324     albertel 3792:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3793:     my @partids = ();
1.41      ng       3794:     foreach my $part (@parts) {
                   3795: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3796:         my $narrowtext = &mt('Tries');
                   3797: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3798: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3799: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3800:         push(@partids,$partid);
1.324     albertel 3801: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3802: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3803: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 3804:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   3805:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3806: 	    next;
1.485     albertel 3807: 	    
1.207     albertel 3808: 	} else {
1.485     albertel 3809: 	    if ($display =~ /Problem Status/) {
                   3810: 		my $grade_status_mt = &mt('Grade Status');
                   3811: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3812: 	    }
                   3813: 	    my $part_mt = &mt('Part:');
                   3814: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3815: 	}
1.485     albertel 3816: 
1.474     albertel 3817: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3818:     }
1.474     albertel 3819:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3820: 
1.270     albertel 3821:     my %last_resets = 
                   3822: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3823: 
1.41      ng       3824:     #get info for each student
1.44      ng       3825:     #list all the students - with points and grade status
1.257     albertel 3826:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3827:     my $ctr = 0;
1.294     albertel 3828:     foreach (sort 
                   3829: 	     {
                   3830: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3831: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3832: 		 }
                   3833: 		 return $a cmp $b;
                   3834: 	     } (keys(%$fullname))) {
1.126     ng       3835: 	$ctr++;
1.324     albertel 3836: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3837: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3838:     }
1.474     albertel 3839:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3840:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3841:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3842: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3843:     if (scalar(%$fullname) eq 0) {
                   3844: 	my $colspan=3+scalar(@parts);
1.433     banghart 3845: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3846:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3847: 	$result='<span class="LC_warning">'.
1.485     albertel 3848: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3849: 	        $section_display, $stu_status).
1.433     banghart 3850: 	    '</span>';
1.96      albertel 3851:     }
1.324     albertel 3852:     $result.=&show_grading_menu_form($symb);
1.41      ng       3853:     return $result;
                   3854: }
                   3855: 
1.44      ng       3856: #--- call by previous routine to display each student
1.41      ng       3857: sub viewstudentgrade {
1.324     albertel 3858:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3859:     my ($uname,$udom) = split(/:/,$student);
                   3860:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3861:     my %aggregates = (); 
1.474     albertel 3862:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3863: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3864: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3865: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3866: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3867: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3868:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3869:     foreach my $apart (@$parts) {
                   3870: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3871: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3872:         $result.='<td align="center">';
1.269     raeburn  3873:         my ($aggtries,$totaltries);
                   3874:         unless (exists($aggregates{$part})) {
1.270     albertel 3875: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3876: 
                   3877: 	    $aggtries = $totaltries;
1.269     raeburn  3878:             if ($$last_resets{$part}) {  
1.270     albertel 3879:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3880: 					   $part);
                   3881:             }
1.269     raeburn  3882:             $result.='<input type="hidden" name="'.
                   3883:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3884:             $result.='<input type="hidden" name="'.
                   3885:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3886:             $aggregates{$part} = 1;
                   3887:         }
1.41      ng       3888: 	if ($type eq 'awarded') {
1.320     albertel 3889: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3890: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3891: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3892: 	    $result.='<input type="text" name="'.
1.89      albertel 3893: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3894:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3895: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3896: 	} elsif ($type eq 'solved') {
                   3897: 	    my ($status,$foo)=split(/_/,$score,2);
                   3898: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3899: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3900: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3901: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3902: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3903:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3904: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3905: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3906: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3907: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3908: 	} else {
                   3909: 	    $result.='<input type="hidden" name="'.
                   3910: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3911: 		    "\n";
1.233     albertel 3912: 	    $result.='<input type="text" name="'.
1.122     ng       3913: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3914: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3915: 	}
                   3916:     }
1.474     albertel 3917:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3918:     return $result;
1.38      ng       3919: }
                   3920: 
1.44      ng       3921: #--- change scores for all the students in a section/class
                   3922: #    record does not get update if unchanged
1.38      ng       3923: sub editgrades {
1.41      ng       3924:     my ($request) = @_;
                   3925: 
1.596.2.12.2.  (raeburn 3926:):     my ($symb)=&get_symb($request);
1.433     banghart 3927:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3928:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 3929:3):     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
                   3930:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       3931: 
1.477     albertel 3932:     my $result= &Apache::loncommon::start_data_table().
                   3933: 	&Apache::loncommon::start_data_table_header_row().
                   3934: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3935: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3936:     my %scoreptr = (
                   3937: 		    'correct'  =>'correct_by_override',
                   3938: 		    'incorrect'=>'incorrect_by_override',
                   3939: 		    'excused'  =>'excused',
                   3940: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3941:                     'credited' =>'credit_attempted',
1.43      ng       3942: 		    'nothing'  => '',
                   3943: 		    );
1.257     albertel 3944:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3945: 
1.44      ng       3946:     my (@partid);
                   3947:     my %weight = ();
1.54      albertel 3948:     my %columns = ();
1.44      ng       3949:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3950: 
1.582     raeburn  3951:     my $partserror;
                   3952:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3953:     if ($partserror) {
                   3954:         return &navmap_errormsg();
                   3955:     }
1.54      albertel 3956:     my $header;
1.257     albertel 3957:     while ($ctr < $env{'form.totalparts'}) {
                   3958: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3959: 	push(@partid,$partid);
1.257     albertel 3960: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3961: 	$ctr++;
1.54      albertel 3962:     }
1.324     albertel 3963:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3964:     foreach my $partid (@partid) {
1.478     albertel 3965: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3966: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3967: 	$columns{$partid}=2;
                   3968: 	foreach my $stores (@parts) {
                   3969: 	    my ($part,$type) = &split_part_type($stores);
                   3970: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3971: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3972: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3973: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3974:             my $narrowtext = &mt('Tries');
                   3975: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3976: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3977: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3978: 	    $columns{$partid}+=2;
                   3979: 	}
                   3980:     }
                   3981:     foreach my $partid (@partid) {
1.324     albertel 3982: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3983: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3984: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3985: 	    '</th>';
1.54      albertel 3986: 
1.44      ng       3987:     }
1.477     albertel 3988:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3989: 	&Apache::loncommon::start_data_table_header_row().
                   3990: 	$header.
                   3991: 	&Apache::loncommon::end_data_table_header_row();
                   3992:     my @noupdate;
1.126     ng       3993:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3994:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3995: 	my $line;
1.257     albertel 3996: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3997: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3998: 	my %newrecord;
                   3999: 	my $updateflag = 0;
1.281     albertel 4000: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 4001: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 4002: 	if (!&canmodify($usec)) {
1.126     ng       4003: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 4004: 	    push(@noupdate,
1.478     albertel 4005: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   4006: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 4007: 	    next;
                   4008: 	}
1.269     raeburn  4009:         my %aggregate = ();
                   4010:         my $aggregateflag = 0;
1.281     albertel 4011: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4012: 	foreach (@partid) {
1.257     albertel 4013: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4014: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4015: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4016: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4017: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4018: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4019: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4020: 	    my $score;
                   4021: 	    if ($partial eq '') {
1.257     albertel 4022: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4023: 	    } elsif ($partial > 0) {
                   4024: 		$score = 'correct_by_override';
                   4025: 	    } elsif ($partial == 0) {
                   4026: 		$score = 'incorrect_by_override';
                   4027: 	    }
1.257     albertel 4028: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4029: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4030: 
1.292     albertel 4031: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4032: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4033: 	    if ($dropMenu eq 'reset status' &&
                   4034: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4035: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4036: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4037: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4038: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4039: 		$updateflag = 1;
1.269     raeburn  4040:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4041:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4042:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4043:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4044:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4045:                     $aggregateflag = 1;
                   4046:                 }
1.139     albertel 4047: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4048: 		$updateflag = 1;
                   4049: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4050: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4051: 		$rec_update++;
1.125     ng       4052: 	    }
                   4053: 
1.93      albertel 4054: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4055: 		'<td align="center">'.$awarded.
                   4056: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4057: 
1.54      albertel 4058: 
                   4059: 	    my $partid=$_;
                   4060: 	    foreach my $stores (@parts) {
                   4061: 		my ($part,$type) = &split_part_type($stores);
                   4062: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4063: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4064: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4065: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4066: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4067: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4068: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4069: 		    $updateflag=1;
                   4070: 		}
1.93      albertel 4071: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4072: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4073: 	    }
1.44      ng       4074: 	}
1.477     albertel 4075: 	$line.="\n";
1.301     albertel 4076: 
                   4077: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4078: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4079: 
1.44      ng       4080: 	if ($updateflag) {
                   4081: 	    $count++;
1.257     albertel 4082: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4083: 				    $udom,$uname);
1.301     albertel 4084: 
                   4085: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4086: 					      $cnum,$udom,$uname)) {
                   4087: 		# need to figure out if should be in queue.
                   4088: 		my %record =  
                   4089: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4090: 					     $udom,$uname);
                   4091: 		my $all_graded = 1;
                   4092: 		my $none_graded = 1;
                   4093: 		foreach my $part (@parts) {
                   4094: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4095: 			$all_graded = 0;
                   4096: 		    } else {
                   4097: 			$none_graded = 0;
                   4098: 		    }
                   4099: 		}
                   4100: 
                   4101: 		if ($all_graded || $none_graded) {
                   4102: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4103: 							   $symb,$cdom,$cnum,
                   4104: 							   $udom,$uname);
                   4105: 		}
                   4106: 	    }
                   4107: 
1.477     albertel 4108: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4109: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4110: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4111: 	    $updateCtr++;
1.93      albertel 4112: 	} else {
1.477     albertel 4113: 	    push(@noupdate,
                   4114: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4115: 	    $noupdateCtr++;
1.44      ng       4116: 	}
1.269     raeburn  4117:         if ($aggregateflag) {
                   4118:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4119: 				  $cdom,$cnum);
1.269     raeburn  4120:         }
1.93      albertel 4121:     }
1.477     albertel 4122:     if (@noupdate) {
1.126     ng       4123: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4124: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4125: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4126: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4127: 	    &mt('No Changes Occurred For the Students Below').
                   4128: 	    '</td>'.
1.477     albertel 4129: 	    &Apache::loncommon::end_data_table_row();
                   4130: 	foreach my $line (@noupdate) {
                   4131: 	    $result.=
                   4132: 		&Apache::loncommon::start_data_table_row().
                   4133: 		$line.
                   4134: 		&Apache::loncommon::end_data_table_row();
                   4135: 	}
1.44      ng       4136:     }
1.477     albertel 4137:     $result .= &Apache::loncommon::end_data_table().
                   4138: 	&show_grading_menu_form($symb);
1.478     albertel 4139:     my $msg = '<p><b>'.
                   4140: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4141: 	    $rec_update,$count).'</b><br />'.
                   4142: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4143: 	'</b></p>';
1.44      ng       4144:     return $title.$msg.$result;
1.5       albertel 4145: }
1.54      albertel 4146: 
                   4147: sub split_part_type {
                   4148:     my ($partstr) = @_;
                   4149:     my ($temp,@allparts)=split(/_/,$partstr);
                   4150:     my $type=pop(@allparts);
1.439     albertel 4151:     my $part=join('_',@allparts);
1.54      albertel 4152:     return ($part,$type);
                   4153: }
                   4154: 
1.44      ng       4155: #------------- end of section for handling grading by section/class ---------
                   4156: #
                   4157: #----------------------------------------------------------------------------
                   4158: 
1.5       albertel 4159: 
1.44      ng       4160: #----------------------------------------------------------------------------
                   4161: #
                   4162: #-------------------------- Next few routines handles grading by csv upload
                   4163: #
                   4164: #--- Javascript to handle csv upload
1.27      albertel 4165: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4166:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4167:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4168:   return(<<ENDPICK);
                   4169:   function verify(vf) {
                   4170:     var foundsomething=0;
                   4171:     var founduname=0;
1.243     albertel 4172:     var foundID=0;
1.27      albertel 4173:     for (i=0;i<=vf.nfields.value;i++) {
                   4174:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4175:       if (i==0 && tw!=0) { foundID=1; }
                   4176:       if (i==1 && tw!=0) { founduname=1; }
                   4177:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4178:     }
1.246     albertel 4179:     if (founduname==0 && foundID==0) {
                   4180: 	alert('$error1');
                   4181: 	return;
1.27      albertel 4182:     }
                   4183:     if (foundsomething==0) {
1.246     albertel 4184: 	alert('$error2');
                   4185: 	return;
1.27      albertel 4186:     }
                   4187:     vf.submit();
                   4188:   }
                   4189:   function flip(vf,tf) {
                   4190:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4191:     var i;
                   4192:     for (i=0;i<=vf.nfields.value;i++) {
                   4193:       //can not pick the same destination field for both name and domain
                   4194:       if (((i ==0)||(i ==1)) && 
                   4195:           ((tf==0)||(tf==1)) && 
                   4196:           (i!=tf) &&
                   4197:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4198:         eval('vf.f'+i+'.selectedIndex=0;')
                   4199:       }
                   4200:     }
                   4201:   }
                   4202: ENDPICK
                   4203: }
                   4204: 
                   4205: sub csvupload_javascript_forward_associate {
1.573     bisitz   4206:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4207:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4208:   return(<<ENDPICK);
                   4209:   function verify(vf) {
                   4210:     var foundsomething=0;
                   4211:     var founduname=0;
1.243     albertel 4212:     var foundID=0;
1.27      albertel 4213:     for (i=0;i<=vf.nfields.value;i++) {
                   4214:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4215:       if (tw==1) { foundID=1; }
                   4216:       if (tw==2) { founduname=1; }
                   4217:       if (tw>3) { foundsomething=1; }
1.27      albertel 4218:     }
1.246     albertel 4219:     if (founduname==0 && foundID==0) {
                   4220: 	alert('$error1');
                   4221: 	return;
1.27      albertel 4222:     }
                   4223:     if (foundsomething==0) {
1.246     albertel 4224: 	alert('$error2');
                   4225: 	return;
1.27      albertel 4226:     }
                   4227:     vf.submit();
                   4228:   }
                   4229:   function flip(vf,tf) {
                   4230:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4231:     var i;
                   4232:     //can not pick the same destination field twice
                   4233:     for (i=0;i<=vf.nfields.value;i++) {
                   4234:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4235:         eval('vf.f'+i+'.selectedIndex=0;')
                   4236:       }
                   4237:     }
                   4238:   }
                   4239: ENDPICK
                   4240: }
                   4241: 
1.26      albertel 4242: sub csvuploadmap_header {
1.324     albertel 4243:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4244:     my $javascript;
1.257     albertel 4245:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4246: 	$javascript=&csvupload_javascript_reverse_associate();
                   4247:     } else {
                   4248: 	$javascript=&csvupload_javascript_forward_associate();
                   4249:     }
1.45      ng       4250: 
1.324     albertel 4251:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 4252:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4253:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4254:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       4255:     $request->print(<<ENDPICK);
1.26      albertel 4256: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4257: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       4258: $result
1.326     albertel 4259: <hr />
1.26      albertel 4260: <h3>Identify fields</h3>
                   4261: Total number of records found in file: $distotal <hr />
                   4262: Enter as many fields as you can. The system will inform you and bring you back
                   4263: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4264: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4265: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4266: <input type="hidden" name="associate"  value="" />
                   4267: <input type="hidden" name="phase"      value="three" />
                   4268: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4269: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4270: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4271: <input type="hidden" name="upfile_associate" 
1.257     albertel 4272:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4273: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4274: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4275: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4276: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4277: <hr />
                   4278: <script type="text/javascript" language="Javascript">
                   4279: $javascript
                   4280: </script>
                   4281: ENDPICK
1.118     ng       4282:     return '';
1.26      albertel 4283: 
                   4284: }
                   4285: 
                   4286: sub csvupload_fields {
1.582     raeburn  4287:     my ($symb,$errorref) = @_;
                   4288:     my (@parts) = &getpartlist($symb,$errorref);
                   4289:     if (ref($errorref)) {
                   4290:         if ($$errorref) {
                   4291:             return;
                   4292:         }
                   4293:     }
                   4294: 
1.556     weissno  4295:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4296: 		['username','Student Username'],
                   4297: 		['domain','Student Domain']);
1.324     albertel 4298:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4299:     foreach my $part (sort(@parts)) {
                   4300: 	my @datum;
                   4301: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4302: 	my $name=$part;
                   4303: 	if  (!$display) { $display = $name; }
                   4304: 	@datum=($name,$display);
1.244     albertel 4305: 	if ($name=~/^stores_(.*)_awarded/) {
                   4306: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4307: 	}
1.41      ng       4308: 	push(@fields,\@datum);
                   4309:     }
                   4310:     return (@fields);
1.26      albertel 4311: }
                   4312: 
                   4313: sub csvuploadmap_footer {
1.41      ng       4314:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4315:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4316:     $request->print(<<ENDPICK);
1.26      albertel 4317: </table>
                   4318: <input type="hidden" name="nfields" value="$i" />
                   4319: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4320:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4321: </form>
                   4322: ENDPICK
                   4323: }
                   4324: 
1.283     albertel 4325: sub checkforfile_js {
1.539     riegler  4326:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       4327:     my $result =<<CSVFORMJS;
                   4328: <script type="text/javascript" language="javascript">
                   4329:     function checkUpload(formname) {
                   4330: 	if (formname.upfile.value == "") {
1.539     riegler  4331: 	    alert("$alertmsg");
1.86      ng       4332: 	    return false;
                   4333: 	}
                   4334: 	formname.submit();
                   4335:     }
                   4336:     </script>
                   4337: CSVFORMJS
1.283     albertel 4338:     return $result;
                   4339: }
                   4340: 
                   4341: sub upcsvScores_form {
                   4342:     my ($request) = shift;
1.324     albertel 4343:     my ($symb)=&get_symb($request);
1.283     albertel 4344:     if (!$symb) {return '';}
                   4345:     my $result=&checkforfile_js();
1.257     albertel 4346:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4347:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4348:     $result.=$table;
1.326     albertel 4349:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4350:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4351:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4352: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4353:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4354:     my $upload=&mt("Upload Scores");
1.86      ng       4355:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4356:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4357:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4358:     $result.=<<ENDUPFORM;
1.106     albertel 4359: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4360: <input type="hidden" name="symb" value="$symb" />
                   4361: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4362: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4363: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4364: $upfile_select
1.589     bisitz   4365: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4366: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4367: </form>
                   4368: ENDUPFORM
1.370     www      4369:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4370:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4371:     .'</td></tr></table>'."\n";
1.86      ng       4372:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4373:     $result.=&show_grading_menu_form($symb);
1.86      ng       4374:     return $result;
                   4375: }
                   4376: 
                   4377: 
1.26      albertel 4378: sub csvuploadmap {
1.41      ng       4379:     my ($request)= @_;
1.324     albertel 4380:     my ($symb)=&get_symb($request);
1.41      ng       4381:     if (!$symb) {return '';}
1.72      ng       4382: 
1.41      ng       4383:     my $datatoken;
1.257     albertel 4384:     if (!$env{'form.datatoken'}) {
1.41      ng       4385: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4386:     } else {
1.257     albertel 4387: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4388: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4389:     }
1.41      ng       4390:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4391:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4392:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4393:     my ($i,$keyfields);
                   4394:     if (@records) {
1.582     raeburn  4395:         my $fieldserror;
                   4396: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4397:         if ($fieldserror) {
                   4398:             $request->print(&navmap_errormsg());
                   4399:             return;
                   4400:         }
1.257     albertel 4401: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4402: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4403: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4404: 							  \@fields);
                   4405: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4406: 	    chop($keyfields);
                   4407: 	} else {
                   4408: 	    unshift(@fields,['none','']);
                   4409: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4410: 							    \@fields);
1.311     banghart 4411:             foreach my $rec (@records) {
                   4412:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4413:                 if (%temp) {
                   4414:                     $keyfields=join(',',sort(keys(%temp)));
                   4415:                     last;
                   4416:                 }
                   4417:             }
1.41      ng       4418: 	}
                   4419:     }
                   4420:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4421:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4422: 
1.41      ng       4423:     return '';
1.27      albertel 4424: }
                   4425: 
1.246     albertel 4426: sub csvuploadoptions {
1.41      ng       4427:     my ($request)= @_;
1.324     albertel 4428:     my ($symb)=&get_symb($request);
1.257     albertel 4429:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4430:     my $ignore=&mt('Ignore First Line');
                   4431:     $request->print(<<ENDPICK);
                   4432: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4433: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4434: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4435: <!--
1.246     albertel 4436: <p>
                   4437: <label>
                   4438:    <input type="checkbox" name="show_full_results" />
                   4439:    Show a table of all changes
                   4440: </label>
                   4441: </p>
1.302     albertel 4442: -->
1.246     albertel 4443: <p>
                   4444: <label>
                   4445:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4446:    Overwrite any existing score
                   4447: </label>
                   4448: </p>
                   4449: ENDPICK
                   4450:     my %fields=&get_fields();
                   4451:     if (!defined($fields{'domain'})) {
1.257     albertel 4452: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4453: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4454:     }
1.257     albertel 4455:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4456: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4457: 	my $cleankey=$1;
                   4458: 	if ($cleankey eq 'command') { next; }
                   4459: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4460: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4461:     }
                   4462:     # FIXME do a check for any duplicated user ids...
                   4463:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4464:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4465: <hr /></form>'."\n");
1.324     albertel 4466:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4467:     return '';
                   4468: }
                   4469: 
                   4470: sub get_fields {
                   4471:     my %fields;
1.257     albertel 4472:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4473:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4474: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4475: 	    if ($env{'form.f'.$i} ne 'none') {
                   4476: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4477: 	    }
                   4478: 	} else {
1.257     albertel 4479: 	    if ($env{'form.f'.$i} ne 'none') {
                   4480: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4481: 	    }
                   4482: 	}
1.27      albertel 4483:     }
1.246     albertel 4484:     return %fields;
                   4485: }
                   4486: 
                   4487: sub csvuploadassign {
                   4488:     my ($request)= @_;
1.324     albertel 4489:     my ($symb)=&get_symb($request);
1.246     albertel 4490:     if (!$symb) {return '';}
1.345     bowersj2 4491:     my $error_msg = '';
1.246     albertel 4492:     &Apache::loncommon::load_tmp_file($request);
                   4493:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4494:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4495:     my %fields=&get_fields();
1.41      ng       4496:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4497:     my $courseid=$env{'request.course.id'};
1.97      albertel 4498:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4499:     my @notallowed;
1.41      ng       4500:     my @skipped;
1.596.2.4  raeburn  4501:     my @warnings;
1.41      ng       4502:     my $countdone=0;
                   4503:     foreach my $grade (@gradedata) {
                   4504: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4505: 	my $domain;
                   4506: 	if ($entries{$fields{'domain'}}) {
                   4507: 	    $domain=$entries{$fields{'domain'}};
                   4508: 	} else {
1.257     albertel 4509: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4510: 	}
1.243     albertel 4511: 	$domain=~s/\s//g;
1.41      ng       4512: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4513: 	$username=~s/\s//g;
1.243     albertel 4514: 	if (!$username) {
                   4515: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4516: 	    $id=~s/\s//g;
1.243     albertel 4517: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4518: 	    $username=$ids{$id};
                   4519: 	}
1.41      ng       4520: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4521: 	    my $id=$entries{$fields{'ID'}};
                   4522: 	    $id=~s/\s//g;
                   4523: 	    if ($id) {
                   4524: 		push(@skipped,"$id:$domain");
                   4525: 	    } else {
                   4526: 		push(@skipped,"$username:$domain");
                   4527: 	    }
1.41      ng       4528: 	    next;
                   4529: 	}
1.108     albertel 4530: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4531: 	if (!&canmodify($usec)) {
                   4532: 	    push(@notallowed,"$username:$domain");
                   4533: 	    next;
                   4534: 	}
1.244     albertel 4535: 	my %points;
1.41      ng       4536: 	my %grades;
                   4537: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4538: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4539: 		$dest eq 'domain') { next; }
                   4540: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4541: 	    if ($dest=~/stores_(.*)_points/) {
                   4542: 		my $part=$1;
                   4543: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4544: 					      $symb,$domain,$username);
1.345     bowersj2 4545:                 if ($wgt) {
                   4546:                     $entries{$fields{$dest}}=~s/\s//g;
                   4547:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4548:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4549:                                           : 'correct_by_override';
1.596.2.4  raeburn  4550:                     if ($pcr>1) {
                   4551:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4552:                     }
1.345     bowersj2 4553:                     $grades{"resource.$part.awarded"}=$pcr;
                   4554:                     $grades{"resource.$part.solved"}=$award;
                   4555:                     $points{$part}=1;
                   4556:                 } else {
                   4557:                     $error_msg = "<br />" .
                   4558:                         &mt("Some point values were assigned"
                   4559:                             ." for problems with a weight "
                   4560:                             ."of zero. These values were "
                   4561:                             ."ignored.");
                   4562:                 }
1.244     albertel 4563: 	    } else {
                   4564: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4565: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4566: 		my $store_key=$dest;
                   4567: 		$store_key=~s/^stores/resource/;
                   4568: 		$store_key=~s/_/\./g;
                   4569: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4570: 	    }
1.41      ng       4571: 	}
1.508     www      4572: 	if (! %grades) { 
                   4573:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4574:         } else {
                   4575: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4576: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4577: 					   $env{'request.course.id'},
                   4578: 					   $domain,$username);
1.508     www      4579: 	   if ($result eq 'ok') {
                   4580: 	      $request->print('.');
1.596.2.4  raeburn  4581: # Remove from grading queue
                   4582:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4583:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4584:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4585:                                              $domain,$username);
1.508     www      4586: 	   } else {
                   4587: 	      $request->print("<p><span class=\"LC_error\">".
                   4588:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4589:                                   "$username:$domain",$result)."</span></p>");
                   4590: 	   }
                   4591: 	   $request->rflush();
                   4592: 	   $countdone++;
                   4593:         }
1.41      ng       4594:     }
1.570     www      4595:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4596:     if (@warnings) {
                   4597:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4598:         $request->print(join(', ',@warnings));
                   4599:     }
1.41      ng       4600:     if (@skipped) {
1.571     www      4601: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4602:         $request->print(join(', ',@skipped));
1.106     albertel 4603:     }
                   4604:     if (@notallowed) {
1.571     www      4605: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4606: 	$request->print(join(', ',@notallowed));
1.41      ng       4607:     }
1.106     albertel 4608:     $request->print("<br />\n");
1.324     albertel 4609:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4610:     return $error_msg;
1.26      albertel 4611: }
1.44      ng       4612: #------------- end of section for handling csv file upload ---------
                   4613: #
                   4614: #-------------------------------------------------------------------
                   4615: #
1.122     ng       4616: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4617: #
                   4618: #--- Select a page/sequence and a student to grade
1.68      ng       4619: sub pickStudentPage {
                   4620:     my ($request) = shift;
                   4621: 
1.539     riegler  4622:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4623:     $request->print(<<LISTJAVASCRIPT);
                   4624: <script type="text/javascript" language="javascript">
                   4625: 
                   4626: function checkPickOne(formname) {
1.76      ng       4627:     if (radioSelection(formname.student) == null) {
1.539     riegler  4628: 	alert("$alertmsg");
1.68      ng       4629: 	return;
                   4630:     }
1.125     ng       4631:     ptr = pullDownSelection(formname.selectpage);
                   4632:     formname.page.value = formname["page"+ptr].value;
                   4633:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4634:     formname.submit();
                   4635: }
                   4636: 
                   4637: </script>
                   4638: LISTJAVASCRIPT
1.118     ng       4639:     &commonJSfunctions($request);
1.324     albertel 4640:     my ($symb) = &get_symb($request);
1.257     albertel 4641:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4642:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4643:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4644: 
1.398     albertel 4645:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4646: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4647: 
1.80      ng       4648:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4649:     my $map_error;
                   4650:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4651:     if ($map_error) {
                   4652:         $request->print(&navmap_errormsg());
                   4653:         return; 
                   4654:     }
1.137     albertel 4655:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4656: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4657: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4658:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4659:     my $ctr=0;
1.68      ng       4660:     foreach (@$titles) {
                   4661: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4662: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4663: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4664: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4665: 	$ctr++;
1.68      ng       4666:     }
1.485     albertel 4667:     $select.= '</select>';
1.539     riegler  4668:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4669: 
1.70      ng       4670:     $ctr=0;
                   4671:     foreach (@$titles) {
                   4672: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4673: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4674: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4675: 	$ctr++;
                   4676:     }
1.72      ng       4677:     $result.='<input type="hidden" name="page" />'."\n".
                   4678: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4679: 
1.485     albertel 4680:     my $options =
                   4681: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4682: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4683:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4684: 
                   4685:     $options =
                   4686: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4687: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4688: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4689:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4690:     
                   4691:     $result.=&build_section_inputs();
1.442     banghart 4692:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4693:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4694: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4695: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4696: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4697: 
1.539     riegler  4698:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4699: 
1.80      ng       4700:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4701:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4702: 
1.68      ng       4703:     $request->print($result);
                   4704: 
1.485     albertel 4705:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4706: 	&Apache::loncommon::start_data_table().
                   4707: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4708: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4709: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4710: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4711: 	'<th>'.&nameUserString('header').'</th>'.
                   4712: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4713:  
1.76      ng       4714:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4715:     my $ptr = 1;
1.294     albertel 4716:     foreach my $student (sort 
                   4717: 			 {
                   4718: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4719: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4720: 			     }
                   4721: 			     return $a cmp $b;
                   4722: 			 } (keys(%$fullname))) {
1.68      ng       4723: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4724: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4725:                                   : '</td>');
1.126     ng       4726: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4727: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4728: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4729: 	$studentTable.=
                   4730: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4731:                          : '');
1.68      ng       4732: 	$ptr++;
                   4733:     }
1.484     albertel 4734:     if ($ptr%2 == 0) {
                   4735: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4736: 	    &Apache::loncommon::end_data_table_row();
                   4737:     }
                   4738:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4739:     $studentTable.='<input type="button" '.
1.589     bisitz   4740:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4741: 
1.324     albertel 4742:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4743:     $request->print($studentTable);
                   4744: 
                   4745:     return '';
                   4746: }
                   4747: 
                   4748: sub getSymbMap {
1.582     raeburn  4749:     my ($map_error) = @_;
1.132     bowersj2 4750:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4751:     unless (ref($navmap)) {
                   4752:         if (ref($map_error)) {
                   4753:             $$map_error = 'navmap';
                   4754:         }
                   4755:         return;
                   4756:     }
1.68      ng       4757:     my %symbx = ();
                   4758:     my @titles = ();
1.117     bowersj2 4759:     my $minder = 0;
                   4760: 
                   4761:     # Gather every sequence that has problems.
1.240     albertel 4762:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4763: 					       1,0,1);
1.117     bowersj2 4764:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4765: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4766: 	    my $title = $minder.'.'.
                   4767: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4768: 	    push(@titles, $title); # minder in case two titles are identical
                   4769: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4770: 	    $minder++;
1.241     albertel 4771: 	}
1.68      ng       4772:     }
                   4773:     return \@titles,\%symbx;
                   4774: }
                   4775: 
1.72      ng       4776: #
                   4777: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4778: sub displayPage {
                   4779:     my ($request) = shift;
                   4780: 
1.324     albertel 4781:     my ($symb) = &get_symb($request);
1.257     albertel 4782:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4783:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4784:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4785:     my $pageTitle = $env{'form.page'};
1.103     albertel 4786:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4787:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4788:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4789: 
                   4790:     #need to make sure we have the correct data for later EXT calls, 
                   4791:     #thus invalidate the cache
                   4792:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4793:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4794:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4795:     &Apache::lonnet::clear_EXT_cache_status();
                   4796: 
1.103     albertel 4797:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 4798:4): 	$request->print('<span class="LC_warning">'.
                   4799:4):                         &mt('Unable to view requested student. ([_1])',
                   4800:4):                             $env{'form.student'}).
                   4801:4):                         '</span>');
                   4802:4):         $request->print(&show_grading_menu_form($symb));
                   4803:4):         return;
1.103     albertel 4804:     }
1.398     albertel 4805:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4806:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4807: 	'</h3>'."\n";
1.500     albertel 4808:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4809:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4810: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4811:     } else {
                   4812: 	delete($env{'form.CODE'});
                   4813:     }
1.71      ng       4814:     &sub_page_js($request);
                   4815:     $request->print($result);
                   4816: 
1.132     bowersj2 4817:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4818:     unless (ref($navmap)) {
                   4819:         $request->print(&navmap_errormsg());
                   4820:         $request->print(&show_grading_menu_form($symb));
                   4821:         return;
                   4822:     }
1.257     albertel 4823:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4824:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4825:     if (!$map) {
1.485     albertel 4826: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4827: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4828: 	return; 
                   4829:     }
1.68      ng       4830:     my $iterator = $navmap->getIterator($map->map_start(),
                   4831: 					$map->map_finish());
                   4832: 
1.71      ng       4833:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4834: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4835: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4836: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4837: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4838: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4839: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4840: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4841: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4842: 
1.382     albertel 4843:     if (defined($env{'form.CODE'})) {
                   4844: 	$studentTable.=
                   4845: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4846:     }
1.381     albertel 4847:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4848: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4849: 
1.594     bisitz   4850:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4851:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4852:         '</span>'."\n".
1.484     albertel 4853: 	&Apache::loncommon::start_data_table().
                   4854: 	&Apache::loncommon::start_data_table_header_row().
                   4855: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4856: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4857: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4858: 
1.329     albertel 4859:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4860:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4861:     $iterator->next(); # skip the first BEGIN_MAP
                   4862:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4863:     while ($depth > 0) {
1.68      ng       4864:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4865:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4866: 
1.385     albertel 4867:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4868: 	    my $parts = $curRes->parts();
1.68      ng       4869:             my $title = $curRes->compTitle();
1.71      ng       4870: 	    my $symbx = $curRes->symb();
1.484     albertel 4871: 	    $studentTable.=
                   4872: 		&Apache::loncommon::start_data_table_row().
                   4873: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4874: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 4875:2): 		                        : '<br />('.&mt('[_1]parts',
                   4876:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4877: 		 ).
                   4878: 		 '</td>';
1.71      ng       4879: 	    $studentTable.='<td valign="top">';
1.382     albertel 4880: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4881: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4882: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4883: 					     undef,'both',\%form);
1.71      ng       4884: 	    } else {
1.382     albertel 4885: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4886: 		$companswer =~ s|<form(.*?)>||g;
                   4887: 		$companswer =~ s|</form>||g;
1.71      ng       4888: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4889: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4890: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4891: #		}
1.116     ng       4892: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4893: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4894: 	    }
                   4895: 
1.257     albertel 4896: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4897: 
1.257     albertel 4898: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4899: 		if ($record{'version'} eq '') {
1.485     albertel 4900: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4901: 		} else {
1.116     ng       4902: 		    my %responseType = ();
                   4903: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4904: 			my @responseIds =$curRes->responseIds($partid);
                   4905: 			my @responseType =$curRes->responseType($partid);
                   4906: 			my %responseIds;
                   4907: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4908: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4909: 			}
                   4910: 			$responseType{$partid} = \%responseIds;
1.116     ng       4911: 		    }
1.148     albertel 4912: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4913: 
1.71      ng       4914: 		}
1.257     albertel 4915: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4916: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4917: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4918: 									$env{'request.course.id'},
1.71      ng       4919: 									'','.submission');
                   4920:  
                   4921: 	    }
1.103     albertel 4922: 	    if (&canmodify($usec)) {
1.585     bisitz   4923:             $studentTable.=&gradeBox_start();
1.103     albertel 4924: 		foreach my $partid (@{$parts}) {
                   4925: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4926: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4927: 		    $question++;
                   4928: 		}
1.585     bisitz   4929:             $studentTable.=&gradeBox_end();
1.196     albertel 4930: 		$prob++;
1.71      ng       4931: 	    }
                   4932: 	    $studentTable.='</td></tr>';
1.68      ng       4933: 
1.103     albertel 4934: 	}
1.68      ng       4935:         $curRes = $iterator->next();
                   4936:     }
                   4937: 
1.589     bisitz   4938:     $studentTable.=
                   4939:         '</table>'."\n".
                   4940:         '<input type="button" value="'.&mt('Save').'" '.
                   4941:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4942:         '</form>'."\n";
1.324     albertel 4943:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4944:     $request->print($studentTable);
                   4945: 
                   4946:     return '';
1.119     ng       4947: }
                   4948: 
                   4949: sub displaySubByDates {
1.148     albertel 4950:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4951:     my $isCODE=0;
1.335     albertel 4952:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4953:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4954:     my $studentTable=&Apache::loncommon::start_data_table().
                   4955: 	&Apache::loncommon::start_data_table_header_row().
                   4956: 	'<th>'.&mt('Date/Time').'</th>'.
                   4957: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 4958:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4959: 	'<th>'.&mt('Submission').'</th>'.
                   4960: 	'<th>'.&mt('Status').'</th>'.
                   4961: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4962:     my ($version);
                   4963:     my %mark;
1.148     albertel 4964:     my %orders;
1.119     ng       4965:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4966:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4967: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4968:     }
1.335     albertel 4969: 
                   4970:     my $interaction;
1.525     raeburn  4971:     my $no_increment = 1;
1.596.2.2  raeburn  4972:     my %lastrndseed;
1.119     ng       4973:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4974: 	my $timestamp = 
                   4975: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4976: 	if (exists($$record{$version.':resource.0.version'})) {
                   4977: 	    $interaction = $$record{$version.':resource.0.version'};
                   4978: 	}
1.596.2.12.2.  (raeburn 4979:):         if ($isTask && $env{'form.previousversion'}) {
                   4980:):             next unless ($interaction == $env{'form.previousversion'});
                   4981:):         }
1.335     albertel 4982: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4983: 		             : "$version:resource");
1.467     albertel 4984: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4985: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4986: 	if ($isCODE) {
                   4987: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4988: 	}
1.596.2.12.2.  (raeburn 4989:):         if ($isTask) {
                   4990:):             $studentTable.='<td>'.$interaction.'</td>';
                   4991:):         }
1.119     ng       4992: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4993: 	my @displaySub = ();
                   4994: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  4995:             my ($hidden,$type);
                   4996:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4997:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4998:                 $hidden = 1;
                   4999:             }
1.335     albertel 5000: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   5001: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5002: 	    
1.122     ng       5003: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5004: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5005: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5006: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5007: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5008:                     
1.335     albertel 5009: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5010: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5011:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5012:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5013:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5014:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5015:                                    .'</span>'
                   5016:                                    .' <b>';
1.596     raeburn  5017:                     if ($hidden) {
                   5018:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5019:                     } else {
1.596.2.2  raeburn  5020:                         my ($trial,$rndseed,$newvariation);
                   5021:                         if ($type eq 'randomizetry') {
                   5022:                             $trial = $$record{"$where.$partid.tries"};
                   5023:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5024:                         }
1.596     raeburn  5025: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5026: 			    $displaySub[0].=&mt('Trial not counted');
                   5027: 		        } else {
                   5028: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5029: 					    $$record{"$where.$partid.tries"});
1.596.2.2  raeburn  5030:                             if ($rndseed || $lastrndseed{$partid}) {
                   5031:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   5032:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5033:                                 }
                   5034:                             }
1.596     raeburn  5035: 		        }
                   5036: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5037:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5038: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5039: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5040: 			    $orders{$partid}->{$responseId}=
                   5041: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5042:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5043: 		        }
1.596.2.2  raeburn  5044: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5045: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5046: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5047:                     }
1.147     albertel 5048: 		}
                   5049: 	    }
1.335     albertel 5050: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5051: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5052: 				    $$record{"$where.$partid.checkedin"},
                   5053: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5054: 					'<br />';
1.335     albertel 5055: 	    }
                   5056: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5057: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5058: 		    lc($$record{"$where.$partid.award"}).' '.
                   5059: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5060: 		    '<br />';
                   5061: 	    }
1.335     albertel 5062: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5063: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5064: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5065: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5066: 		$displaySub[2].=
                   5067: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5068: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5069: 	    }
                   5070: 	}
                   5071: 	# needed because old essay regrader has not parts info
                   5072: 	if (exists $$record{"$version:resource.regrader"}) {
                   5073: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5074: 	}
                   5075: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5076: 	if ($displaySub[2]) {
1.467     albertel 5077: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5078: 	}
1.467     albertel 5079: 	$studentTable.='&nbsp;</td>'.
                   5080: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5081:     }
1.467     albertel 5082:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5083:     return $studentTable;
1.71      ng       5084: }
                   5085: 
                   5086: sub updateGradeByPage {
                   5087:     my ($request) = shift;
                   5088: 
1.257     albertel 5089:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5090:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5091:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5092:     my $pageTitle = $env{'form.page'};
1.103     albertel 5093:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5094:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5095:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5096:     if (!&canmodify($usec)) {
1.526     raeburn  5097: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 5098: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 5099: 	return;
                   5100:     }
1.398     albertel 5101:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5102:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5103: 	'</h3>'."\n";
1.70      ng       5104: 
1.68      ng       5105:     $request->print($result);
                   5106: 
1.582     raeburn  5107: 
1.132     bowersj2 5108:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5109:     unless (ref($navmap)) {
                   5110:         $request->print(&navmap_errormsg());
                   5111:         return;
                   5112:     }
1.257     albertel 5113:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5114:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5115:     if (!$map) {
1.527     raeburn  5116: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 5117: 	my ($symb)=&get_symb($request);
                   5118: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5119: 	return; 
                   5120:     }
1.71      ng       5121:     my $iterator = $navmap->getIterator($map->map_start(),
                   5122: 					$map->map_finish());
1.70      ng       5123: 
1.484     albertel 5124:     my $studentTable=
                   5125: 	&Apache::loncommon::start_data_table().
                   5126: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5127: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5128: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5129: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5130: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5131: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5132: 
                   5133:     $iterator->next(); # skip the first BEGIN_MAP
                   5134:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 5135:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 5136:     while ($depth > 0) {
1.71      ng       5137:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5138:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5139: 
1.385     albertel 5140:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5141: 	    my $parts = $curRes->parts();
1.71      ng       5142:             my $title = $curRes->compTitle();
                   5143: 	    my $symbx = $curRes->symb();
1.484     albertel 5144: 	    $studentTable.=
                   5145: 		&Apache::loncommon::start_data_table_row().
                   5146: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5147: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5148:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5149: 		.')').'</td>';
1.71      ng       5150: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5151: 
                   5152: 	    my %newrecord=();
                   5153: 	    my @displayPts=();
1.269     raeburn  5154:             my %aggregate = ();
                   5155:             my $aggregateflag = 0;
1.71      ng       5156: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5157: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5158: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5159: 
1.257     albertel 5160: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5161: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5162: 		my $partial = $newpts/$wgt;
                   5163: 		my $score;
                   5164: 		if ($partial > 0) {
                   5165: 		    $score = 'correct_by_override';
1.125     ng       5166: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5167: 		    $score = 'incorrect_by_override';
                   5168: 		}
1.257     albertel 5169: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5170: 		if ($dropMenu eq 'excused') {
1.71      ng       5171: 		    $partial = '';
                   5172: 		    $score = 'excused';
1.125     ng       5173: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5174: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5175: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5176: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5177: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5178: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5179: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5180: 		    $changeflag++;
                   5181: 		    $newpts = '';
1.269     raeburn  5182:                     
                   5183:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5184:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5185:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5186:                     if ($aggtries > 0) {
                   5187:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5188:                         $aggregateflag = 1;
                   5189:                     }
1.71      ng       5190: 		}
1.324     albertel 5191: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5192: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5193: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5194: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5195: 		    '&nbsp;<br />';
1.526     raeburn  5196: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5197: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5198: 		    '&nbsp;<br />';
1.71      ng       5199: 		$question++;
1.380     albertel 5200: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5201: 
1.71      ng       5202: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5203: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5204: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5205: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5206: 
                   5207: 		$changeflag++;
                   5208: 	    }
                   5209: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5210: 		my %record = 
                   5211: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5212: 					     $udom,$uname);
                   5213: 
                   5214: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5215: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5216: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5217: 		    $newrecord{'resource.CODE'} = '';
                   5218: 		}
1.257     albertel 5219: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5220: 					$udom,$uname);
1.382     albertel 5221: 		%record = &Apache::lonnet::restore($symbx,
                   5222: 						   $env{'request.course.id'},
                   5223: 						   $udom,$uname);
1.380     albertel 5224: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5225: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5226: 	    }
1.380     albertel 5227: 	    
1.269     raeburn  5228:             if ($aggregateflag) {
                   5229:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5230:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5231:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5232:             }
1.125     ng       5233: 
1.71      ng       5234: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5235: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5236: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5237: 
1.196     albertel 5238: 	    $prob++;
1.68      ng       5239: 	}
1.71      ng       5240:         $curRes = $iterator->next();
1.68      ng       5241:     }
1.98      albertel 5242: 
1.484     albertel 5243:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 5244:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  5245:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5246: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5247: 		  $changeflag));
1.76      ng       5248:     $request->print($grademsg.$studentTable);
1.68      ng       5249: 
1.70      ng       5250:     return '';
                   5251: }
                   5252: 
1.72      ng       5253: #-------- end of section for handling grading by page/sequence ---------
                   5254: #
                   5255: #-------------------------------------------------------------------
                   5256: 
1.581     www      5257: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5258: #
                   5259: #------ start of section for handling grading by page/sequence ---------
                   5260: 
1.423     albertel 5261: =pod
                   5262: 
                   5263: =head1 Bubble sheet grading routines
                   5264: 
1.424     albertel 5265:   For this documentation:
                   5266: 
                   5267:    'scanline' refers to the full line of characters
                   5268:    from the file that we are parsing that represents one entire sheet
                   5269: 
                   5270:    'bubble line' refers to the data
1.596.2.6  raeburn  5271:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5272: 
                   5273: 
1.596.2.6  raeburn  5274: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5275: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5276: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5277: one of the predefined configurations for what each scanline looks
                   5278: like.
                   5279: 
                   5280: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5281: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5282: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5283:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5284: invalid student/employee ID
1.424     albertel 5285: 
                   5286: If the CODE option is used that determines the randomization of the
1.556     weissno  5287: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5288: username:domain.
                   5289: 
                   5290: During the validation phase the instructor can choose to skip scanlines. 
                   5291: 
1.596.2.6  raeburn  5292: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5293: 
                   5294:   scantron_original_filename (unmodified original file)
                   5295:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5296:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5297: 
                   5298: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5299: correction information that isn't representable in the bubblesheet
1.424     albertel 5300: file (see &scantron_getfile() for more information)
                   5301: 
                   5302: After all scanlines are either valid, marked as valid or skipped, then
                   5303: foreach line foreach problem in the picked sequence, an ssi request is
                   5304: made that simulates a user submitting their selected letter(s) against
                   5305: the homework problem.
1.423     albertel 5306: 
                   5307: =over 4
                   5308: 
                   5309: 
                   5310: 
                   5311: =item defaultFormData
                   5312: 
                   5313:   Returns html hidden inputs used to hold context/default values.
                   5314: 
                   5315:  Arguments:
                   5316:   $symb - $symb of the current resource 
                   5317: 
                   5318: =cut
1.422     foxr     5319: 
1.81      albertel 5320: sub defaultFormData {
1.324     albertel 5321:     my ($symb)=@_;
1.447     foxr     5322:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5323:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5324:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5325: }
                   5326: 
1.447     foxr     5327: 
1.423     albertel 5328: =pod 
                   5329: 
                   5330: =item getSequenceDropDown
                   5331: 
                   5332:    Return html dropdown of possible sequences to grade
                   5333:  
                   5334:  Arguments:
1.582     raeburn  5335:    $symb - $symb of the current resource
                   5336:    $map_error - ref to scalar which will container error if
                   5337:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5338: 
                   5339: =cut
1.422     foxr     5340: 
1.75      albertel 5341: sub getSequenceDropDown {
1.582     raeburn  5342:     my ($symb,$map_error)=@_;
1.75      albertel 5343:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5344:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5345:     if (ref($map_error)) {
                   5346:         return if ($$map_error);
                   5347:     }
1.137     albertel 5348:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5349:     my $ctr=0;
                   5350:     foreach (@$titles) {
                   5351: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5352: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5353: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5354: 	    '>'.$showtitle.'</option>'."\n";
                   5355: 	$ctr++;
                   5356:     }
                   5357:     $result.= '</select>';
                   5358:     return $result;
                   5359: }
                   5360: 
1.495     albertel 5361: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5362:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5363: 
                   5364: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5365: 
1.509     raeburn  5366: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5367:                                    # matchresponse or rankresponse, where 
                   5368:                                    # an individual response can have multiple 
                   5369:                                    # lines
1.503     raeburn  5370: 
                   5371: my %responsetype_per_response;     # responsetype for each response
                   5372: 
1.596.2.12.2.  6(raebur 5373:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5374:3):                                    # numbered response. Needed when randomorder
                   5375:3):                                    # or randompick are in use. Key is ID, value 
                   5376:3):                                    # is response number.
                   5377:3): 
1.495     albertel 5378: # Save and restore the bubble lines array to the form env.
                   5379: 
                   5380: 
                   5381: sub save_bubble_lines {
                   5382:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5383: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5384: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5385: 	    $first_bubble_line{$line};
1.503     raeburn  5386:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5387:             $subdivided_bubble_lines{$line};
                   5388:         $env{"form.scantron.responsetype.$line"} =
                   5389:             $responsetype_per_response{$line};
1.495     albertel 5390:     }
1.596.2.12.2.  6(raebur 5391:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5392:3):         my $line = $masterseq_id_responsenum{$resid};
                   5393:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5394:3):     }
1.495     albertel 5395: }
                   5396: 
                   5397: 
                   5398: sub restore_bubble_lines {
                   5399:     my $line = 0;
                   5400:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5401:3):     %masterseq_id_responsenum = ();
1.495     albertel 5402:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5403: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5404: 	$bubble_lines_per_response{$line} = $value;
                   5405: 	$first_bubble_line{$line}  =
                   5406: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5407:         $subdivided_bubble_lines{$line} =
                   5408:             $env{"form.scantron.sub_bubblelines.$line"};
                   5409:         $responsetype_per_response{$line} =
                   5410:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5411:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5412:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5413: 	$line++;
                   5414:     }
                   5415: }
                   5416: 
1.423     albertel 5417: =pod 
                   5418: 
                   5419: =item scantron_filenames
                   5420: 
                   5421:    Returns a list of the scantron files in the current course 
                   5422: 
                   5423: =cut
1.422     foxr     5424: 
1.202     albertel 5425: sub scantron_filenames {
1.257     albertel 5426:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5427:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5428:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5429:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5430:):                                                         $cname,$getpropath);
1.202     albertel 5431:     my @possiblenames;
1.596.2.12.2.  (raeburn 5432:):     if (ref($dirlist) eq 'ARRAY') {
                   5433:):         foreach my $filename (sort(@{$dirlist})) {
                   5434:): 	    ($filename)=split(/&/,$filename);
                   5435:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5436:): 	    $filename=~s/^scantron_orig_//;
                   5437:): 	    push(@possiblenames,$filename);
                   5438:):         }
1.202     albertel 5439:     }
                   5440:     return @possiblenames;
                   5441: }
                   5442: 
1.423     albertel 5443: =pod 
                   5444: 
                   5445: =item scantron_uploads
                   5446: 
                   5447:    Returns  html drop-down list of scantron files in current course.
                   5448: 
                   5449:  Arguments:
                   5450:    $file2grade - filename to set as selected in the dropdown
                   5451: 
                   5452: =cut
1.422     foxr     5453: 
1.202     albertel 5454: sub scantron_uploads {
1.209     ng       5455:     my ($file2grade) = @_;
1.202     albertel 5456:     my $result=	'<select name="scantron_selectfile">';
                   5457:     $result.="<option></option>";
                   5458:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5459: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5460:     }
                   5461:     $result.="</select>";
                   5462:     return $result;
                   5463: }
                   5464: 
1.423     albertel 5465: =pod 
                   5466: 
                   5467: =item scantron_scantab
                   5468: 
                   5469:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5470:   file.
                   5471: 
                   5472: =cut
1.422     foxr     5473: 
1.82      albertel 5474: sub scantron_scantab {
                   5475:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5476:     $result.='<option></option>'."\n";
1.518     raeburn  5477:     my @lines = &get_scantronformat_file();
                   5478:     if (@lines > 0) {
                   5479:         foreach my $line (@lines) {
                   5480:             next if (($line =~ /^\#/) || ($line eq ''));
                   5481: 	    my ($name,$descrip)=split(/:/,$line);
                   5482: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5483:         }
1.82      albertel 5484:     }
                   5485:     $result.='</select>'."\n";
1.518     raeburn  5486:     return $result;
                   5487: }
                   5488: 
                   5489: =pod
                   5490: 
                   5491: =item get_scantronformat_file
                   5492: 
                   5493:   Returns an array containing lines from the scantron format file for
                   5494:   the domain of the course.
                   5495: 
                   5496:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5497:   lines are from this file.
                   5498: 
                   5499:   Otherwise, if a default.tab has been published in RES space by the 
                   5500:   domainconfig user, lines are from this file.
                   5501: 
                   5502:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5503:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5504: 
1.518     raeburn  5505: =cut
                   5506: 
                   5507: sub get_scantronformat_file {
                   5508:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5509:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5510:     my $gottab = 0;
                   5511:     my @lines;
                   5512:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5513:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5514:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5515:             if ($formatfile ne '-1') {
                   5516:                 @lines = split("\n",$formatfile,-1);
                   5517:                 $gottab = 1;
                   5518:             }
                   5519:         }
                   5520:     }
                   5521:     if (!$gottab) {
                   5522:         my $confname = $cdom.'-domainconfig';
                   5523:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5524:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5525:         if ($formatfile ne '-1') {
                   5526:             @lines = split("\n",$formatfile,-1);
                   5527:             $gottab = 1;
                   5528:         }
                   5529:     }
                   5530:     if (!$gottab) {
1.519     raeburn  5531:         my @domains = &Apache::lonnet::current_machine_domains();
                   5532:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5533:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5534:             @lines = <$fh>;
                   5535:             close($fh);
                   5536:         } else {
                   5537:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5538:             @lines = <$fh>;
                   5539:             close($fh);
                   5540:         }
1.518     raeburn  5541:     }
                   5542:     return @lines;
1.82      albertel 5543: }
                   5544: 
1.423     albertel 5545: =pod 
                   5546: 
                   5547: =item scantron_CODElist
                   5548: 
                   5549:   Returns html drop down of the saved CODE lists from current course,
                   5550:   generated from earlier printings.
                   5551: 
                   5552: =cut
1.422     foxr     5553: 
1.186     albertel 5554: sub scantron_CODElist {
1.257     albertel 5555:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5556:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5557:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5558:     my $namechoice='<option></option>';
1.225     albertel 5559:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5560: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5561: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5562: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5563:     }
                   5564:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5565:     return $namechoice;
                   5566: }
                   5567: 
1.423     albertel 5568: =pod 
                   5569: 
                   5570: =item scantron_CODEunique
                   5571: 
                   5572:   Returns the html for "Each CODE to be used once" radio.
                   5573: 
                   5574: =cut
1.422     foxr     5575: 
1.186     albertel 5576: sub scantron_CODEunique {
1.532     bisitz   5577:     my $result='<span class="LC_nobreak">
1.272     albertel 5578:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5579:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5580:                 </span>
1.532     bisitz   5581:                 <span class="LC_nobreak">
1.272     albertel 5582:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5583:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5584:                 </span>';
1.186     albertel 5585:     return $result;
                   5586: }
1.423     albertel 5587: 
                   5588: =pod 
                   5589: 
                   5590: =item scantron_selectphase
                   5591: 
1.596.2.6  raeburn  5592:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5593:   Allows for - starting a grading run.
1.424     albertel 5594:              - downloading existing scan data (original, corrected
1.423     albertel 5595:                                                 or skipped info)
                   5596: 
                   5597:              - uploading new scan data
                   5598: 
                   5599:  Arguments:
                   5600:   $r          - The Apache request object
                   5601:   $file2grade - name of the file that contain the scanned data to score
                   5602: 
                   5603: =cut
1.186     albertel 5604: 
1.75      albertel 5605: sub scantron_selectphase {
1.209     ng       5606:     my ($r,$file2grade) = @_;
1.324     albertel 5607:     my ($symb)=&get_symb($r);
1.75      albertel 5608:     if (!$symb) {return '';}
1.582     raeburn  5609:     my $map_error;
                   5610:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5611:     if ($map_error) {
                   5612:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5613:         return;
                   5614:     }
1.324     albertel 5615:     my $default_form_data=&defaultFormData($symb);
                   5616:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5617:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5618:     my $format_selector=&scantron_scantab();
1.186     albertel 5619:     my $CODE_selector=&scantron_CODElist();
                   5620:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5621:     my $result;
1.422     foxr     5622: 
1.513     foxr     5623:     $ssi_error = 0;
                   5624: 
1.596.2.4  raeburn  5625:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5626:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5627: 
                   5628:         # Chunk of form to prompt for a scantron file upload.
                   5629: 
                   5630:         $r->print('
                   5631:     <br />
                   5632:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5633:        '.&Apache::loncommon::start_data_table_header_row().'
                   5634:             <th>
                   5635:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5636:             </th>
                   5637:        '.&Apache::loncommon::end_data_table_header_row().'
                   5638:        '.&Apache::loncommon::start_data_table_row().'
                   5639:             <td>
                   5640: ');
                   5641:     my $default_form_data=&defaultFormData(&get_symb($r,1));
                   5642:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5643:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5644:     $r->print('
                   5645:               <script type="text/javascript" language="javascript">
                   5646:     function checkUpload(formname) {
                   5647:         if (formname.upfile.value == "") {
                   5648:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5649:             return false;
                   5650:         }
                   5651:         formname.submit();
                   5652:     }
                   5653:               </script>
                   5654: 
                   5655:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5656:                 '.$default_form_data.'
                   5657:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5658:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5659:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5660:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5661:                 <br />
                   5662:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5663:               </form>
                   5664: ');
                   5665: 
                   5666:         $r->print('
                   5667:             </td>
                   5668:        '.&Apache::loncommon::end_data_table_row().'
                   5669:        '.&Apache::loncommon::end_data_table().'
                   5670: ');
                   5671:     }
                   5672: 
1.422     foxr     5673:     # Chunk of form to prompt for a file to grade and how:
                   5674: 
1.489     albertel 5675:     $result.= '
                   5676:     <br />
                   5677:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5678:     <input type="hidden" name="command" value="scantron_warning" />
                   5679:     '.$default_form_data.'
                   5680:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5681:        '.&Apache::loncommon::start_data_table_header_row().'
                   5682:             <th colspan="2">
1.492     albertel 5683:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5684:             </th>
                   5685:        '.&Apache::loncommon::end_data_table_header_row().'
                   5686:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5687:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5688:        '.&Apache::loncommon::end_data_table_row().'
                   5689:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5690:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5691:        '.&Apache::loncommon::end_data_table_row().'
                   5692:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5693:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5694:        '.&Apache::loncommon::end_data_table_row().'
                   5695:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5696:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5697:        '.&Apache::loncommon::end_data_table_row().'
                   5698:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5699:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5700:        '.&Apache::loncommon::end_data_table_row().'
                   5701:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5702: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5703:             <td>
1.492     albertel 5704: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5705:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5706:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5707: 	    </td>
1.489     albertel 5708:        '.&Apache::loncommon::end_data_table_row().'
                   5709:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5710:             <td colspan="2">
1.572     www      5711:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5712:             </td>
1.489     albertel 5713:        '.&Apache::loncommon::end_data_table_row().'
                   5714:     '.&Apache::loncommon::end_data_table().'
                   5715:     </form>
                   5716: ';
1.162     albertel 5717:    
                   5718:     $r->print($result);
                   5719: 
1.422     foxr     5720:     # Chunk of the form that prompts to view a scoring office file,
                   5721:     # corrected file, skipped records in a file.
                   5722: 
1.489     albertel 5723:     $r->print('
                   5724:    <br />
                   5725:    <form action="/adm/grades" name="scantron_download">
                   5726:      '.$default_form_data.'
                   5727:      <input type="hidden" name="command" value="scantron_download" />
                   5728:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5729:        '.&Apache::loncommon::start_data_table_header_row().'
                   5730:               <th>
1.492     albertel 5731:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5732:               </th>
                   5733:        '.&Apache::loncommon::end_data_table_header_row().'
                   5734:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5735:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5736:                 <br />
1.492     albertel 5737:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5738:        '.&Apache::loncommon::end_data_table_row().'
                   5739:      '.&Apache::loncommon::end_data_table().'
                   5740:    </form>
                   5741:    <br />
                   5742: ');
1.162     albertel 5743: 
1.457     banghart 5744:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5745: 
1.596.2.12.2.  8(raebur 5746:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5747:              $default_form_data."\n".
                   5748:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5749:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5750:              '<th colspan="2">
1.572     www      5751:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5752:              '</th>'."\n".
                   5753:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5754:               &Apache::loncommon::start_data_table_row()."\n".
                   5755:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5756:               '<td> '.$sequence_selector.' </td>'.
                   5757:               &Apache::loncommon::end_data_table_row()."\n".
                   5758:               &Apache::loncommon::start_data_table_row()."\n".
                   5759:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5760:               '<td> '.$file_selector.' </td>'."\n".
                   5761:               &Apache::loncommon::end_data_table_row()."\n".
                   5762:               &Apache::loncommon::start_data_table_row()."\n".
                   5763:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5764:               '<td> '.$format_selector.' </td>'."\n".
                   5765:               &Apache::loncommon::end_data_table_row()."\n".
                   5766:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5767:               '<td> '.&mt('Options').' </td>'."\n".
                   5768:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5769:               &Apache::loncommon::end_data_table_row()."\n".
                   5770:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5771:               '<td colspan="2">'."\n".
                   5772:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5773:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5774:               '</td>'."\n".
                   5775:               &Apache::loncommon::end_data_table_row()."\n".
                   5776:               &Apache::loncommon::end_data_table()."\n".
                   5777:               '</form><br />');
1.457     banghart 5778:     $r->print($grading_menu_button);
1.523     raeburn  5779:     return;
1.75      albertel 5780: }
                   5781: 
1.423     albertel 5782: =pod
                   5783: 
                   5784: =item get_scantron_config
                   5785: 
                   5786:    Parse and return the scantron configuration line selected as a
                   5787:    hash of configuration file fields.
                   5788: 
                   5789:  Arguments:
                   5790:     which - the name of the configuration to parse from the file.
                   5791: 
                   5792: 
                   5793:  Returns:
                   5794:             If the named configuration is not in the file, an empty
                   5795:             hash is returned.
                   5796:     a hash with the fields
                   5797:       name         - internal name for the this configuration setup
                   5798:       description  - text to display to operator that describes this config
                   5799:       CODElocation - if 0 or the string 'none'
                   5800:                           - no CODE exists for this config
                   5801:                      if -1 || the string 'letter'
                   5802:                           - a CODE exists for this config and is
                   5803:                             a string of letters
                   5804:                      Unsupported value (but planned for future support)
                   5805:                           if a positive integer
                   5806:                                - The CODE exists as the first n items from
                   5807:                                  the question section of the form
                   5808:                           if the string 'number'
                   5809:                                - The CODE exists for this config and is
                   5810:                                  a string of numbers
                   5811:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5812:                      the CODE starts
                   5813:       CODElength  - length of the CODE
1.573     bisitz   5814:       IDstart     - column where the student/employee ID starts
1.556     weissno  5815:       IDlength    - length of the student/employee ID info
1.423     albertel 5816:       Qstart      - column where the information from the bubbled
                   5817:                     'questions' start
                   5818:       Qlength     - number of columns comprising a single bubble line from
                   5819:                     the sheet. (usually either 1 or 10)
1.424     albertel 5820:       Qon         - either a single character representing the character used
1.423     albertel 5821:                     to signal a bubble was chosen in the positional setup, or
                   5822:                     the string 'letter' if the letter of the chosen bubble is
                   5823:                     in the final, or 'number' if a number representing the
                   5824:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5825:       Qoff        - the character used to represent that a bubble was
                   5826:                     left blank
1.423     albertel 5827:       PaperID     - if the scanning process generates a unique number for each
                   5828:                     sheet scanned the column that this ID number starts in
                   5829:       PaperIDlength - number of columns that comprise the unique ID number
                   5830:                       for the sheet of paper
1.424     albertel 5831:       FirstName   - column that the first name starts in
1.423     albertel 5832:       FirstNameLength - number of columns that the first name spans
                   5833:  
                   5834:       LastName    - column that the last name starts in
                   5835:       LastNameLength - number of columns that the last name spans
1.596.2.12.2.  (raeburn 5836:):       BubblesPerRow - number of bubbles available in each row used to
                   5837:):                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5838: 
                   5839: =cut
1.422     foxr     5840: 
1.82      albertel 5841: sub get_scantron_config {
                   5842:     my ($which) = @_;
1.518     raeburn  5843:     my @lines = &get_scantronformat_file();
1.82      albertel 5844:     my %config;
1.157     albertel 5845:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5846:     foreach my $line (@lines) {
1.82      albertel 5847: 	my ($name,$descrip)=split(/:/,$line);
                   5848: 	if ($name ne $which ) { next; }
                   5849: 	chomp($line);
                   5850: 	my @config=split(/:/,$line);
                   5851: 	$config{'name'}=$config[0];
                   5852: 	$config{'description'}=$config[1];
                   5853: 	$config{'CODElocation'}=$config[2];
                   5854: 	$config{'CODEstart'}=$config[3];
                   5855: 	$config{'CODElength'}=$config[4];
                   5856: 	$config{'IDstart'}=$config[5];
                   5857: 	$config{'IDlength'}=$config[6];
                   5858: 	$config{'Qstart'}=$config[7];
1.497     foxr     5859:  	$config{'Qlength'}=$config[8];
1.82      albertel 5860: 	$config{'Qoff'}=$config[9];
                   5861: 	$config{'Qon'}=$config[10];
1.157     albertel 5862: 	$config{'PaperID'}=$config[11];
                   5863: 	$config{'PaperIDlength'}=$config[12];
                   5864: 	$config{'FirstName'}=$config[13];
                   5865: 	$config{'FirstNamelength'}=$config[14];
                   5866: 	$config{'LastName'}=$config[15];
                   5867: 	$config{'LastNamelength'}=$config[16];
1.596.2.12.2.  (raeburn 5868:):         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5869: 	last;
                   5870:     }
                   5871:     return %config;
                   5872: }
                   5873: 
1.423     albertel 5874: =pod 
                   5875: 
                   5876: =item username_to_idmap
                   5877: 
1.556     weissno  5878:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5879:     student username:domain.
                   5880: 
                   5881:   Arguments:
                   5882: 
                   5883:     $classlist - reference to the class list hash. This is a hash
                   5884:                  keyed by student name:domain  whose elements are references
1.424     albertel 5885:                  to arrays containing various chunks of information
1.423     albertel 5886:                  about the student. (See loncoursedata for more info).
                   5887: 
                   5888:   Returns
                   5889:     %idmap - the constructed hash
                   5890: 
                   5891: =cut
                   5892: 
1.82      albertel 5893: sub username_to_idmap {
                   5894:     my ($classlist)= @_;
                   5895:     my %idmap;
                   5896:     foreach my $student (keys(%$classlist)) {
                   5897: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5898: 	    $student;
                   5899:     }
                   5900:     return %idmap;
                   5901: }
1.423     albertel 5902: 
                   5903: =pod
                   5904: 
1.424     albertel 5905: =item scantron_fixup_scanline
1.423     albertel 5906: 
                   5907:    Process a requested correction to a scanline.
                   5908: 
                   5909:   Arguments:
                   5910:     $scantron_config   - hash from &get_scantron_config()
                   5911:     $scan_data         - hash of correction information 
                   5912:                           (see &scantron_getfile())
                   5913:     $line              - existing scanline
                   5914:     $whichline         - line number of the passed in scanline
                   5915:     $field             - type of change to process 
                   5916:                          (either 
1.573     bisitz   5917:                           'ID'     -> correct the student/employee ID
1.423     albertel 5918:                           'CODE'   -> correct the CODE
                   5919:                           'answer' -> fixup the submitted answers)
                   5920:     
                   5921:    $args               - hash of additional info,
                   5922:                           - 'ID' 
                   5923:                                'newid' -> studentID to use in replacement
1.424     albertel 5924:                                           of existing one
1.423     albertel 5925:                           - 'CODE' 
                   5926:                                'CODE_ignore_dup' - set to true if duplicates
                   5927:                                                    should be ignored.
                   5928: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5929:                                         if the existing unfound code should
1.423     albertel 5930:                                         be used as is
                   5931:                           - 'answer'
                   5932:                                'response' - new answer or 'none' if blank
                   5933:                                'question' - the bubble line to change
1.503     raeburn  5934:                                'questionnum' - the question identifier,
                   5935:                                                may include subquestion. 
1.423     albertel 5936: 
                   5937:   Returns:
                   5938:     $line - the modified scanline
                   5939: 
                   5940:   Side effects: 
                   5941:     $scan_data - may be updated
                   5942: 
                   5943: =cut
                   5944: 
1.82      albertel 5945: 
1.157     albertel 5946: sub scantron_fixup_scanline {
                   5947:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5948:     if ($field eq 'ID') {
                   5949: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5950: 	    return ($line,1,'New value too large');
1.157     albertel 5951: 	}
                   5952: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5953: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5954: 				     $args->{'newid'});
                   5955: 	}
                   5956: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5957: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5958: 	if ($args->{'newid'}=~/^\s*$/) {
                   5959: 	    &scan_data($scan_data,"$whichline.user",
                   5960: 		       $args->{'username'}.':'.$args->{'domain'});
                   5961: 	}
1.186     albertel 5962:     } elsif ($field eq 'CODE') {
1.192     albertel 5963: 	if ($args->{'CODE_ignore_dup'}) {
                   5964: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5965: 	}
                   5966: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5967: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5968: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5969: 		return ($line,1,'New CODE value too large');
                   5970: 	    }
                   5971: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5972: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5973: 	    }
                   5974: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5975: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5976: 	}
1.157     albertel 5977:     } elsif ($field eq 'answer') {
1.497     foxr     5978: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5979: 	my $off=$scantron_config->{'Qoff'};
                   5980: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5981: 	my $answer=${off}x$length;
                   5982: 	if ($args->{'response'} eq 'none') {
                   5983: 	    &scan_data($scan_data,
1.503     raeburn  5984: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5985: 	} else {
                   5986: 	    if ($on eq 'letter') {
                   5987: 		my @alphabet=('A'..'Z');
                   5988: 		$answer=$alphabet[$args->{'response'}];
                   5989: 	    } elsif ($on eq 'number') {
                   5990: 		$answer=$args->{'response'}+1;
                   5991: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5992: 	    } else {
1.497     foxr     5993: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5994: 	    }
1.497     foxr     5995: 	    &scan_data($scan_data,
1.503     raeburn  5996: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5997: 	}
1.497     foxr     5998: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5999: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6000:     }
                   6001:     return $line;
                   6002: }
1.423     albertel 6003: 
                   6004: =pod
                   6005: 
                   6006: =item scan_data
                   6007: 
                   6008:     Edit or look up  an item in the scan_data hash.
                   6009: 
                   6010:   Arguments:
                   6011:     $scan_data  - The hash (see scantron_getfile)
                   6012:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6013:                   scantronfilename_key).
1.423     albertel 6014:     $data        - New value of the hash entry.
                   6015:     $delete      - If true, the entry is removed from the hash.
                   6016: 
                   6017:   Returns:
                   6018:     The new value of the hash table field (undefined if deleted).
                   6019: 
                   6020: =cut
                   6021: 
                   6022: 
1.157     albertel 6023: sub scan_data {
                   6024:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6025:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6026:     if (defined($value)) {
                   6027: 	$scan_data->{$filename.'_'.$key} = $value;
                   6028:     }
                   6029:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6030:     return $scan_data->{$filename.'_'.$key};
                   6031: }
1.423     albertel 6032: 
1.495     albertel 6033: # ----- These first few routines are general use routines.----
                   6034: 
                   6035: # Return the number of occurences of a pattern in a string.
                   6036: 
                   6037: sub occurence_count {
                   6038:     my ($string, $pattern) = @_;
                   6039: 
                   6040:     my @matches = ($string =~ /$pattern/g);
                   6041: 
                   6042:     return scalar(@matches);
                   6043: }
                   6044: 
                   6045: 
                   6046: # Take a string known to have digits and convert all the
                   6047: # digits into letters in the range J,A..I.
                   6048: 
                   6049: sub digits_to_letters {
                   6050:     my ($input) = @_;
                   6051: 
                   6052:     my @alphabet = ('J', 'A'..'I');
                   6053: 
                   6054:     my @input    = split(//, $input);
                   6055:     my $output ='';
                   6056:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6057: 	if ($input[$i] =~ /\d/) {
                   6058: 	    $output .= $alphabet[$input[$i]];
                   6059: 	} else {
                   6060: 	    $output .= $input[$i];
                   6061: 	}
                   6062:     }
                   6063:     return $output;
                   6064: }
                   6065: 
1.423     albertel 6066: =pod 
                   6067: 
                   6068: =item scantron_parse_scanline
                   6069: 
                   6070:   Decodes a scanline from the selected scantron file
                   6071: 
                   6072:  Arguments:
                   6073:     line             - The text of the scantron file line to process
                   6074:     whichline        - Line number
                   6075:     scantron_config  - Hash describing the format of the scantron lines.
                   6076:     scan_data        - Hash of extra information about the scanline
                   6077:                        (see scantron_getfile for more information)
                   6078:     just_header      - True if should not process question answers but only
                   6079:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6080:3):     randomorder      - True if randomorder in use
                   6081:3):     randompick       - True if randompick in use
                   6082:3):     sequence         - Exam folder URL
                   6083:3):     master_seq       - Ref to array containing symbs in exam folder
                   6084:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6085:3):                        (corresponding values are resource objects)
                   6086:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6087:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6088:3):                        are refs to an array of resource objects, ordered
                   6089:3):                        according to order used for CODE, when randomorder
                   6090:3):                        and or randompick are in use.
                   6091:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6092:3):                        for current line to question number used for same question
                   6093:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6094:3):     startline        - Ref to hash where key is question number (0 is first)
                   6095:3):                        and value is number of first bubble line for current 
                   6096:3):                        student or code-based randompick and/or randomorder.
                   6097:3):     totalref         - Ref of scalar used to score total number of bubble
                   6098:3):                        lines needed for responses in a scan line (used when
                   6099:3):                        randompick in use. 
                   6100:3): 
1.423     albertel 6101:  Returns:
                   6102:    Hash containing the result of parsing the scanline
                   6103: 
                   6104:    Keys are all proceeded by the string 'scantron.'
                   6105: 
                   6106:        CODE    - the CODE in use for this scanline
                   6107:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6108:                  by the operator
                   6109:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6110:                             CODEs were selected, but the usage has been
                   6111:                             forced by the operator
1.556     weissno  6112:        ID  - student/employee ID
1.423     albertel 6113:        PaperID - if used, the ID number printed on the sheet when the 
                   6114:                  paper was scanned
                   6115:        FirstName - first name from the sheet
                   6116:        LastName  - last name from the sheet
                   6117: 
                   6118:      if just_header was not true these key may also exist
                   6119: 
1.447     foxr     6120:        missingerror - a list of bubble ranges that are considered to be answers
                   6121:                       to a single question that don't have any bubbles filled in.
                   6122:                       Of the form questionnumber:firstbubblenumber:count.
                   6123:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6124:                       to a single question that have more than one bubble filled in.
                   6125:                       Of the form questionnumber::firstbubblenumber:count
                   6126:    
                   6127:                 In the above, count is the number of bubble responses in the
                   6128:                 input line needed to represent the possible answers to the question.
                   6129:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6130:                 per line would have count = 2.
                   6131: 
1.423     albertel 6132:        maxquest     - the number of the last bubble line that was parsed
                   6133: 
                   6134:        (<number> starts at 1)
                   6135:        <number>.answer - zero or more letters representing the selected
                   6136:                          letters from the scanline for the bubble line 
                   6137:                          <number>.
                   6138:                          if blank there was either no bubble or there where
                   6139:                          multiple bubbles, (consult the keys missingerror and
                   6140:                          doubleerror if this is an error condition)
                   6141: 
                   6142: =cut
                   6143: 
1.82      albertel 6144: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6145:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6146:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6147:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6148: 
1.82      albertel 6149:     my %record;
1.596.2.12.2.  6(raebur 6150:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6151:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6152: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6153: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6154: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6155: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6156: 	    $record{'scantron.CODE'}=substr($data,
                   6157: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6158: 					    $$scantron_config{'CODElength'});
1.191     albertel 6159: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6160: 		$record{'scantron.useCODE'}=1;
                   6161: 	    }
1.192     albertel 6162: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6163: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6164: 	    }
1.82      albertel 6165: 	} else {
                   6166: 	    #FIXME interpret first N questions
                   6167: 	}
                   6168:     }
1.83      albertel 6169:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6170: 				  $$scantron_config{'IDlength'});
1.157     albertel 6171:     $record{'scantron.PaperID'}=
                   6172: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6173: 	       $$scantron_config{'PaperIDlength'});
                   6174:     $record{'scantron.FirstName'}=
                   6175: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6176: 	       $$scantron_config{'FirstNamelength'});
                   6177:     $record{'scantron.LastName'}=
                   6178: 	substr($data,$$scantron_config{'LastName'}-1,
                   6179: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6180:     if ($just_header) { return \%record; }
1.194     albertel 6181: 
1.82      albertel 6182:     my @alphabet=('A'..'Z');
                   6183:     my $questnum=0;
1.447     foxr     6184:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6185: 
1.596.2.12.2.  6(raebur 6186:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6187:3):     if ($randompick || $randomorder) {
                   6188:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6189:3):                                          $master_seq,$symb_to_resource,
                   6190:3):                                          $partids_by_symb,$orderedforcode,
                   6191:3):                                          $respnumlookup,$startline);
                   6192:3):         if ($total) {
                   6193:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6194:3):         }
                   6195:3):         if (ref($totalref)) {
                   6196:3):             $$totalref = $total;
                   6197:3):         }
                   6198:3):     }
                   6199:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6200:     chomp($questions);		# Get rid of any trailing \n.
                   6201:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6202:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6203:3):         my $answers_needed;
                   6204:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6205:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6206:3):         } else {
                   6207:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6208:3):         }
1.503     raeburn  6209:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6210:                              || 1;
                   6211:         $questnum++;
                   6212:         my $quest_id = $questnum;
                   6213:         my $currentquest = substr($questions,0,$answer_length);
                   6214:         $questions       = substr($questions,$answer_length);
                   6215:         if (length($currentquest) < $answer_length) { next; }
                   6216: 
1.596.2.12.2.  6(raebur 6217:3):         my $subdivided;
                   6218:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6219:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6220:3):         } else {
                   6221:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6222:3):         }
                   6223:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6224:             my $subquestnum = 1;
                   6225:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6226:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6227:             foreach my $subans (@subanswers_needed) {
                   6228:                 my $subans_length =
                   6229:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6230:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6231:                 $subquestions   = substr($subquestions,$subans_length);
                   6232:                 $quest_id = "$questnum.$subquestnum";
                   6233:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6234:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6235:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6236:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6237:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6238:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6239:                 } else {
                   6240:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6241:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6242:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6243:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6244:                 }
                   6245:                 $subquestnum ++;
                   6246:             }
                   6247:         } else {
                   6248:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6249:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6250:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6251:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6252:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6253:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6254:             } else {
                   6255:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6256:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6257:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6258:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6259:             }
                   6260:         }
                   6261:     }
                   6262:     $record{'scantron.maxquest'}=$questnum;
                   6263:     return \%record;
                   6264: }
1.447     foxr     6265: 
1.596.2.12.2.  6(raebur 6266:3): sub get_master_seq {
                   6267:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6268:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6269:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6270:3):     my $resource_error;
                   6271:3):     foreach my $resource (@{$resources}) {
                   6272:3):         my $ressymb;
                   6273:3):         if (ref($resource)) {
                   6274:3):             $ressymb = $resource->symb();
                   6275:3):             push(@{$master_seq},$ressymb);
                   6276:3):             $symb_to_resource->{$ressymb} = $resource;
                   6277:3):         } else {
                   6278:3):             $resource_error = 1;
                   6279:3):             last;
                   6280:3):         }
                   6281:3):     }
                   6282:3):     return $resource_error;
                   6283:3): }
                   6284:3): 
                   6285:3): sub get_respnum_lookups {
                   6286:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6287:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6288:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6289:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6290:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6291:3):                    (ref($startline) eq 'HASH'));
                   6292:3):     my ($user,$scancode);
                   6293:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6294:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6295:3):         $scancode = $record->{'scantron.CODE'};
                   6296:3):     } else {
                   6297:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6298:3):     }
                   6299:3):     my @mapresources =
                   6300:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6301:3):                      $orderedforcode);
                   6302:3):     my $total = 0;
                   6303:3):     my $count = 0;
                   6304:3):     foreach my $resource (@mapresources) {
                   6305:3):         my $id = $resource->id();
                   6306:3):         my $symb = $resource->symb();
                   6307:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6308:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6309:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6310:3):                 if ($respnum ne '') {
                   6311:3):                     $respnumlookup->{$count} = $respnum;
                   6312:3):                     $startline->{$count} = $total;
                   6313:3):                     $total += $bubble_lines_per_response{$respnum};
                   6314:3):                     $count ++;
                   6315:3):                 }
                   6316:3):             }
                   6317:3):         }
                   6318:3):     }
                   6319:3):     return $total;
                   6320:3): }
                   6321:3): 
1.503     raeburn  6322: sub scantron_validator_lettnum {
                   6323:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6324:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6325:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6326: 
                   6327:     # Qon 'letter' implies for each slot in currquest we have:
                   6328:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6329:     #    about anything else (esp. a value of Qoff) for missing
                   6330:     #    bubbles.
                   6331:     #
                   6332:     # Qon 'number' implies each slot gives a digit that indexes the
                   6333:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6334:     #    and * or ? for double bubbles on a single line.
                   6335:     #
1.447     foxr     6336: 
1.503     raeburn  6337:     my $matchon;
                   6338:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6339:         $matchon = '[A-Z]';
                   6340:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6341:         $matchon = '\d';
                   6342:     }
                   6343:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6344:3):     my $responsenum = $questnum-1;
                   6345:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6346:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6347:3):     }
                   6348:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6349:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6350:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6351:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6352:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6353:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6354:         my @singlelines = split('',$currquest);
                   6355:         foreach my $entry (@singlelines) {
                   6356:             $occurrences = &occurence_count($entry,$matchon);
                   6357:             if ($occurrences > 1) {
                   6358:                 last;
                   6359:             }
1.596.2.12.2.  6(raebur 6360:3):         }
1.503     raeburn  6361:     } else {
                   6362:         $occurrences = &occurence_count($currquest,$matchon); 
                   6363:     }
                   6364:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6365:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6366:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6367:             my $bubble = substr($currquest,$ans,1);
                   6368:             if ($bubble =~ /$matchon/ ) {
                   6369:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6370:                     if ($bubble == 0) {
                   6371:                         $bubble = 10; 
                   6372:                     }
                   6373:                     $record->{"scantron.$ansnum.answer"} = 
                   6374:                         $alphabet->[$bubble-1];
                   6375:                 } else {
                   6376:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6377:                 }
                   6378:             } else {
                   6379:                 $record->{"scantron.$ansnum.answer"}='';
                   6380:             }
                   6381:             $ansnum++;
                   6382:         }
                   6383:     } elsif (!defined($currquest)
                   6384:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6385:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6386:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6387:             $record->{"scantron.$ansnum.answer"}='';
                   6388:             $ansnum++;
                   6389:         }
                   6390:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6391:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6392:         }
                   6393:     } else {
                   6394:         if ($$scantron_config{'Qon'} eq 'number') {
                   6395:             $currquest = &digits_to_letters($currquest);            
                   6396:         }
                   6397:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6398:             my $bubble = substr($currquest,$ans,1);
                   6399:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6400:             $ansnum++;
                   6401:         }
                   6402:     }
                   6403:     return $ansnum;
                   6404: }
1.447     foxr     6405: 
1.503     raeburn  6406: sub scantron_validator_positional {
                   6407:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6408:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6409:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6410: 
1.503     raeburn  6411:     # Otherwise there's a positional notation;
                   6412:     # each bubble line requires Qlength items, and there are filled in
                   6413:     # bubbles for each case where there 'Qon' characters.
                   6414:     #
1.447     foxr     6415: 
1.503     raeburn  6416:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6417: 
1.503     raeburn  6418:     # If the split only gives us one element.. the full length of the
                   6419:     # answer string, no bubbles are filled in:
1.447     foxr     6420: 
1.507     raeburn  6421:     if ($answers_needed eq '') {
                   6422:         return;
                   6423:     }
                   6424: 
1.503     raeburn  6425:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6426:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6427:             $record->{"scantron.$ansnum.answer"}='';
                   6428:             $ansnum++;
                   6429:         }
                   6430:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6431:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6432:         }
                   6433:     } elsif (scalar(@array) == 2) {
                   6434:         my $location = length($array[0]);
                   6435:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6436:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6437:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6438:             if ($ans eq $line_num) {
                   6439:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6440:             } else {
                   6441:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6442:             }
                   6443:             $ansnum++;
                   6444:          }
                   6445:     } else {
                   6446:         #  If there's more than one instance of a bubble character
                   6447:         #  That's a double bubble; with positional notation we can
                   6448:         #  record all the bubbles filled in as well as the
                   6449:         #  fact this response consists of multiple bubbles.
                   6450:         #
1.596.2.12.2.  6(raebur 6451:3):         my $responsenum = $questnum-1;
                   6452:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6453:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6454:3):         }
                   6455:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6456:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6457:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6458:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6459:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6460:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6461:             my $doubleerror = 0;
                   6462:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6463:                    (!$doubleerror)) {
                   6464:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6465:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6466:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6467:                if (length(@currarray) > 2) {
                   6468:                    $doubleerror = 1;
                   6469:                } 
                   6470:             }
                   6471:             if ($doubleerror) {
                   6472:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6473:             }
                   6474:         } else {
                   6475:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6476:         }
                   6477:         my $item = $ansnum;
                   6478:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6479:             $record->{"scantron.$item.answer"} = '';
                   6480:             $item ++;
                   6481:         }
1.447     foxr     6482: 
1.503     raeburn  6483:         my @ans=@array;
                   6484:         my $i=0;
                   6485:         my $increment = 0;
                   6486:         while ($#ans) {
                   6487:             $i+=length($ans[0]) + $increment;
                   6488:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6489:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6490:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6491:             shift(@ans);
                   6492:             $increment = 1;
                   6493:         }
                   6494:         $ansnum += $answers_needed;
1.82      albertel 6495:     }
1.503     raeburn  6496:     return $ansnum;
1.82      albertel 6497: }
                   6498: 
1.423     albertel 6499: =pod
                   6500: 
                   6501: =item scantron_add_delay
                   6502: 
                   6503:    Adds an error message that occurred during the grading phase to a
                   6504:    queue of messages to be shown after grading pass is complete
                   6505: 
                   6506:  Arguments:
1.424     albertel 6507:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6508:    $scanline    - the scanline that caused the error
                   6509:    $errormesage - the error message
                   6510:    $errorcode   - a numeric code for the error
                   6511: 
                   6512:  Side Effects:
1.424     albertel 6513:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6514: 
                   6515: =cut
                   6516: 
1.82      albertel 6517: sub scantron_add_delay {
1.140     albertel 6518:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6519:     push(@$delayqueue,
                   6520: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6521: 	  'ecode' => $errorcode }
                   6522: 	 );
1.82      albertel 6523: }
                   6524: 
1.423     albertel 6525: =pod
                   6526: 
                   6527: =item scantron_find_student
                   6528: 
1.424     albertel 6529:    Finds the username for the current scanline
                   6530: 
                   6531:   Arguments:
                   6532:    $scantron_record - hash result from scantron_parse_scanline
                   6533:    $scan_data       - hash of correction information 
                   6534:                       (see &scantron_getfile() form more information)
                   6535:    $idmap           - hash from &username_to_idmap()
                   6536:    $line            - number of current scanline
                   6537:  
                   6538:   Returns:
                   6539:    Either 'username:domain' or undef if unknown
                   6540: 
1.423     albertel 6541: =cut
                   6542: 
1.82      albertel 6543: sub scantron_find_student {
1.157     albertel 6544:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6545:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6546:     if ($scanID =~ /^\s*$/) {
                   6547:  	return &scan_data($scan_data,"$line.user");
                   6548:     }
1.83      albertel 6549:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6550:  	if (lc($id) eq lc($scanID)) {
                   6551:  	    return $$idmap{$id};
                   6552:  	}
1.83      albertel 6553:     }
                   6554:     return undef;
                   6555: }
                   6556: 
1.423     albertel 6557: =pod
                   6558: 
                   6559: =item scantron_filter
                   6560: 
1.424     albertel 6561:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6562:    hidden resources was selected
                   6563: 
1.423     albertel 6564: =cut
                   6565: 
1.83      albertel 6566: sub scantron_filter {
                   6567:     my ($curres)=@_;
1.331     albertel 6568: 
                   6569:     if (ref($curres) && $curres->is_problem()) {
                   6570: 	# if the user has asked to not have either hidden
                   6571: 	# or 'randomout' controlled resources to be graded
                   6572: 	# don't include them
                   6573: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6574: 	    && $curres->randomout) {
                   6575: 	    return 0;
                   6576: 	}
1.83      albertel 6577: 	return 1;
                   6578:     }
                   6579:     return 0;
1.82      albertel 6580: }
                   6581: 
1.423     albertel 6582: =pod
                   6583: 
                   6584: =item scantron_process_corrections
                   6585: 
1.424     albertel 6586:    Gets correction information out of submitted form data and corrects
                   6587:    the scanline
                   6588: 
1.423     albertel 6589: =cut
                   6590: 
1.157     albertel 6591: sub scantron_process_corrections {
                   6592:     my ($r) = @_;
1.257     albertel 6593:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6594:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6595:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6596:     my $which=$env{'form.scantron_line'};
1.200     albertel 6597:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6598:     my ($skip,$err,$errmsg);
1.257     albertel 6599:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6600: 	$skip=1;
1.257     albertel 6601:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6602: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6603: 	    $env{'form.scantron_domain'};
1.157     albertel 6604: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6605: 	($line,$err,$errmsg)=
                   6606: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6607: 				     'ID',{'newid'=>$newid,
1.257     albertel 6608: 				    'username'=>$env{'form.scantron_username'},
                   6609: 				    'domain'=>$env{'form.scantron_domain'}});
                   6610:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6611: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6612: 	my $newCODE;
1.192     albertel 6613: 	my %args;
1.190     albertel 6614: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6615: 	    $newCODE='use_unfound';
1.190     albertel 6616: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6617: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6618: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6619: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6620: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6621: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6622: 	}
1.257     albertel 6623: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6624: 	    $args{'CODE_ignore_dup'}=1;
                   6625: 	}
                   6626: 	$args{'CODE'}=$newCODE;
1.186     albertel 6627: 	($line,$err,$errmsg)=
                   6628: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6629: 				     'CODE',\%args);
1.257     albertel 6630:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6631: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6632: 	    ($line,$err,$errmsg)=
                   6633: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6634: 					 $which,'answer',
                   6635: 					 { 'question'=>$question,
1.503     raeburn  6636: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6637:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6638: 	    if ($err) { last; }
                   6639: 	}
                   6640:     }
                   6641:     if ($err) {
1.596.2.12.2.  0(raebur 6642:3): 	$r->print(
                   6643:3):             '<p class="LC_error">'
                   6644:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6645:3):                 $errmsg)
          1(raebur 6646:3):            .'</p>');
1.157     albertel 6647:     } else {
1.200     albertel 6648: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6649: 	&scantron_putfile($scanlines,$scan_data);
                   6650:     }
                   6651: }
                   6652: 
1.423     albertel 6653: =pod
                   6654: 
                   6655: =item reset_skipping_status
                   6656: 
1.424     albertel 6657:    Forgets the current set of remember skipped scanlines (and thus
                   6658:    reverts back to considering all lines in the
                   6659:    scantron_skipped_<filename> file)
                   6660: 
1.423     albertel 6661: =cut
                   6662: 
1.200     albertel 6663: sub reset_skipping_status {
                   6664:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6665:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6666:     &scantron_putfile(undef,$scan_data);
                   6667: }
                   6668: 
1.423     albertel 6669: =pod
                   6670: 
                   6671: =item start_skipping
                   6672: 
1.424     albertel 6673:    Marks a scanline to be skipped. 
                   6674: 
1.423     albertel 6675: =cut
                   6676: 
1.376     albertel 6677: sub start_skipping {
1.200     albertel 6678:     my ($scan_data,$i)=@_;
                   6679:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6680:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6681: 	$remembered{$i}=2;
                   6682:     } else {
                   6683: 	$remembered{$i}=1;
                   6684:     }
1.200     albertel 6685:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6686: }
                   6687: 
1.423     albertel 6688: =pod
                   6689: 
                   6690: =item should_be_skipped
                   6691: 
1.424     albertel 6692:    Checks whether a scanline should be skipped.
                   6693: 
1.423     albertel 6694: =cut
                   6695: 
1.200     albertel 6696: sub should_be_skipped {
1.376     albertel 6697:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6698:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6699: 	# not redoing old skips
1.376     albertel 6700: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6701: 	return 0;
                   6702:     }
                   6703:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6704: 
                   6705:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6706: 	return 0;
                   6707:     }
1.200     albertel 6708:     return 1;
                   6709: }
                   6710: 
1.423     albertel 6711: =pod
                   6712: 
                   6713: =item remember_current_skipped
                   6714: 
1.424     albertel 6715:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6716:    file and remembers them into scan_data for later use.
                   6717: 
1.423     albertel 6718: =cut
                   6719: 
1.200     albertel 6720: sub remember_current_skipped {
                   6721:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6722:     my %to_remember;
                   6723:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6724: 	if ($scanlines->{'skipped'}[$i]) {
                   6725: 	    $to_remember{$i}=1;
                   6726: 	}
                   6727:     }
1.376     albertel 6728: 
1.200     albertel 6729:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6730:     &scantron_putfile(undef,$scan_data);
                   6731: }
                   6732: 
1.423     albertel 6733: =pod
                   6734: 
                   6735: =item check_for_error
                   6736: 
1.424     albertel 6737:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  6738:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6739:     something went wrong.
                   6740: 
1.423     albertel 6741: =cut
                   6742: 
1.200     albertel 6743: sub check_for_error {
                   6744:     my ($r,$result)=@_;
                   6745:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6746: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6747:     }
                   6748: }
1.157     albertel 6749: 
1.423     albertel 6750: =pod
                   6751: 
                   6752: =item scantron_warning_screen
                   6753: 
1.424     albertel 6754:    Interstitial screen to make sure the operator has selected the
                   6755:    correct options before we start the validation phase.
                   6756: 
1.423     albertel 6757: =cut
                   6758: 
1.203     albertel 6759: sub scantron_warning_screen {
                   6760:     my ($button_text)=@_;
1.257     albertel 6761:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6762:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6763:     my $CODElist;
1.284     albertel 6764:     if ($scantron_config{'CODElocation'} &&
                   6765: 	$scantron_config{'CODEstart'} &&
                   6766: 	$scantron_config{'CODElength'}) {
                   6767: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 6768:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6769: 	$CODElist=
1.492     albertel 6770: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6771: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6772:     }
1.596.2.12.2.  (raeburn 6773:):     my $lastbubblepoints;
                   6774:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6775:):         $lastbubblepoints =
                   6776:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6777:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6778:):     }
1.492     albertel 6779:     return ('
1.203     albertel 6780: <p>
1.492     albertel 6781: <span class="LC_warning">
1.596.2.12.2.  6(raebur 6782:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6783: </p>
                   6784: <table>
1.492     albertel 6785: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6786: <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 6787:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 6788: </table>
                   6789: <br />
1.596.2.12.2.  2(raebur 6790:2): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
                   6791:2): <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
1.203     albertel 6792: 
                   6793: <br />
1.492     albertel 6794: ');
1.203     albertel 6795: }
                   6796: 
1.423     albertel 6797: =pod
                   6798: 
                   6799: =item scantron_do_warning
                   6800: 
1.424     albertel 6801:    Check if the operator has picked something for all required
                   6802:    fields. Error out if something is missing.
                   6803: 
1.423     albertel 6804: =cut
                   6805: 
1.203     albertel 6806: sub scantron_do_warning {
                   6807:     my ($r)=@_;
1.324     albertel 6808:     my ($symb)=&get_symb($r);
1.203     albertel 6809:     if (!$symb) {return '';}
1.324     albertel 6810:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6811:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6812:     if ( $env{'form.selectpage'} eq '' ||
                   6813: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6814: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  6815: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6816: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6817: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6818: 	} 
1.257     albertel 6819: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  6820: 	    $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 6821: 	} 
1.257     albertel 6822: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  6823: 	    $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 6824: 	} 
                   6825:     } else {
1.265     www      6826: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.596.2.12.2.  (raeburn 6827:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6828: 	$r->print('
1.596.2.12.2.  (raeburn 6829:): '.$warning.$bubbledbyhand.'
1.492     albertel 6830: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6831: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6832: ');
1.237     albertel 6833:     }
1.352     albertel 6834:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6835:     return '';
                   6836: }
                   6837: 
1.423     albertel 6838: =pod
                   6839: 
                   6840: =item scantron_form_start
                   6841: 
1.424     albertel 6842:     html hidden input for remembering all selected grading options
                   6843: 
1.423     albertel 6844: =cut
                   6845: 
1.203     albertel 6846: sub scantron_form_start {
                   6847:     my ($max_bubble)=@_;
                   6848:     my $result= <<SCANTRONFORM;
                   6849: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6850:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6851:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6852:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6853:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6854:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6855:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6856:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6857:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6858:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6859: SCANTRONFORM
1.447     foxr     6860: 
                   6861:   my $line = 0;
                   6862:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6863:        my $chunk =
                   6864: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6865:        $chunk .=
                   6866: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6867:        $chunk .= 
                   6868:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6869:        $chunk .=
                   6870:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 6871:3):        $chunk .=
                   6872:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6873:        $result .= $chunk;
                   6874:        $line++;
1.596.2.12.2.  6(raebur 6875:3):     }
1.203     albertel 6876:     return $result;
                   6877: }
                   6878: 
1.423     albertel 6879: =pod
                   6880: 
                   6881: =item scantron_validate_file
                   6882: 
1.596.2.6  raeburn  6883:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6884: 
                   6885:     Also processes any necessary information resets that need to
                   6886:     occur before validation begins (ignore previous corrections,
                   6887:     restarting the skipped records processing)
                   6888: 
1.423     albertel 6889: =cut
                   6890: 
1.157     albertel 6891: sub scantron_validate_file {
                   6892:     my ($r) = @_;
1.324     albertel 6893:     my ($symb)=&get_symb($r);
1.157     albertel 6894:     if (!$symb) {return '';}
1.324     albertel 6895:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6896:     
1.596.2.12.2.  0(raebur 6897:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 6898:     # them when doing the corrections reset
1.257     albertel 6899:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6900: 	&reset_skipping_status();
                   6901:     }
1.257     albertel 6902:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6903: 	&remember_current_skipped();
1.257     albertel 6904: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6905:     }
                   6906: 
1.257     albertel 6907:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6908: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6909: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6910: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6911: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6912:     }
1.200     albertel 6913: 
1.257     albertel 6914:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6915: 	&scantron_process_corrections($r);
                   6916:     }
1.503     raeburn  6917:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6918:     #get the student pick code ready
                   6919:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6920:     my $nav_error;
1.596.2.12.2.  (raeburn 6921:):     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6922:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6923:     if ($nav_error) {
                   6924:         $r->print(&navmap_errormsg());
                   6925:         return '';
                   6926:     }
1.203     albertel 6927:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 6928:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6929:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6930:):     }
1.157     albertel 6931:     $r->print($result);
                   6932:     
1.334     albertel 6933:     my @validate_phases=( 'sequence',
                   6934: 			  'ID',
1.157     albertel 6935: 			  'CODE',
                   6936: 			  'doublebubble',
                   6937: 			  'missingbubbles');
1.257     albertel 6938:     if (!$env{'form.validatepass'}) {
                   6939: 	$env{'form.validatepass'} = 0;
1.157     albertel 6940:     }
1.257     albertel 6941:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6942: 
1.448     foxr     6943: 
1.157     albertel 6944:     my $stop=0;
                   6945:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6946: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6947: 	$r->rflush();
1.596.2.12.2.  6(raebur 6948:3): 
1.157     albertel 6949: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6950: 	{
                   6951: 	    no strict 'refs';
                   6952: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6953: 	}
                   6954:     }
                   6955:     if (!$stop) {
1.203     albertel 6956: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6957: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6958:                   $warning.
                   6959:                   &mt('Perform verification for each student after storage of submissions?').
                   6960:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6961:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6962:                   ('&nbsp;'x3).'<label>'.
                   6963:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6964:                   '</label></span><br />'.
                   6965:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6966:                   &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  6967:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6968:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6969:     } else {
                   6970: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6971: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6972:     }
                   6973:     if ($stop) {
1.334     albertel 6974: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6975: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6976: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6977: 
1.492     albertel 6978: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6979: 	} else {
1.503     raeburn  6980:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6981: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6982:             } else {
1.539     riegler  6983:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6984:             }
1.492     albertel 6985: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6986: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6987: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6988: 	}
1.157     albertel 6989:     }
1.352     albertel 6990:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6991:     return '';
                   6992: }
                   6993: 
1.423     albertel 6994: 
                   6995: =pod
                   6996: 
                   6997: =item scantron_remove_file
                   6998: 
1.596.2.6  raeburn  6999:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7000:    scantron_original_<filename> is never removed
                   7001: 
                   7002: 
1.423     albertel 7003: =cut
                   7004: 
1.200     albertel 7005: sub scantron_remove_file {
1.192     albertel 7006:     my ($which)=@_;
1.257     albertel 7007:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7008:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7009:     my $file='scantron_';
1.200     albertel 7010:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7011: 	$file.=$which.'_';
1.192     albertel 7012:     } else {
                   7013: 	return 'refused';
                   7014:     }
1.257     albertel 7015:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7016:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7017: }
                   7018: 
1.423     albertel 7019: 
                   7020: =pod
                   7021: 
                   7022: =item scantron_remove_scan_data
                   7023: 
1.596.2.6  raeburn  7024:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7025:    data file.  (In the case that both the are doing skipped records we need
                   7026:    to remember the old skipped lines for the time being so that element
                   7027:    persists for a while.)
                   7028: 
1.423     albertel 7029: =cut
                   7030: 
1.200     albertel 7031: sub scantron_remove_scan_data {
1.257     albertel 7032:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7033:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7034:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7035:     my @todelete;
1.257     albertel 7036:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7037:     foreach my $key (@keys) {
                   7038: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7039: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7040: 		$key=~/remember_skipping/) {
                   7041: 		next;
                   7042: 	    }
1.192     albertel 7043: 	    push(@todelete,$key);
                   7044: 	}
                   7045:     }
1.200     albertel 7046:     my $result;
1.192     albertel 7047:     if (@todelete) {
1.491     albertel 7048: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7049: 				       \@todelete,$cdom,$cname);
                   7050:     } else {
                   7051: 	$result = 'ok';
1.192     albertel 7052:     }
                   7053:     return $result;
                   7054: }
                   7055: 
1.423     albertel 7056: 
                   7057: =pod
                   7058: 
                   7059: =item scantron_getfile
                   7060: 
1.596.2.6  raeburn  7061:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7062:     the scan_data hash
                   7063:   
                   7064:   Arguments:
                   7065:     None
                   7066: 
                   7067:   Returns:
                   7068:     2 hash references
                   7069: 
                   7070:      - first one has 
                   7071:          orig      -
                   7072:          corrected -
                   7073:          skipped   -  each of which points to an array ref of the specified
                   7074:                       file broken up into individual lines
                   7075:          count     - number of scanlines
                   7076:  
                   7077:      - second is the scan_data hash possible keys are
1.425     albertel 7078:        ($number refers to scanline numbered $number and thus the key affects
                   7079:         only that scanline
                   7080:         $bubline refers to the specific bubble line element and the aspects
                   7081:         refers to that specific bubble line element)
                   7082: 
                   7083:        $number.user - username:domain to use
                   7084:        $number.CODE_ignore_dup 
                   7085:                     - ignore the duplicate CODE error 
                   7086:        $number.useCODE
                   7087:                     - use the CODE in the scanline as is
                   7088:        $number.no_bubble.$bubline
                   7089:                     - it is valid that there is no bubbled in bubble
                   7090:                       at $number $bubline
                   7091:        remember_skipping
                   7092:                     - a frozen hash containing keys of $number and values
                   7093:                       of either 
                   7094:                         1 - we are on a 'do skipped records pass' and plan
                   7095:                             on processing this line
                   7096:                         2 - we are on a 'do skipped records pass' and this
                   7097:                             scanline has been marked to skip yet again
1.424     albertel 7098: 
1.423     albertel 7099: =cut
                   7100: 
1.157     albertel 7101: sub scantron_getfile {
1.200     albertel 7102:     #FIXME really would prefer a scantron directory
1.257     albertel 7103:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7104:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7105:     my $lines;
                   7106:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7107: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7108:     my %scanlines;
                   7109:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7110:     my $temp=$scanlines{'orig'};
                   7111:     $scanlines{'count'}=$#$temp;
                   7112: 
                   7113:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7114: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7115:     if ($lines eq '-1') {
                   7116: 	$scanlines{'corrected'}=[];
                   7117:     } else {
                   7118: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7119:     }
                   7120:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7121: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7122:     if ($lines eq '-1') {
                   7123: 	$scanlines{'skipped'}=[];
                   7124:     } else {
                   7125: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7126:     }
1.175     albertel 7127:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7128:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7129:     my %scan_data = @tmp;
                   7130:     return (\%scanlines,\%scan_data);
                   7131: }
                   7132: 
1.423     albertel 7133: =pod
                   7134: 
                   7135: =item lonnet_putfile
                   7136: 
1.424     albertel 7137:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7138: 
                   7139:  Arguments:
                   7140:    $contents - data to store
                   7141:    $filename - filename to store $contents into
                   7142: 
                   7143:  Returns:
                   7144:    result value from &Apache::lonnet::finishuserfileupload
                   7145: 
1.423     albertel 7146: =cut
                   7147: 
1.157     albertel 7148: sub lonnet_putfile {
                   7149:     my ($contents,$filename)=@_;
1.257     albertel 7150:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7151:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7152:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7153:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7154: 
                   7155: }
                   7156: 
1.423     albertel 7157: =pod
                   7158: 
                   7159: =item scantron_putfile
                   7160: 
1.596.2.6  raeburn  7161:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7162:     scan_data hash. (Does not modify the original version only the
                   7163:     corrected and skipped versions.
                   7164: 
                   7165:  Arguments:
                   7166:     $scanlines - hash ref that looks like the first return value from
                   7167:                  &scantron_getfile()
                   7168:     $scan_data - hash ref that looks like the second return value from
                   7169:                  &scantron_getfile()
                   7170: 
1.423     albertel 7171: =cut
                   7172: 
1.157     albertel 7173: sub scantron_putfile {
                   7174:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7175:     #FIXME really would prefer a scantron directory
1.257     albertel 7176:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7177:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7178:     if ($scanlines) {
                   7179: 	my $prefix='scantron_';
1.157     albertel 7180: # no need to update orig, shouldn't change
                   7181: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7182: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7183: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7184: 			$prefix.'corrected_'.
1.257     albertel 7185: 			$env{'form.scantron_selectfile'});
1.200     albertel 7186: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7187: 			$prefix.'skipped_'.
1.257     albertel 7188: 			$env{'form.scantron_selectfile'});
1.200     albertel 7189:     }
1.175     albertel 7190:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7191: }
                   7192: 
1.423     albertel 7193: =pod
                   7194: 
                   7195: =item scantron_get_line
                   7196: 
1.424     albertel 7197:    Returns the correct version of the scanline
                   7198: 
                   7199:  Arguments:
                   7200:     $scanlines - hash ref that looks like the first return value from
                   7201:                  &scantron_getfile()
                   7202:     $scan_data - hash ref that looks like the second return value from
                   7203:                  &scantron_getfile()
                   7204:     $i         - number of the requested line (starts at 0)
                   7205: 
                   7206:  Returns:
                   7207:    A scanline, (either the original or the corrected one if it
                   7208:    exists), or undef if the requested scanline should be
                   7209:    skipped. (Either because it's an skipped scanline, or it's an
                   7210:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7211:    pass.
                   7212: 
1.423     albertel 7213: =cut
                   7214: 
1.157     albertel 7215: sub scantron_get_line {
1.200     albertel 7216:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7217:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7218:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7219:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7220:     return $scanlines->{'orig'}[$i]; 
                   7221: }
                   7222: 
1.423     albertel 7223: =pod
                   7224: 
                   7225: =item scantron_todo_count
                   7226: 
1.424     albertel 7227:     Counts the number of scanlines that need processing.
                   7228: 
                   7229:  Arguments:
                   7230:     $scanlines - hash ref that looks like the first return value from
                   7231:                  &scantron_getfile()
                   7232:     $scan_data - hash ref that looks like the second return value from
                   7233:                  &scantron_getfile()
                   7234: 
                   7235:  Returns:
                   7236:     $count - number of scanlines to process
                   7237: 
1.423     albertel 7238: =cut
                   7239: 
1.200     albertel 7240: sub get_todo_count {
                   7241:     my ($scanlines,$scan_data)=@_;
                   7242:     my $count=0;
                   7243:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7244: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7245: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7246: 	$count++;
                   7247:     }
                   7248:     return $count;
                   7249: }
                   7250: 
1.423     albertel 7251: =pod
                   7252: 
                   7253: =item scantron_put_line
                   7254: 
1.596.2.6  raeburn  7255:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7256:     data file.
                   7257: 
                   7258:  Arguments:
                   7259:     $scanlines - hash ref that looks like the first return value from
                   7260:                  &scantron_getfile()
                   7261:     $scan_data - hash ref that looks like the second return value from
                   7262:                  &scantron_getfile()
                   7263:     $i         - line number to update
                   7264:     $newline   - contents of the updated scanline
                   7265:     $skip      - if true make the line for skipping and update the
                   7266:                  'skipped' file
                   7267: 
1.423     albertel 7268: =cut
                   7269: 
1.157     albertel 7270: sub scantron_put_line {
1.200     albertel 7271:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7272:     if ($skip) {
                   7273: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7274: 	&start_skipping($scan_data,$i);
1.157     albertel 7275: 	return;
                   7276:     }
                   7277:     $scanlines->{'corrected'}[$i]=$newline;
                   7278: }
                   7279: 
1.423     albertel 7280: =pod
                   7281: 
                   7282: =item scantron_clear_skip
                   7283: 
1.424     albertel 7284:    Remove a line from the 'skipped' file
                   7285: 
                   7286:  Arguments:
                   7287:     $scanlines - hash ref that looks like the first return value from
                   7288:                  &scantron_getfile()
                   7289:     $scan_data - hash ref that looks like the second return value from
                   7290:                  &scantron_getfile()
                   7291:     $i         - line number to update
                   7292: 
1.423     albertel 7293: =cut
                   7294: 
1.376     albertel 7295: sub scantron_clear_skip {
                   7296:     my ($scanlines,$scan_data,$i)=@_;
                   7297:     if (exists($scanlines->{'skipped'}[$i])) {
                   7298: 	undef($scanlines->{'skipped'}[$i]);
                   7299: 	return 1;
                   7300:     }
                   7301:     return 0;
                   7302: }
                   7303: 
1.423     albertel 7304: =pod
                   7305: 
                   7306: =item scantron_filter_not_exam
                   7307: 
1.424     albertel 7308:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7309:    filter out resources that are not marked as 'exam' mode
                   7310: 
1.423     albertel 7311: =cut
                   7312: 
1.334     albertel 7313: sub scantron_filter_not_exam {
                   7314:     my ($curres)=@_;
                   7315:     
                   7316:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7317: 	# if the user has asked to not have either hidden
                   7318: 	# or 'randomout' controlled resources to be graded
                   7319: 	# don't include them
                   7320: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7321: 	    && $curres->randomout) {
                   7322: 	    return 0;
                   7323: 	}
                   7324: 	return 1;
                   7325:     }
                   7326:     return 0;
                   7327: }
                   7328: 
1.423     albertel 7329: =pod
                   7330: 
                   7331: =item scantron_validate_sequence
                   7332: 
1.424     albertel 7333:     Validates the selected sequence, checking for resource that are
                   7334:     not set to exam mode.
                   7335: 
1.423     albertel 7336: =cut
                   7337: 
1.334     albertel 7338: sub scantron_validate_sequence {
                   7339:     my ($r,$currentphase) = @_;
                   7340: 
                   7341:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7342:     unless (ref($navmap)) {
                   7343:         $r->print(&navmap_errormsg());
                   7344:         return (1,$currentphase);
                   7345:     }
1.334     albertel 7346:     my (undef,undef,$sequence)=
                   7347: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7348: 
                   7349:     my $map=$navmap->getResourceByUrl($sequence);
                   7350: 
                   7351:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7352:                                     value="ignore" />');
                   7353:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7354: 	my @resources=
                   7355: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7356: 	if (@resources) {
1.596.2.12.2.  0(raebur 7357:2): 	    $r->print('<p class="LC_warning">'
                   7358:2):                .&mt('Some resources in the sequence currently are not set to'
                   7359:2):                    .' exam mode. Grading these resources currently may not'
                   7360:2):                    .' work correctly.')
                   7361:2):                .'</p>'
                   7362:2):             );
1.334     albertel 7363: 	    return (1,$currentphase);
                   7364: 	}
                   7365:     }
                   7366: 
                   7367:     return (0,$currentphase+1);
                   7368: }
                   7369: 
1.423     albertel 7370: 
                   7371: 
1.157     albertel 7372: sub scantron_validate_ID {
                   7373:     my ($r,$currentphase) = @_;
                   7374:     
                   7375:     #get student info
                   7376:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7377:     my %idmap=&username_to_idmap($classlist);
                   7378: 
                   7379:     #get scantron line setup
1.257     albertel 7380:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7381:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7382: 
                   7383:     my $nav_error;
1.596.2.12.2.  (raeburn 7384:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7385:     if ($nav_error) {
                   7386:         $r->print(&navmap_errormsg());
                   7387:         return(1,$currentphase);
                   7388:     }
1.157     albertel 7389: 
                   7390:     my %found=('ids'=>{},'usernames'=>{});
                   7391:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7392: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7393: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7394: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7395: 						 $scan_data);
                   7396: 	my $id=$$scan_record{'scantron.ID'};
                   7397: 	my $found;
                   7398: 	foreach my $checkid (keys(%idmap)) {
                   7399: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7400: 	}
                   7401: 	if ($found) {
                   7402: 	    my $username=$idmap{$found};
                   7403: 	    if ($found{'ids'}{$found}) {
                   7404: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7405: 					 $line,'duplicateID',$found);
1.194     albertel 7406: 		return(1,$currentphase);
1.157     albertel 7407: 	    } elsif ($found{'usernames'}{$username}) {
                   7408: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7409: 					 $line,'duplicateID',$username);
1.194     albertel 7410: 		return(1,$currentphase);
1.157     albertel 7411: 	    }
1.186     albertel 7412: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7413: 	    $found{'ids'}{$found}++;
                   7414: 	    $found{'usernames'}{$username}++;
                   7415: 	} else {
                   7416: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7417: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7418: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7419: 		    &scantron_get_correction($r,$i,$scan_record,
                   7420: 					     \%scantron_config,
                   7421: 					     $line,'duplicateID',$username);
1.194     albertel 7422: 		    return(1,$currentphase);
1.157     albertel 7423: 		} elsif (!defined($username)) {
                   7424: 		    &scantron_get_correction($r,$i,$scan_record,
                   7425: 					     \%scantron_config,
                   7426: 					     $line,'incorrectID');
1.194     albertel 7427: 		    return(1,$currentphase);
1.157     albertel 7428: 		}
                   7429: 		$found{'usernames'}{$username}++;
                   7430: 	    } else {
                   7431: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7432: 					 $line,'incorrectID');
1.194     albertel 7433: 		return(1,$currentphase);
1.157     albertel 7434: 	    }
                   7435: 	}
                   7436:     }
                   7437: 
                   7438:     return (0,$currentphase+1);
                   7439: }
                   7440: 
1.423     albertel 7441: 
1.157     albertel 7442: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7443:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7444:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7445: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7446: #to show both the current line and the previous one and allow skipping
                   7447: #the previous one or the current one
                   7448: 
1.333     albertel 7449:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7450:         $r->print(
                   7451:             '<p class="LC_warning">'
                   7452:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7453:                 "<b>$error</b>",
                   7454:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7455:            ."</p> \n");
1.157     albertel 7456:     } else {
1.596.2.6  raeburn  7457:         $r->print(
                   7458:             '<p class="LC_warning">'
                   7459:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7460:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7461:            ."</p> \n");
                   7462:     }
                   7463:     my $message =
                   7464:         '<p>'
                   7465:        .&mt('The ID on the form is [_1]',
                   7466:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7467:        .'<br />'
1.596.2.12  raeburn  7468:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7469:             $$scan_record{'scantron.LastName'},
                   7470:             $$scan_record{'scantron.FirstName'})
                   7471:        .'</p>';
1.242     albertel 7472: 
1.157     albertel 7473:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7474:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7475:                            # Array populated for doublebubble or
                   7476:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7477:                            # to validate radio button checking   
                   7478: 
1.157     albertel 7479:     if ($error =~ /ID$/) {
1.186     albertel 7480: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7481: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7482: 		      "</p>\n");
1.157     albertel 7483: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7484: 	    $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 7485: 	}
1.242     albertel 7486: 	$r->print($message);
1.492     albertel 7487: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7488: 	$r->print("\n<ul><li> ");
                   7489: 	#FIXME it would be nice if this sent back the user ID and
                   7490: 	#could do partial userID matches
                   7491: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7492: 				       'scantron_username','scantron_domain'));
                   7493: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7494:3): 	$r->print("\n:\n".
1.257     albertel 7495: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7496: 
                   7497: 	$r->print('</li>');
1.186     albertel 7498:     } elsif ($error =~ /CODE$/) {
                   7499: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7500: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7501: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7502: 	    $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 7503: 	}
1.596.2.6  raeburn  7504:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7505:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7506:                  ."</p>\n");
1.242     albertel 7507: 	$r->print($message);
1.596.2.6  raeburn  7508: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7509: 	$r->print("\n<br /> ");
1.194     albertel 7510: 	my $i=0;
1.273     albertel 7511: 	if ($error eq 'incorrectCODE' 
                   7512: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7513: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7514: 	    if ($closest > 0) {
                   7515: 		foreach my $testcode (@{$closest}) {
                   7516: 		    my $checked='';
1.569     bisitz   7517: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7518: 		    $r->print("
                   7519:    <label>
1.569     bisitz   7520:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7521:        ".&mt("Use the similar CODE [_1] instead.",
                   7522: 	    "<b><tt>".$testcode."</tt></b>")."
                   7523:     </label>
                   7524:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7525: 		    $r->print("\n<br />");
                   7526: 		    $i++;
                   7527: 		}
1.194     albertel 7528: 	    }
                   7529: 	}
1.273     albertel 7530: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7531: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7532: 	    $r->print("
                   7533:     <label>
1.569     bisitz   7534:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7535:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7536: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7537:     </label>");
1.273     albertel 7538: 	    $r->print("\n<br />");
                   7539: 	}
1.194     albertel 7540: 
1.188     albertel 7541: 	$r->print(<<ENDSCRIPT);
                   7542: <script type="text/javascript">
                   7543: function change_radio(field) {
1.190     albertel 7544:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7545:     var i;
                   7546:     for (i=0;i<slct.length;i++) {
                   7547:         if (slct[i].value==field) { slct[i].checked=true; }
                   7548:     }
                   7549: }
                   7550: </script>
                   7551: ENDSCRIPT
1.187     albertel 7552: 	my $href="/adm/pickcode?".
1.359     www      7553: 	   "form=".&escape("scantronupload").
                   7554: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7555: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7556: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7557: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7558: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7559: 	    $r->print("
                   7560:     <label>
                   7561:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7562:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7563: 	     "<a target='_blank' href='$href'>","</a>")."
                   7564:     </label> 
1.558     bisitz   7565:     ".&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 7566: 	    $r->print("\n<br />");
                   7567: 	}
1.492     albertel 7568: 	$r->print("
                   7569:     <label>
                   7570:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7571:        ".&mt("Use [_1] as the CODE.",
                   7572: 	     "</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 7573: 	$r->print("\n<br /><br />");
1.157     albertel 7574:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7575: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7576: 
                   7577: 	# The form field scantron_questions is acutally a list of line numbers.
                   7578: 	# represented by this form so:
                   7579: 
1.596.2.12.2.  6(raebur 7580:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7581:3):                                                 $respnumlookup,$startline);
1.497     foxr     7582: 
1.157     albertel 7583: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7584: 		  $line_list.'" />');
1.242     albertel 7585: 	$r->print($message);
1.492     albertel 7586: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7587: 	foreach my $question (@{$arg}) {
1.503     raeburn  7588: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7589:3):                                                    $scan_record, $error,
                   7590:3):                                                    $randomorder,$randompick,
                   7591:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7592:             push(@lines_to_correct,@linenums);
1.157     albertel 7593: 	}
1.503     raeburn  7594:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7595:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7596: 	$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 7597: 	$r->print($message);
1.492     albertel 7598: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7599: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7600: 
1.503     raeburn  7601: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7602: 	# a list of question numbers. Therefore:
                   7603: 	#
                   7604: 	
1.596.2.12.2.  6(raebur 7605:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7606:3):                                                 $respnumlookup,$startline);
1.497     foxr     7607: 
1.157     albertel 7608: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7609: 		  $line_list.'" />');
1.157     albertel 7610: 	foreach my $question (@{$arg}) {
1.503     raeburn  7611: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7612:3):                                                    $scan_record, $error,
                   7613:3):                                                    $randomorder,$randompick,
                   7614:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7615:             push(@lines_to_correct,@linenums);
1.157     albertel 7616: 	}
1.503     raeburn  7617:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7618:     } else {
                   7619: 	$r->print("\n<ul>");
                   7620:     }
                   7621:     $r->print("\n</li></ul>");
1.497     foxr     7622: }
                   7623: 
1.503     raeburn  7624: sub verify_bubbles_checked {
                   7625:     my (@ansnums) = @_;
                   7626:     my $ansnumstr = join('","',@ansnums);
                   7627:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   7628:     my $output = (<<ENDSCRIPT);
                   7629: <script type="text/javascript">
                   7630: function verify_bubble_radio(form) {
                   7631:     var ansnumArray = new Array ("$ansnumstr");
                   7632:     var need_bubble_count = 0;
                   7633:     for (var i=0; i<ansnumArray.length; i++) {
                   7634:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7635:             var bubble_picked = 0; 
                   7636:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7637:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7638:                     bubble_picked = 1;
                   7639:                 }
                   7640:             }
                   7641:             if (bubble_picked == 0) {
                   7642:                 need_bubble_count ++;
                   7643:             }
                   7644:         }
                   7645:     }
                   7646:     if (need_bubble_count) {
                   7647:         alert("$warning");
                   7648:         return;
                   7649:     }
                   7650:     form.submit(); 
                   7651: }
                   7652: </script>
                   7653: ENDSCRIPT
                   7654:     return $output;
                   7655: }
                   7656: 
1.497     foxr     7657: =pod
                   7658: 
                   7659: =item  questions_to_line_list
1.157     albertel 7660: 
1.497     foxr     7661: Converts a list of questions into a string of comma separated
                   7662: line numbers in the answer sheet used by the questions.  This is
                   7663: used to fill in the scantron_questions form field.
                   7664: 
                   7665:   Arguments:
                   7666:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7667:3):      randomorder  - True if randomorder in use.
                   7668:3):      randompick   - True if randompick in use.
                   7669:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7670:3):                      for current line to question number used for same question
                   7671:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7672:3):      startline    - Reference to hash where key is question number (0 is first)
                   7673:3):                     and key is number of first bubble line for current student
                   7674:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7675: 
                   7676: =cut
                   7677: 
                   7678: 
                   7679: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7680:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7681:     my @lines;
                   7682: 
1.503     raeburn  7683:     foreach my $item (@{$questions}) {
                   7684:         my $question = $item;
                   7685:         my ($first,$count,$last);
                   7686:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7687:             $question = $1;
                   7688:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7689:3):             my $responsenum = $question-1;
                   7690:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7691:3):                 $responsenum = $respnumlookup->{$question-1};
                   7692:3):                 if (ref($startline) eq 'HASH') {
                   7693:3):                     $first = $startline->{$question-1} + 1;
                   7694:3):                 }
                   7695:3):             } else {
                   7696:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7697:3):             }
          7(raebur 7698:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7699:             my $subcount = 1;
                   7700:             while ($subcount<$subquestion) {
                   7701:                 $first += $subans[$subcount-1];
                   7702:                 $subcount ++;
                   7703:             }
                   7704:             $count = $subans[$subquestion-1];
                   7705:         } else {
1.596.2.12.2.  7(raebur 7706:3):             my $responsenum = $question-1;
                   7707:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7708:3):                 $responsenum = $respnumlookup->{$question-1};
                   7709:3):                 if (ref($startline) eq 'HASH') {
                   7710:3):                     $first = $startline->{$question-1} + 1;
                   7711:3):                 }
                   7712:3):             } else {
                   7713:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7714:3):             }
                   7715:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7716:         }
1.506     raeburn  7717:         $last = $first+$count-1;
1.503     raeburn  7718:         push(@lines, ($first..$last));
1.497     foxr     7719:     }
                   7720:     return join(',', @lines);
                   7721: }
                   7722: 
                   7723: =pod 
                   7724: 
                   7725: =item prompt_for_corrections
                   7726: 
                   7727: Prompts for a potentially multiline correction to the
                   7728: user's bubbling (factors out common code from scantron_get_correction
                   7729: for multi and missing bubble cases).
                   7730: 
                   7731:  Arguments:
                   7732:    $r           - Apache request object.
                   7733:    $question    - The question number to prompt for.
                   7734:    $scan_config - The scantron file configuration hash.
                   7735:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7736:    $error       - Type of error
1.596.2.12.2.  7(raebur 7737:3):    $randomorder - True if randomorder in use.
                   7738:3):    $randompick  - True if randompick in use.
                   7739:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7740:3):                     for current line to question number used for same question
                   7741:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   7742:3):    $startline   - Reference to hash where key is question number (0 is first)
                   7743:3):                   and value is number of first bubble line for current student
                   7744:3):                   or code-based randompick and/or randomorder.
1.497     foxr     7745: 
                   7746:  Implicit inputs:
                   7747:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7748:                                   Numbered from 0 (but question numbers are from
                   7749:                                   1.
                   7750:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7751:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7752:                                   type problems render as separate sub-questions, 
1.503     raeburn  7753:                                   in exam mode. This hash contains a 
                   7754:                                   comma-separated list of the lines per 
                   7755:                                   sub-question.
1.510     raeburn  7756:    %responsetype_per_response   - essayresponse, formularesponse,
                   7757:                                   stringresponse, imageresponse, reactionresponse,
                   7758:                                   and organicresponse type problem parts can have
1.503     raeburn  7759:                                   multiple lines per response if the weight
                   7760:                                   assigned exceeds 10.  In this case, only
                   7761:                                   one bubble per line is permitted, but more 
                   7762:                                   than one line might contain bubbles, e.g.
                   7763:                                   bubbling of: line 1 - J, line 2 - J, 
                   7764:                                   line 3 - B would assign 22 points.  
1.497     foxr     7765: 
                   7766: =cut
                   7767: 
                   7768: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 7769:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7770:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7771:     my ($current_line,$lines);
                   7772:     my @linenums;
                   7773:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 7774:3):     my ($first,$responsenum);
1.503     raeburn  7775:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7776:         $question = $1;
                   7777:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 7778:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7779:3):             $responsenum = $respnumlookup->{$question-1};
                   7780:3):             if (ref($startline) eq 'HASH') {
                   7781:3):                 $first = $startline->{$question-1};
                   7782:3):             }
                   7783:3):         } else {
                   7784:3):             $responsenum = $question-1;
          7(raebur 7785:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 7786:3):         }
                   7787:3):         $current_line = $first + 1 ;
                   7788:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7789:         my $subcount = 1;
                   7790:         while ($subcount<$subquestion) {
                   7791:             $current_line += $subans[$subcount-1];
                   7792:             $subcount ++;
                   7793:         }
                   7794:         $lines = $subans[$subquestion-1];
                   7795:     } else {
1.596.2.12.2.  6(raebur 7796:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7797:3):             $responsenum = $respnumlookup->{$question-1};
                   7798:3):             if (ref($startline) eq 'HASH') {
                   7799:3):                 $first = $startline->{$question-1};
                   7800:3):             }
                   7801:3):         } else {
                   7802:3):             $responsenum = $question-1;
                   7803:3):             $first = $first_bubble_line{$responsenum};
                   7804:3):         }
                   7805:3):         $current_line = $first + 1;
                   7806:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7807:     }
1.497     foxr     7808:     if ($lines > 1) {
1.503     raeburn  7809:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 7810:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7811:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7812:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7813:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7814:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7815:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 7816: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  7817:         } else {
                   7818:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7819:         }
1.497     foxr     7820:     }
                   7821:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7822:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 7823:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7824: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7825:         push(@linenums,$current_line);
1.497     foxr     7826: 	$current_line++;
                   7827:     }
                   7828:     if ($lines > 1) {
                   7829: 	$r->print("<hr /><br />");
                   7830:     }
1.503     raeburn  7831:     return @linenums;
1.157     albertel 7832: }
1.423     albertel 7833: 
                   7834: =pod
                   7835: 
                   7836: =item scantron_bubble_selector
                   7837:   
                   7838:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7839:    possibly showing the existing the selected bubbles if known
1.423     albertel 7840: 
                   7841:  Arguments:
                   7842:     $r           - Apache request object
                   7843:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7844:     $line        - Number of the line being displayed.
1.503     raeburn  7845:     $questionnum - Question number (may include subquestion)
                   7846:     $error       - Type of error.
1.497     foxr     7847:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7848: 
                   7849: =cut
                   7850: 
1.157     albertel 7851: sub scantron_bubble_selector {
1.503     raeburn  7852:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7853:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7854: 
                   7855:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 7856:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   7857:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7858:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7859:):             $max=$$scan_config{'BubblesPerRow'};
                   7860:):             if (($scmode eq 'number') && ($max > 10)) {
                   7861:):                 $max = 10;
                   7862:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   7863:):                 $max = 26;
                   7864:):             }
                   7865:):         } else {
                   7866:):             $max = 10;
                   7867:):         }
                   7868:):     }
1.274     albertel 7869: 
1.157     albertel 7870:     my @alphabet=('A'..'Z');
1.503     raeburn  7871:     $r->print(&Apache::loncommon::start_data_table().
                   7872:               &Apache::loncommon::start_data_table_row());
                   7873:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7874:     for (my $i=0;$i<$max+1;$i++) {
                   7875: 	$r->print("\n".'<td align="center">');
                   7876: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7877: 	else { $r->print('&nbsp;'); }
                   7878: 	$r->print('</td>');
                   7879:     }
1.503     raeburn  7880:     $r->print(&Apache::loncommon::end_data_table_row().
                   7881:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7882:     for (my $i=0;$i<$max;$i++) {
                   7883: 	$r->print("\n".
                   7884: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7885: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7886:     }
1.503     raeburn  7887:     my $nobub_checked = ' ';
                   7888:     if ($error eq 'missingbubble') {
                   7889:         $nobub_checked = ' checked = "checked" ';
                   7890:     }
                   7891:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7892: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7893:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7894:               $line.'" value="'.$questionnum.'" /></td>');
                   7895:     $r->print(&Apache::loncommon::end_data_table_row().
                   7896:               &Apache::loncommon::end_data_table());
1.157     albertel 7897: }
                   7898: 
1.423     albertel 7899: =pod
                   7900: 
                   7901: =item num_matches
                   7902: 
1.424     albertel 7903:    Counts the number of characters that are the same between the two arguments.
                   7904: 
                   7905:  Arguments:
                   7906:    $orig - CODE from the scanline
                   7907:    $code - CODE to match against
                   7908: 
                   7909:  Returns:
                   7910:    $count - integer count of the number of same characters between the
                   7911:             two arguments
                   7912: 
1.423     albertel 7913: =cut
                   7914: 
1.194     albertel 7915: sub num_matches {
                   7916:     my ($orig,$code) = @_;
                   7917:     my @code=split(//,$code);
                   7918:     my @orig=split(//,$orig);
                   7919:     my $same=0;
                   7920:     for (my $i=0;$i<scalar(@code);$i++) {
                   7921: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7922:     }
                   7923:     return $same;
                   7924: }
                   7925: 
1.423     albertel 7926: =pod
                   7927: 
                   7928: =item scantron_get_closely_matching_CODEs
                   7929: 
1.424     albertel 7930:    Cycles through all CODEs and finds the set that has the greatest
                   7931:    number of same characters as the provided CODE
                   7932: 
                   7933:  Arguments:
                   7934:    $allcodes - hash ref returned by &get_codes()
                   7935:    $CODE     - CODE from the current scanline
                   7936: 
                   7937:  Returns:
                   7938:    2 element list
                   7939:     - first elements is number of how closely matching the best fit is 
                   7940:       (5 means best set has 5 matching characters)
                   7941:     - second element is an arrary ref containing the set of valid CODEs
                   7942:       that best fit the passed in CODE
                   7943: 
1.423     albertel 7944: =cut
                   7945: 
1.194     albertel 7946: sub scantron_get_closely_matching_CODEs {
                   7947:     my ($allcodes,$CODE)=@_;
                   7948:     my @CODEs;
                   7949:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7950: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7951:     }
                   7952: 
                   7953:     return ($#CODEs,$CODEs[-1]);
                   7954: }
                   7955: 
1.423     albertel 7956: =pod
                   7957: 
                   7958: =item get_codes
                   7959: 
1.424     albertel 7960:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7961:    set of remembered CODEs.
                   7962: 
                   7963:  Arguments:
                   7964:   $old_name - name of the set of remembered CODEs
                   7965:   $cdom     - domain of the course
                   7966:   $cnum     - internal course name
                   7967: 
                   7968:  Returns:
                   7969:   %allcodes - keys are the valid CODEs, values are all 1
                   7970: 
1.423     albertel 7971: =cut
                   7972: 
1.194     albertel 7973: sub get_codes {
1.280     foxr     7974:     my ($old_name, $cdom, $cnum) = @_;
                   7975:     if (!$old_name) {
                   7976: 	$old_name=$env{'form.scantron_CODElist'};
                   7977:     }
                   7978:     if (!$cdom) {
                   7979: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7980:     }
                   7981:     if (!$cnum) {
                   7982: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7983:     }
1.278     albertel 7984:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7985: 				    $cdom,$cnum);
                   7986:     my %allcodes;
                   7987:     if ($result{"type\0$old_name"} eq 'number') {
                   7988: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7989:     } else {
                   7990: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7991:     }
1.194     albertel 7992:     return %allcodes;
                   7993: }
                   7994: 
1.423     albertel 7995: =pod
                   7996: 
                   7997: =item scantron_validate_CODE
                   7998: 
1.424     albertel 7999:    Validates all scanlines in the selected file to not have any
                   8000:    invalid or underspecified CODEs and that none of the codes are
                   8001:    duplicated if this was requested.
                   8002: 
1.423     albertel 8003: =cut
                   8004: 
1.157     albertel 8005: sub scantron_validate_CODE {
                   8006:     my ($r,$currentphase) = @_;
1.257     albertel 8007:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8008:     if ($scantron_config{'CODElocation'} &&
                   8009: 	$scantron_config{'CODEstart'} &&
                   8010: 	$scantron_config{'CODElength'}) {
1.257     albertel 8011: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8012: 	    &FIXME_blow_up()
                   8013: 	}
                   8014:     } else {
                   8015: 	return (0,$currentphase+1);
                   8016:     }
                   8017:     
                   8018:     my %usedCODEs;
                   8019: 
1.194     albertel 8020:     my %allcodes=&get_codes();
1.186     albertel 8021: 
1.582     raeburn  8022:     my $nav_error;
1.596.2.12.2.  (raeburn 8023:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8024:     if ($nav_error) {
                   8025:         $r->print(&navmap_errormsg());
                   8026:         return(1,$currentphase);
                   8027:     }
1.447     foxr     8028: 
1.186     albertel 8029:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8030:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8031: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8032: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8033: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8034: 						 $scan_data);
                   8035: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8036: 	my $error=0;
1.224     albertel 8037: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8038: 	    &scantron_get_correction($r,$i,$scan_record,
                   8039: 				     \%scantron_config,
                   8040: 				     $line,'incorrectCODE',\%allcodes);
                   8041: 	    return(1,$currentphase);
                   8042: 	}
1.221     albertel 8043: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8044: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8045: 	    &scantron_get_correction($r,$i,$scan_record,
                   8046: 				     \%scantron_config,
1.194     albertel 8047: 				     $line,'incorrectCODE',\%allcodes);
                   8048: 	    return(1,$currentphase);
1.186     albertel 8049: 	}
1.214     albertel 8050: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8051: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8052: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8053: 	    &scantron_get_correction($r,$i,$scan_record,
                   8054: 				     \%scantron_config,
1.194     albertel 8055: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8056: 	    return(1,$currentphase);
1.186     albertel 8057: 	}
1.524     raeburn  8058: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8059:     }
1.157     albertel 8060:     return (0,$currentphase+1);
                   8061: }
                   8062: 
1.423     albertel 8063: =pod
                   8064: 
                   8065: =item scantron_validate_doublebubble
                   8066: 
1.424     albertel 8067:    Validates all scanlines in the selected file to not have any
                   8068:    bubble lines with multiple bubbles marked.
                   8069: 
1.423     albertel 8070: =cut
                   8071: 
1.157     albertel 8072: sub scantron_validate_doublebubble {
                   8073:     my ($r,$currentphase) = @_;
                   8074:     #get student info
                   8075:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8076:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8077:3):     my (undef,undef,$sequence)=
                   8078:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8079: 
                   8080:     #get scantron line setup
1.257     albertel 8081:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8082:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8083:3): 
                   8084:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8085:3):     unless (ref($navmap)) {
                   8086:3):         $r->print(&navmap_errormsg());
                   8087:3):         return(1,$currentphase);
                   8088:3):     }
                   8089:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8090:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8091:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8092:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8093:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8094:3): 
1.583     raeburn  8095:     my $nav_error;
1.596.2.12.2.  6(raebur 8096:3):     if (ref($map)) {
                   8097:3):         $randomorder = $map->randomorder();
                   8098:3):         $randompick = $map->randompick();
                   8099:3):         if ($randomorder || $randompick) {
                   8100:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8101:3):             if ($nav_error) {
                   8102:3):                 $r->print(&navmap_errormsg());
                   8103:3):                 return(1,$currentphase);
                   8104:3):             }
                   8105:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8106:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8107:3):         }
                   8108:3):     } else {
                   8109:3):         $r->print(&navmap_errormsg());
                   8110:3):         return(1,$currentphase);
                   8111:3):     }
                   8112:3): 
          (raeburn 8113:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8114:     if ($nav_error) {
                   8115:         $r->print(&navmap_errormsg());
                   8116:         return(1,$currentphase);
                   8117:     }
1.447     foxr     8118: 
1.157     albertel 8119:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8120: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8121: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8122: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8123:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8124:3):                                                  $randompick,$sequence,\@master_seq,
                   8125:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8126:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8127: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8128: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8129: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8130:3): 				 $$scan_record{'scantron.doubleerror'},
                   8131:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8132:     	return (1,$currentphase);
                   8133:     }
                   8134:     return (0,$currentphase+1);
                   8135: }
                   8136: 
1.423     albertel 8137: 
1.503     raeburn  8138: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8139:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8140:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8141: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8142: 	&restore_bubble_lines();
1.257     albertel 8143: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8144:     }
1.330     albertel 8145: 
1.447     foxr     8146:     my (undef, undef, $sequence) =
1.257     albertel 8147: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8148: 
1.447     foxr     8149:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8150:     unless (ref($navmap)) {
                   8151:         if (ref($nav_error)) {
                   8152:             $$nav_error = 1;
                   8153:         }
1.591     raeburn  8154:         return;
1.582     raeburn  8155:     }
1.191     albertel 8156:     my $map=$navmap->getResourceByUrl($sequence);
                   8157:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8158:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8159: 
                   8160:     &Apache::lonxml::clear_problem_counter();
                   8161: 
1.557     raeburn  8162:     my $uname       = $env{'user.name'};
                   8163:     my $udom        = $env{'user.domain'};
1.435     foxr     8164:     my $cid         = $env{'request.course.id'};
                   8165:     my $total_lines = 0;
                   8166:     %bubble_lines_per_response = ();
1.447     foxr     8167:     %first_bubble_line         = ();
1.503     raeburn  8168:     %subdivided_bubble_lines   = ();
                   8169:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8170:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8171: 
1.447     foxr     8172:     my $response_number = 0;
                   8173:     my $bubble_line     = 0;
1.191     albertel 8174:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8175:3):         my $resid = $resource->id();
          (raeburn 8176:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8177:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8178:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8179: 	    foreach my $part_id (@{$parts}) {
                   8180:                 my $lines;
                   8181: 
                   8182: 	        # TODO - make this a persistent hash not an array.
                   8183: 
                   8184:                 # optionresponse, matchresponse and rankresponse type items 
                   8185:                 # render as separate sub-questions in exam mode.
                   8186:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8187:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8188:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8189:                     my ($numbub,$numshown);
                   8190:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8191:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8192:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8193:                         }
                   8194:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8195:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8196:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8197:                         }
                   8198:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8199:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8200:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8201:                         }
                   8202:                     }
                   8203:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8204:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8205:                     }
1.596.2.12.2.  (raeburn 8206:):                     my $bubbles_per_row =
                   8207:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8208:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8209:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8210:                         $inner_bubble_lines++;
                   8211:                     }
                   8212:                     for (my $i=0; $i<$numshown; $i++) {
                   8213:                         $subdivided_bubble_lines{$response_number} .= 
                   8214:                             $inner_bubble_lines.',';
                   8215:                     }
                   8216:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8217:                     $lines = $numshown * $inner_bubble_lines;
                   8218:                 } else {
                   8219:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8220:):                 }
1.542     raeburn  8221: 
                   8222:                 $first_bubble_line{$response_number} = $bubble_line;
                   8223: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8224:                 $responsetype_per_response{$response_number} = 
                   8225:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8226:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8227: 	        $response_number++;
                   8228: 
                   8229: 	        $bubble_line +=  $lines;
                   8230: 	        $total_lines +=  $lines;
                   8231: 	    }
                   8232:         }
                   8233:     }
1.552     raeburn  8234:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8235: 
                   8236:     &save_bubble_lines();
                   8237:     $env{'form.scantron_maxbubble'} =
                   8238: 	$total_lines;
                   8239:     return $env{'form.scantron_maxbubble'};
                   8240: }
1.523     raeburn  8241: 
1.596.2.12.2.  (raeburn 8242:): sub bubblesheet_bubbles_per_row {
                   8243:):     my ($scantron_config) = @_;
                   8244:):     my $bubbles_per_row;
                   8245:):     if (ref($scantron_config) eq 'HASH') {
                   8246:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8247:):     }
                   8248:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8249:):         $bubbles_per_row = 10;
                   8250:):     }
                   8251:):     return $bubbles_per_row;
                   8252:): }
                   8253:): 
1.157     albertel 8254: sub scantron_validate_missingbubbles {
                   8255:     my ($r,$currentphase) = @_;
                   8256:     #get student info
                   8257:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8258:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8259:3):     my (undef,undef,$sequence)=
                   8260:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8261: 
                   8262:     #get scantron line setup
1.257     albertel 8263:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8264:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8265:3): 
                   8266:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8267:3):     unless (ref($navmap)) {
                   8268:3):         $r->print(&navmap_errormsg());
                   8269:3):         return(1,$currentphase);
                   8270:3):     }
                   8271:3): 
                   8272:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8273:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8274:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8275:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8276:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8277:3): 
1.582     raeburn  8278:     my $nav_error;
1.596.2.12.2.  6(raebur 8279:3):     if (ref($map)) {
                   8280:3):         $randomorder = $map->randomorder();
                   8281:3):         $randompick = $map->randompick();
          7(raebur 8282:3):         if ($randomorder || $randompick) {
                   8283:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8284:3):             if ($nav_error) {
                   8285:3):                 $r->print(&navmap_errormsg());
                   8286:3):                 return(1,$currentphase);
                   8287:3):             }
                   8288:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8289:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8290:3):         }
          6(raebur 8291:3):     } else {
                   8292:3):         $r->print(&navmap_errormsg());
          7(raebur 8293:3):         return(1,$currentphase);
          6(raebur 8294:3):     }
                   8295:3): 
                   8296:3): 
          (raeburn 8297:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8298:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8299:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8300:         return(1,$currentphase);
                   8301:     }
1.596.2.12.2.  6(raebur 8302:3): 
1.157     albertel 8303:     if (!$max_bubble) { $max_bubble=2**31; }
                   8304:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8305: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8306: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8307:3):         my $scan_record =
                   8308:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8309:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8310:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8311:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8312: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8313: 	my @to_correct;
1.470     foxr     8314: 	
                   8315: 	# Probably here's where the error is...
                   8316: 
1.157     albertel 8317: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8318:             my $lastbubble;
                   8319:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8320:3):                 my $question = $1;
                   8321:3):                 my $subquestion = $2;
                   8322:3):                 my ($first,$responsenum);
                   8323:3):                 if ($randomorder || $randompick) {
                   8324:3):                     $responsenum = $respnumlookup{$question-1};
                   8325:3):                     $first = $startline{$question-1};
                   8326:3):                 } else {
                   8327:3):                     $responsenum = $question-1;
                   8328:3):                     $first = $first_bubble_line{$responsenum};
                   8329:3):                 }
                   8330:3):                 if (!defined($first)) { next; }
          7(raebur 8331:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8332:3):                 my $subcount = 1;
                   8333:3):                 while ($subcount<$subquestion) {
                   8334:3):                     $first += $subans[$subcount-1];
                   8335:3):                     $subcount ++;
                   8336:3):                 }
                   8337:3):                 my $count = $subans[$subquestion-1];
                   8338:3):                 $lastbubble = $first + $count;
1.505     raeburn  8339:             } else {
1.596.2.12.2.  6(raebur 8340:3):                 my ($first,$responsenum);
                   8341:3):                 if ($randomorder || $randompick) {
                   8342:3):                     $responsenum = $respnumlookup{$missing-1};
                   8343:3):                     $first = $startline{$missing-1};
                   8344:3):                 } else {
                   8345:3):                     $responsenum = $missing-1;
                   8346:3):                     $first = $first_bubble_line{$responsenum};
                   8347:3):                 }
                   8348:3):                 if (!defined($first)) { next; }
                   8349:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8350:             }
                   8351:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8352: 	    push(@to_correct,$missing);
                   8353: 	}
                   8354: 	if (@to_correct) {
                   8355: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8356:3): 				     $line,'missingbubble',\@to_correct,
                   8357:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8358:3):                                      \%startline);
1.157     albertel 8359: 	    return (1,$currentphase);
                   8360: 	}
                   8361: 
                   8362:     }
                   8363:     return (0,$currentphase+1);
                   8364: }
                   8365: 
1.596.2.12.2.  (raeburn 8366:): sub hand_bubble_option {
                   8367:):     my (undef, undef, $sequence) =
                   8368:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8369:):     return if ($sequence eq '');
                   8370:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8371:):     unless (ref($navmap)) {
                   8372:):         return;
                   8373:):     }
                   8374:):     my $needs_hand_bubbles;
                   8375:):     my $map=$navmap->getResourceByUrl($sequence);
                   8376:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8377:):     foreach my $res (@resources) {
                   8378:):         if (ref($res)) {
                   8379:):             if ($res->is_problem()) {
                   8380:):                 my $partlist = $res->parts();
                   8381:):                 foreach my $part (@{ $partlist }) {
                   8382:):                     my @types = $res->responseType($part);
                   8383:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8384:):                         $needs_hand_bubbles = 1;
                   8385:):                         last;
                   8386:):                     }
                   8387:):                 }
                   8388:):             }
                   8389:):         }
                   8390:):     }
                   8391:):     if ($needs_hand_bubbles) {
                   8392:):         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8393:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8394:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8395:):                &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 />').
                   8396:):                '<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 8397:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8398:):     }
                   8399:):     return;
                   8400:): }
1.423     albertel 8401: 
1.82      albertel 8402: sub scantron_process_students {
1.75      albertel 8403:     my ($r) = @_;
1.513     foxr     8404: 
1.257     albertel 8405:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 8406:     my ($symb)=&get_symb($r);
1.513     foxr     8407:     if (!$symb) {
                   8408: 	return '';
                   8409:     }
1.324     albertel 8410:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8411: 
1.257     albertel 8412:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.596.2.12.2.  6(raebur 8413:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8414:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8415:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8416:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8417:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8418:     unless (ref($navmap)) {
                   8419:         $r->print(&navmap_errormsg());
                   8420:         return '';
1.596.2.12.2.  6(raebur 8421:3):     }
1.83      albertel 8422:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8423:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8424:3):         %grader_randomlists_by_symb);
          1(raebur 8425:2):     if (ref($map)) {
                   8426:2):         $randomorder = $map->randomorder();
          6(raebur 8427:3):         $randompick = $map->randompick();
                   8428:3):     } else {
                   8429:3):         $r->print(&navmap_errormsg());
                   8430:3):         return '';
          1(raebur 8431:2):     }
          6(raebur 8432:3):     my $nav_error;
1.83      albertel 8433:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8434:3):     if ($randomorder || $randompick) {
                   8435:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8436:3):         if ($nav_error) {
                   8437:3):             $r->print(&navmap_errormsg());
                   8438:3):             return '';
1.586     raeburn  8439:         }
                   8440:     }
1.596.2.12.2.  6(raebur 8441:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8442:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8443: 
1.554     raeburn  8444:     my ($uname,$udom);
1.82      albertel 8445:     my $result= <<SCANTRONFORM;
1.81      albertel 8446: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8447:   <input type="hidden" name="command" value="scantron_configphase" />
                   8448:   $default_form_data
                   8449: SCANTRONFORM
1.82      albertel 8450:     $r->print($result);
                   8451: 
                   8452:     my @delayqueue;
1.542     raeburn  8453:     my (%completedstudents,%scandata);
1.140     albertel 8454:     
1.520     www      8455:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8456:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8457:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.140     albertel 8458:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8459: 					  'Processing first student');
1.542     raeburn  8460:     $r->print('<br />');
1.140     albertel 8461:     my $start=&Time::HiRes::time();
1.158     albertel 8462:     my $i=-1;
1.542     raeburn  8463:     my $started;
1.447     foxr     8464: 
1.596.2.12.2.  (raeburn 8465:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8466:     if ($nav_error) {
                   8467:         $r->print(&navmap_errormsg());
                   8468:         return '';
                   8469:     }
                   8470: 
1.513     foxr     8471:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8472:     # the user and return.
                   8473: 
                   8474:     if ($ssi_error) {
                   8475: 	$r->print("</form>");
                   8476: 	&ssi_print_error($r);
                   8477: 	$r->print(&show_grading_menu_form($symb));
1.520     www      8478:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8479: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8480:     }
1.447     foxr     8481: 
1.542     raeburn  8482:     my %lettdig = &letter_to_digits();
                   8483:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8484:3):     my %orderedforcode;
1.542     raeburn  8485: 
1.157     albertel 8486:     while ($i<$scanlines->{'count'}) {
                   8487:  	($uname,$udom)=('','');
                   8488:  	$i++;
1.200     albertel 8489:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8490:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8491: 	if ($started) {
                   8492: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8493: 						     'last student');
                   8494: 	}
                   8495: 	$started=1;
1.596.2.12.2.  6(raebur 8496:3):         my %respnumlookup = ();
                   8497:3):         my %startline = ();
                   8498:3):         my $total;
1.157     albertel 8499:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8500:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8501:3):                                                  $randompick,$sequence,\@master_seq,
                   8502:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8503:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8504:3):                                                  \$total);
1.157     albertel 8505:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8506:  					      \%idmap,$i)) {
                   8507:   	    &scantron_add_delay(\@delayqueue,$line,
                   8508:  				'Unable to find a student that matches',1);
                   8509:  	    next;
                   8510:   	}
                   8511:  	if (exists $completedstudents{$uname}) {
                   8512:  	    &scantron_add_delay(\@delayqueue,$line,
                   8513:  				'Student '.$uname.' has multiple sheets',2);
                   8514:  	    next;
                   8515:  	}
1.596.2.12.2.  1(raebur 8516:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8517:2):         my $user = $uname.':'.$usec;
1.157     albertel 8518:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8519: 
1.596.2.12.2.  1(raebur 8520:2):         my $scancode;
                   8521:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8522:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8523:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8524:2):         } else {
                   8525:2):             $scancode = '';
                   8526:2):         }
                   8527:2): 
                   8528:2):         my @mapresources = @resources;
          6(raebur 8529:3):         if ($randomorder || $randompick) {
          1(raebur 8530:2):             @mapresources =
          6(raebur 8531:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8532:3):                              \%orderedforcode);
          1(raebur 8533:2):         }
1.586     raeburn  8534:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8535:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8536:             my $ressymb;
                   8537:             if (ref($resource)) {
                   8538:                 $ressymb = $resource->symb();
                   8539:             } else {
                   8540:                 $res_error = 1;
                   8541:                 last;
                   8542:             }
1.557     raeburn  8543:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8544:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8545:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8546:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8547:):                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8548:                 $partids_by_symb{$ressymb} = $parts;
                   8549:             } else {
                   8550:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8551:             }
1.554     raeburn  8552:         }
                   8553: 
1.586     raeburn  8554:         if ($res_error) {
                   8555:             &scantron_add_delay(\@delayqueue,$line,
                   8556:                                 'An error occurred while grading student '.$uname,2);
                   8557:             next;
                   8558:         }
                   8559: 
1.330     albertel 8560: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8561:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8562: 
                   8563: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8564: 	    &scantron_putfile($scanlines,$scan_data);
                   8565: 	}
1.161     albertel 8566: 	
1.542     raeburn  8567:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8568:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8569:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8570:3):                                    \%respnumlookup,\%startline) 
                   8571:3):             eq 'ssi_error') {
1.542     raeburn  8572:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8573:             $r->print("</form>");
                   8574:             &ssi_print_error($r);
                   8575:             $r->print(&show_grading_menu_form($symb));
                   8576:             &Apache::lonnet::remove_lock($lock);
                   8577:             return '';      # Why return ''?  Beats me.
                   8578:         }
1.513     foxr     8579: 
1.596.2.12.2.  6(raebur 8580:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8581:3):             my $parmresult =
                   8582:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8583:3):                                                        '0_examcode',2,$scancode,
                   8584:3):                                                        'string_examcode',$uname,
                   8585:3):                                                        $udom);
                   8586:3):         }
1.140     albertel 8587: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8588:         if ($env{'form.verifyrecord'}) {
                   8589:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8590:3):             if ($randompick) {
                   8591:3):                 if ($total) {
                   8592:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8593:3):                 }
                   8594:3):             }
                   8595:3): 
1.542     raeburn  8596:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8597:             chomp($studentdata);
                   8598:             $studentdata =~ s/\r$//;
                   8599:             my $studentrecord = '';
                   8600:             my $counter = -1;
1.596.2.12.2.  1(raebur 8601:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8602:                 my $ressymb = $resource->symb();
1.542     raeburn  8603:                 ($counter,my $recording) =
                   8604:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8605:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8606:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8607:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8608:                 $studentrecord .= $recording;
                   8609:             }
                   8610:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8611:                 &Apache::lonxml::clear_problem_counter();
                   8612:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8613:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8614:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8615:3):                                            \%respnumlookup,\%startline)
                   8616:3):                     eq 'ssi_error') {
1.554     raeburn  8617:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8618:                     $r->print("</form>");
                   8619:                     &ssi_print_error($r);
                   8620:                     $r->print(&show_grading_menu_form($symb));
                   8621:                     &Apache::lonnet::remove_lock($lock);
                   8622:                     delete($completedstudents{$uname});
                   8623:                     return '';
                   8624:                 }
1.542     raeburn  8625:                 $counter = -1;
                   8626:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8627:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8628:                     my $ressymb = $resource->symb();
1.542     raeburn  8629:                     ($counter,my $recording) =
                   8630:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8631:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8632:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8633:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8634:3):                                                  \%startline);
1.542     raeburn  8635:                     $studentrecord .= $recording;
                   8636:                 }
                   8637:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8638:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8639:                     if ($scancode eq '') {
1.596.2.6  raeburn  8640:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8641:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8642:                     } else {
1.596.2.6  raeburn  8643:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8644:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8645:                     }
                   8646:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8647:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8648:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8649:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8650:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8651:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8652:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8653:                               &Apache::loncommon::end_data_table_row().
                   8654:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8655:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8656:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8657:                               &Apache::loncommon::end_data_table_row().
                   8658:                               &Apache::loncommon::end_data_table().'</p>');
                   8659:                 } else {
                   8660:                     $r->print('<br /><span class="LC_warning">'.
                   8661:                              &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 />'.
                   8662:                              &mt("As a consequence, this user's submission history records two tries.").
                   8663:                                  '</span><br />');
                   8664:                 }
                   8665:             }
                   8666:         }
1.543     raeburn  8667:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8668:     } continue {
1.330     albertel 8669: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8670: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8671:     }
1.140     albertel 8672:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8673:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8674: #    my $lasttime = &Time::HiRes::time()-$start;
                   8675: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8676: 
1.200     albertel 8677:     $r->print("</form>");
1.324     albertel 8678:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8679:     return '';
1.75      albertel 8680: }
1.157     albertel 8681: 
1.557     raeburn  8682: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8683:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8684:):         $bubbles_per_row) = @_;
1.557     raeburn  8685:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8686:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8687:         foreach my $resource (@{$resources}) {
                   8688:             my $ressymb = $resource->symb();
                   8689:             my ($analysis,$parts) =
                   8690:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8691:):                                           $env{'user.name'},$env{'user.domain'},
                   8692:):                                           1,$bubbles_per_row);
1.557     raeburn  8693:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8694:             if (ref($analysis) eq 'HASH') {
                   8695:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8696:                     $grader_randomlists_by_symb->{$ressymb} =
                   8697:                         $analysis->{'parts_withrandomlist'};
                   8698:                 }
                   8699:             }
                   8700:         }
                   8701:     }
                   8702:     return;
                   8703: }
                   8704: 
1.596.2.12.2.  1(raebur 8705:2): =pod
                   8706:2): 
                   8707:2): =item users_order
                   8708:2): 
                   8709:2):   Returns array of resources in current map, ordered based on either CODE,
                   8710:2):   if this is a CODEd exam, or based on student's identity if this is a
                   8711:2):   "NAMEd" exam.
                   8712:2): 
          6(raebur 8713:3):   Should be used when randomorder and/or randompick applied when the 
                   8714:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   8715:3):   for the version of the exam the student received.
          1(raebur 8716:2): 
                   8717:2): =cut
                   8718:2): 
                   8719:2): sub users_order  {
          6(raebur 8720:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 8721:2):     my @mapresources;
          6(raebur 8722:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 8723:2):         return @mapresources;
                   8724:2):     }
          6(raebur 8725:3):     if ($scancode) {
                   8726:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8727:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   8728:3):         } else {
                   8729:3):             $env{'form.CODE'} = $scancode;
                   8730:3):             my $actual_seq =
                   8731:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8732:3):                                                                $master_seq,
                   8733:3):                                                                $user,$scancode,1);
                   8734:3):             if (ref($actual_seq) eq 'ARRAY') {
                   8735:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8736:3):                 if (ref($orderedforcode) eq 'HASH') {
                   8737:3):                     if (@mapresources > 0) {
                   8738:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   8739:3):                     }
                   8740:3):                 }
                   8741:3):             }
                   8742:3):             delete($env{'form.CODE'});
          1(raebur 8743:2):         }
                   8744:2):     } else {
                   8745:2):         my $actual_seq =
                   8746:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8747:2):                                                            $master_seq,
          5(raebur 8748:3):                                                            $user,undef,1);
          1(raebur 8749:2):         if (ref($actual_seq) eq 'ARRAY') {
                   8750:2):             @mapresources =
                   8751:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8752:2):         }
          6(raebur 8753:3):     }
                   8754:3):     return @mapresources;
          1(raebur 8755:2): }
                   8756:2): 
1.542     raeburn  8757: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 8758:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8759:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8760:3):     my $uselookup = 0;
                   8761:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8762:3):         (ref($startline) eq 'HASH')) {
                   8763:3):         $uselookup = 1;
                   8764:3):     }
                   8765:3): 
1.554     raeburn  8766:     if (ref($resources) eq 'ARRAY') {
                   8767:         my $count = 0;
                   8768:         foreach my $resource (@{$resources}) {
                   8769:             my $ressymb = $resource->symb();
                   8770:             my %form = ('submitted'      => 'scantron',
                   8771:                         'grade_target'   => 'grade',
                   8772:                         'grade_username' => $uname,
                   8773:                         'grade_domain'   => $udom,
                   8774:                         'grade_courseid' => $env{'request.course.id'},
                   8775:                         'grade_symb'     => $ressymb,
                   8776:                         'CODE'           => $scancode
                   8777:                        );
1.596.2.12.2.  (raeburn 8778:):             if ($bubbles_per_row ne '') {
                   8779:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8780:):             }
                   8781:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8782:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8783:):             }
1.554     raeburn  8784:             if (ref($parts) eq 'HASH') {
                   8785:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8786:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 8787:3):                         if ($uselookup) {
                   8788:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8789:3):                         } else {
                   8790:3):                             $form{'scantron_questnum_start.'.$part} =
                   8791:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8792:3):                         }
1.554     raeburn  8793:                         $count++;
                   8794:                     }
                   8795:                 }
                   8796:             }
                   8797:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8798:             return 'ssi_error' if ($ssi_error);
                   8799:             last if (&Apache::loncommon::connection_aborted($r));
                   8800:         }
1.542     raeburn  8801:     }
                   8802:     return;
                   8803: }
                   8804: 
1.157     albertel 8805: sub scantron_upload_scantron_data {
                   8806:     my ($r)=@_;
1.565     raeburn  8807:     my $dom = $env{'request.role.domain'};
                   8808:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8809:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8810:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8811: 							  'domainid',
1.565     raeburn  8812: 							  'coursename',$dom);
                   8813:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 8814:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   8815:):     my ($symb) = &get_symb($r,1);
                   8816:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8817:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8818:     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 8819:     $r->print('
1.157     albertel 8820: <script type="text/javascript" language="javascript">
                   8821:     function checkUpload(formname) {
                   8822: 	if (formname.upfile.value == "") {
1.579     raeburn  8823: 	    alert("'.$nofile_alert.'");
1.157     albertel 8824: 	    return false;
                   8825: 	}
1.565     raeburn  8826:         if (formname.courseid.value == "") {
1.579     raeburn  8827:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8828:             return false;
                   8829:         }
1.157     albertel 8830: 	formname.submit();
                   8831:     }
1.565     raeburn  8832: 
                   8833:     function ToSyllabus() {
                   8834:         var cdom = '."'$dom'".';
                   8835:         var cnum = document.rules.courseid.value;
                   8836:         if (cdom == "" || cdom == null) {
                   8837:             return;
                   8838:         }
                   8839:         if (cnum == "" || cnum == null) {
                   8840:            return;
                   8841:         }
                   8842:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8843:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8844:         return;
                   8845:     }
                   8846: 
1.157     albertel 8847: </script>
                   8848: 
1.596.2.4  raeburn  8849: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8850: 
1.492     albertel 8851: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8852: '.$default_form_data.
                   8853:   &Apache::lonhtmlcommon::start_pick_box().
                   8854:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8855:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8856:   &Apache::lonhtmlcommon::row_closure().
                   8857:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8858:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8859:   &Apache::lonhtmlcommon::row_closure().
                   8860:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8861:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8862:   &Apache::lonhtmlcommon::row_closure().
                   8863:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8864:   '<input type="file" name="upfile" size="50" />'.
                   8865:   &Apache::lonhtmlcommon::row_closure(1).
                   8866:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8867: 
1.492     albertel 8868: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8869: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8870: </form>
1.492     albertel 8871: ');
1.157     albertel 8872:     return '';
                   8873: }
                   8874: 
1.423     albertel 8875: 
1.157     albertel 8876: sub scantron_upload_scantron_data_save {
                   8877:     my($r)=@_;
1.324     albertel 8878:     my ($symb)=&get_symb($r,1);
1.182     albertel 8879:     my $doanotherupload=
                   8880: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8881: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8882: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8883: 	'</form>'."\n";
1.257     albertel 8884:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8885: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8886: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8887: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8888: 	if ($symb) {
1.324     albertel 8889: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8890: 	} else {
                   8891: 	    $r->print($doanotherupload);
                   8892: 	}
1.162     albertel 8893: 	return '';
                   8894:     }
1.257     albertel 8895:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8896:     my $uploadedfile;
1.596.2.12.2.  5(raebur 8897:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 8898:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 8899:3):         $r->print(
                   8900:3):             &Apache::lonhtmlcommon::confirm_success(
                   8901:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8902:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8903:     } else {
1.568     raeburn  8904:         my $result = 
                   8905:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8906:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8907: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 8908:3):             $r->print(
                   8909:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8910:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8911:3):                         (length($env{'form.upfile'})-1),
                   8912:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8913:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8914:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8915:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8916: 	} else {
1.596.2.12.2.  5(raebur 8917:3):             $r->print(
                   8918:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8919:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8920:3):                           $result,
1.568     raeburn  8921: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8922: 	}
                   8923:     }
1.174     albertel 8924:     if ($symb) {
1.209     ng       8925: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8926:     } else {
1.182     albertel 8927: 	$r->print($doanotherupload);
1.174     albertel 8928:     }
1.157     albertel 8929:     return '';
                   8930: }
                   8931: 
1.567     raeburn  8932: sub validate_uploaded_scantron_file {
                   8933:     my ($cdom,$cname,$fname) = @_;
                   8934:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8935:     my @lines;
                   8936:     if ($scanlines ne '-1') {
                   8937:         @lines=split("\n",$scanlines,-1);
                   8938:     }
                   8939:     my $output;
                   8940:     if (@lines) {
                   8941:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 8942:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8943:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8944:         my %idmap = &username_to_idmap($classlist);
                   8945:         foreach my $key (keys(%idmap)) {
                   8946:             my $lckey = lc($key);
                   8947:             $idmap{$lckey} = $idmap{$key};
                   8948:         }
                   8949:         my %unique_formats;
                   8950:         my @formatlines = &get_scantronformat_file();
                   8951:         foreach my $line (@formatlines) {
                   8952:             chomp($line);
                   8953:             my @config = split(/:/,$line);
                   8954:             my $idstart = $config[5];
                   8955:             my $idlength = $config[6];
                   8956:             if (($idstart ne '') && ($idlength > 0)) {
                   8957:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8958:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8959:                 } else {
                   8960:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8961:                 }
                   8962:             }
                   8963:         }
                   8964:         foreach my $key (keys(%unique_formats)) {
                   8965:             my ($idstart,$idlength) = split(':',$key);
                   8966:             %{$counts{$key}} = (
                   8967:                                'found'   => 0,
                   8968:                                'total'   => 0,
                   8969:                               );
                   8970:             foreach my $line (@lines) {
                   8971:                 next if ($line =~ /^#/);
                   8972:                 next if ($line =~ /^[\s\cz]*$/);
                   8973:                 my $id = substr($line,$idstart-1,$idlength);
                   8974:                 $id = lc($id);
                   8975:                 if (exists($idmap{$id})) {
                   8976:                     $counts{$key}{'found'} ++;
                   8977:                 }
                   8978:                 $counts{$key}{'total'} ++;
                   8979:             }
                   8980:             if ($counts{$key}{'total'}) {
                   8981:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8982:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8983:                     $max_match_pct = $percent_match;
                   8984:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 8985:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8986:                     $max_match_count = $counts{$key}{'total'};
                   8987:                 }
                   8988:             }
                   8989:         }
                   8990:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8991:             my $format_descs;
                   8992:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8993:             for (my $i=0; $i<$numwithformat; $i++) {
                   8994:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8995:                 if ($i<$numwithformat-2) {
                   8996:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8997:                 } elsif ($i==$numwithformat-2) {
                   8998:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8999:                 } elsif ($i==$numwithformat-1) {
                   9000:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9001:                 }
                   9002:             }
                   9003:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9004:3):             $output .= '<br />';
                   9005:3):             if ($found_match_count == $max_match_count) {
                   9006:3):                 # 100% matching entries
                   9007:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9008:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9009:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9010:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9011:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9012:3):                     ' in the file (for the format defined for [_3]).',
                   9013:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9014:3):             } else {
                   9015:3):                 # Not all entries matching? -> Show warning and additional info
                   9016:3):                 $output .=
                   9017:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9018:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9019:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9020:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9021:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9022:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9023:3):                         ' in the file (for the format defined for [_3]).',
                   9024:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9025:3):                     '<p class="LC_info">'.
                   9026:3):                     &mt('A low percentage of matches results from one of the following:').
                   9027:3):                     '</p><ul>'.
                   9028:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9029:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9030:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9031:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9032:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9033:3):                     '</ul>';
                   9034:3):             }
1.567     raeburn  9035:         }
                   9036:     } else {
1.596.2.12.2.  5(raebur 9037:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9038:     }
                   9039:     return $output;
                   9040: }
                   9041: 
1.202     albertel 9042: sub valid_file {
                   9043:     my ($requested_file)=@_;
                   9044:     foreach my $filename (sort(&scantron_filenames())) {
                   9045: 	if ($requested_file eq $filename) { return 1; }
                   9046:     }
                   9047:     return 0;
                   9048: }
                   9049: 
                   9050: sub scantron_download_scantron_data {
                   9051:     my ($r)=@_;
1.596.2.12.2.  (raeburn 9052:):     my ($symb) = &get_symb($r,1);
                   9053:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9054:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9055:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9056:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9057:     if (! &valid_file($file)) {
1.492     albertel 9058: 	$r->print('
1.202     albertel 9059: 	<p>
1.596.2.12.2.  3(raebur 9060:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9061:         </p>
1.492     albertel 9062: ');
1.596.2.12.2.  (raeburn 9063:): 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 9064: 	return;
                   9065:     }
                   9066:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9067:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9068:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9069:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9070:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9071:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9072:     $r->print('
1.202     albertel 9073:     <p>
1.596.2.12.2.  8(raebur 9074:4): 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
1.492     albertel 9075: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9076:     </p>
                   9077:     <p>
1.492     albertel 9078: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9079: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9080:     </p>
                   9081:     <p>
1.492     albertel 9082: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9083: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9084:     </p>
1.492     albertel 9085: ');
1.596.2.12.2.  (raeburn 9086:):     $r->print(&show_grading_menu_form($symb));
1.202     albertel 9087:     return '';
                   9088: }
1.157     albertel 9089: 
1.523     raeburn  9090: sub checkscantron_results {
                   9091:     my ($r) = @_;
                   9092:     my ($symb)=&get_symb($r);
                   9093:     if (!$symb) {return '';}
                   9094:     my $grading_menu_button=&show_grading_menu_form($symb);
                   9095:     my $cid = $env{'request.course.id'};
1.542     raeburn  9096:     my %lettdig = &letter_to_digits();
1.523     raeburn  9097:     my $numletts = scalar(keys(%lettdig));
                   9098:     my $cnum = $env{'course.'.$cid.'.num'};
                   9099:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9100:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9101:     my %record;
                   9102:     my %scantron_config =
                   9103:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.596.2.12.2.  (raeburn 9104:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9105:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9106:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9107:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9108:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9109:     unless (ref($navmap)) {
                   9110:         $r->print(&navmap_errormsg());
                   9111:         return '';
                   9112:     }
1.523     raeburn  9113:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9114:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9115:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9116:2):     if (ref($map)) {
                   9117:2):         $randomorder=$map->randomorder();
          7(raebur 9118:3):         $randompick=$map->randompick();
          1(raebur 9119:2):     }
1.557     raeburn  9120:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9121:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9122:3):     if ($nav_error) {
                   9123:3):         $r->print(&navmap_errormsg());
                   9124:3):         return '';
          1(raebur 9125:2):     }
          (raeburn 9126:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9127:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9128:     my ($uname,$udom);
1.523     raeburn  9129:     my (%scandata,%lastname,%bylast);
                   9130:     $r->print('
                   9131: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9132: 
                   9133:     my @delayqueue;
                   9134:     my %completedstudents;
                   9135: 
1.596.2.12.2.  6(raebur 9136:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9137:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9138:3):     my ($username,$domain,$started);
          (raeburn 9139:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9140:     if ($nav_error) {
                   9141:         $r->print(&navmap_errormsg());
                   9142:         return '';
                   9143:     }
1.523     raeburn  9144: 
                   9145:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9146:                                           'Processing first student');
                   9147:     my $start=&Time::HiRes::time();
                   9148:     my $i=-1;
                   9149: 
                   9150:     while ($i<$scanlines->{'count'}) {
                   9151:         ($username,$domain,$uname)=('','','');
                   9152:         $i++;
                   9153:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9154:         if ($line=~/^[\s\cz]*$/) { next; }
                   9155:         if ($started) {
                   9156:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9157:                                                      'last student');
                   9158:         }
                   9159:         $started=1;
                   9160:         my $scan_record=
                   9161:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9162:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9163:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9164:3):                                               \%idmap,$i)) {
1.523     raeburn  9165:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9166:                                 'Unable to find a student that matches',1);
                   9167:             next;
                   9168:         }
                   9169:         if (exists $completedstudents{$uname}) {
                   9170:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9171:                                 'Student '.$uname.' has multiple sheets',2);
                   9172:             next;
                   9173:         }
                   9174:         my $pid = $scan_record->{'scantron.ID'};
                   9175:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9176:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9177:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9178:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9179:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9180:2): 
                   9181:2):         my $scancode;
                   9182:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9183:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9184:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9185:2):         } else {
                   9186:2):             $scancode = '';
                   9187:2):         }
                   9188:2): 
                   9189:2):         my @mapresources = @resources;
          6(raebur 9190:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9191:3):         my %respnumlookup=();
                   9192:3):         my %startline=();
                   9193:3):         if ($randomorder || $randompick) {
          1(raebur 9194:2):             @mapresources =
          6(raebur 9195:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9196:3):                              \%orderedforcode);
                   9197:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9198:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9199:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9200:3):                                              \%respnumlookup,\%startline);
                   9201:3):             if ($randompick && $total) {
                   9202:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9203:3):             }
          1(raebur 9204:2):         }
          6(raebur 9205:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9206:3):         chomp($scandata{$pid});
                   9207:3):         $scandata{$pid} =~ s/\r$//;
                   9208:3): 
1.523     raeburn  9209:         my $counter = -1;
1.596.2.12.2.  1(raebur 9210:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9211:             my $parts;
1.554     raeburn  9212:             my $ressymb = $resource->symb();
1.557     raeburn  9213:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9214:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9215:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9216:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9217:):                                               $username,$domain,undef,
                   9218:):                                               $bubbles_per_row);
1.557     raeburn  9219:             } else {
                   9220:                 $parts = $grader_partids_by_symb{$ressymb};
                   9221:             }
1.542     raeburn  9222:             ($counter,my $recording) =
                   9223:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9224:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9225:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9226:3):                                          $randomorder,$randompick,
                   9227:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9228:             $record{$pid} .= $recording;
1.523     raeburn  9229:         }
                   9230:     }
                   9231:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9232:     $r->print('<br />');
                   9233:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9234:     $passed = 0;
                   9235:     $failed = 0;
                   9236:     $numstudents = 0;
                   9237:     foreach my $last (sort(keys(%bylast))) {
                   9238:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9239:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9240:                 my $showscandata = $scandata{$pid};
                   9241:                 my $showrecord = $record{$pid};
                   9242:                 $showscandata =~ s/\s/&nbsp;/g;
                   9243:                 $showrecord =~ s/\s/&nbsp;/g;
                   9244:                 if ($scandata{$pid} eq $record{$pid}) {
                   9245:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9246:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9247: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9248: '</tr>'."\n".
                   9249: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9250:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9251:                     $passed ++;
                   9252:                 } else {
                   9253:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9254:                     $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  9255: '</tr>'."\n".
                   9256: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9257:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9258: '</tr>'."\n";
                   9259:                     $failed ++;
                   9260:                 }
                   9261:                 $numstudents ++;
                   9262:             }
                   9263:         }
                   9264:     }
1.596.2.4  raeburn  9265:     $r->print('<p>'.
1.596.2.8  raeburn  9266:               &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  9267:                   '<b>',
                   9268:                   $numstudents,
                   9269:                   '</b>',
                   9270:                   $env{'form.scantron_maxbubble'}).
                   9271:               '</p>'
                   9272:     );
1.596.2.12.2.  2(raebur 9273:2):     $r->print('<p>'
                   9274:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9275:2):              .'<br />'
                   9276:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9277:2):              .'</p>');
1.523     raeburn  9278:     if ($passed) {
1.572     www      9279:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9280:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9281:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9282:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9283:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9284:                  $okstudents."\n".
                   9285:                  &Apache::loncommon::end_data_table().'<br />');
                   9286:     }
                   9287:     if ($failed) {
1.572     www      9288:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9289:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9290:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9291:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9292:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9293:                  $badstudents."\n".
                   9294:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9295:                  &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  9296:     }
                   9297:     $r->print('</form><br />'.$grading_menu_button);
                   9298:     return;
                   9299: }
                   9300: 
1.542     raeburn  9301: sub verify_scantron_grading {
1.554     raeburn  9302:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9303:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9304:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9305:     my ($record,%expected,%startpos);
                   9306:     return ($counter,$record) if (!ref($resource));
                   9307:     return ($counter,$record) if (!$resource->is_problem());
                   9308:     my $symb = $resource->symb();
1.554     raeburn  9309:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9310:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9311:         $counter ++;
                   9312:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9313:3):         my $respnum = $counter;
                   9314:3):         if ($randomorder || $randompick) {
                   9315:3):             $respnum = $respnumlookup->{$counter};
                   9316:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9317:3):         } else {
                   9318:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9319:3):         }
                   9320:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9321:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9322:             foreach my $item (@sub_lines) {
                   9323:                 $expected{$part_id} += $item;
                   9324:             }
                   9325:         } else {
1.596.2.12.2.  6(raebur 9326:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9327:         }
                   9328:     }
                   9329:     if ($symb) {
                   9330:         my %recorded;
                   9331:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9332:         if ($returnhash{'version'}) {
                   9333:             my %lasthash=();
                   9334:             my $version;
                   9335:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9336:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9337:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9338:                 }
                   9339:             }
                   9340:             foreach my $key (keys(%lasthash)) {
                   9341:                 if ($key =~ /\.scantron$/) {
                   9342:                     my $value = &unescape($lasthash{$key});
                   9343:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9344:                     if ($value eq '') {
                   9345:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9346:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9347:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9348:                             }
                   9349:                         }
                   9350:                     } else {
                   9351:                         my @tocheck;
                   9352:                         my @items = split(//,$value);
                   9353:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9354:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9355:                             if (@items < $expected{$part_id}) {
                   9356:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9357:                                 my @singles = split(//,$fragment);
                   9358:                                 foreach my $pos (@singles) {
                   9359:                                     if ($pos eq ' ') {
                   9360:                                         push(@tocheck,$pos);
                   9361:                                     } else {
                   9362:                                         my $next = shift(@items);
                   9363:                                         push(@tocheck,$next);
                   9364:                                     }
                   9365:                                 }
                   9366:                             } else {
                   9367:                                 @tocheck = @items;
                   9368:                             }
                   9369:                             foreach my $letter (@tocheck) {
                   9370:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9371:                                     if ($letter !~ /^[A-J]$/) {
                   9372:                                         $letter = $scantron_config->{'Qoff'};
                   9373:                                     }
                   9374:                                     $recorded{$part_id} .= $letter;
                   9375:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9376:                                     my $digit;
                   9377:                                     if ($letter !~ /^[A-J]$/) {
                   9378:                                         $digit = $scantron_config->{'Qoff'};
                   9379:                                     } else {
                   9380:                                         $digit = $lettdig->{$letter};
                   9381:                                     }
                   9382:                                     $recorded{$part_id} .= $digit;
                   9383:                                 }
                   9384:                             }
                   9385:                         } else {
                   9386:                             @tocheck = @items;
                   9387:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9388:                                 my $curr_sub = shift(@tocheck);
                   9389:                                 my $digit;
                   9390:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9391:                                     $digit = $lettdig->{$curr_sub}-1;
                   9392:                                 }
                   9393:                                 if ($curr_sub eq 'J') {
                   9394:                                     $digit += scalar($numletts);
                   9395:                                 }
                   9396:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9397:                                     if ($j == $digit) {
                   9398:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9399:                                     } else {
                   9400:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9401:                                     }
                   9402:                                 }
                   9403:                             }
                   9404:                         }
                   9405:                     }
                   9406:                 }
                   9407:             }
                   9408:         }
1.554     raeburn  9409:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9410:             if ($recorded{$part_id} eq '') {
                   9411:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9412:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9413:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9414:                     }
                   9415:                 }
                   9416:             }
                   9417:             $record .= $recorded{$part_id};
                   9418:         }
                   9419:     }
                   9420:     return ($counter,$record);
                   9421: }
                   9422: 
1.596.2.12.2.  6(raebur 9423:3): sub letter_to_digits {
1.542     raeburn  9424:     my %lettdig = (
                   9425:                     A => 1,
                   9426:                     B => 2,
                   9427:                     C => 3,
                   9428:                     D => 4,
                   9429:                     E => 5,
                   9430:                     F => 6,
                   9431:                     G => 7,
                   9432:                     H => 8,
                   9433:                     I => 9,
                   9434:                     J => 0,
                   9435:                   );
                   9436:     return %lettdig;
                   9437: }
                   9438: 
1.423     albertel 9439: 
1.75      albertel 9440: #-------- end of section for handling grading scantron forms -------
                   9441: #
                   9442: #-------------------------------------------------------------------
                   9443: 
1.72      ng       9444: #-------------------------- Menu interface -------------------------
                   9445: #
                   9446: #--- Show a Grading Menu button - Calls the next routine ---
                   9447: sub show_grading_menu_form {
1.324     albertel 9448:     my ($symb)=@_;
1.125     ng       9449:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 9450: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 9451: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       9452: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 9453: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       9454: 	'</form>'."\n";
                   9455:     return $result;
                   9456: }
                   9457: 
1.77      ng       9458: # -- Retrieve choices for grading form
                   9459: sub savedState {
                   9460:     my %savedState = ();
1.257     albertel 9461:     if ($env{'form.saveState'}) {
                   9462: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       9463: 	    my ($key,$value) = split(/=/,$_,2);
                   9464: 	    $savedState{$key} = $value;
                   9465: 	}
                   9466:     }
                   9467:     return \%savedState;
                   9468: }
1.76      ng       9469: 
1.596.2.12.2.  (raeburn 9470:): #--- Href with symb and command ---
                   9471:): 
                   9472:): sub href_symb_cmd {
                   9473:):     my ($symb,$cmd)=@_;
                   9474:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9475:): }
                   9476:): 
1.443     banghart 9477: sub grading_menu {
                   9478:     my ($request) = @_;
                   9479:     my ($symb)=&get_symb($request);
                   9480:     if (!$symb) {return '';}
                   9481:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   9482:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   9483: 
1.444     banghart 9484:     $request->print($table);
1.443     banghart 9485:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   9486:                   'handgrade'=>$hdgrade,
                   9487:                   'probTitle'=>$probTitle,
                   9488:                   'command'=>'submit_options',
                   9489:                   'saveState'=>"",
                   9490:                   'gradingMenu'=>1,
                   9491:                   'showgrading'=>"yes");
1.538     schulted 9492:     
                   9493:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9494:     
1.443     banghart 9495:     $fields{'command'} = 'csvform';
1.538     schulted 9496:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9497:     
1.443     banghart 9498:     $fields{'command'} = 'processclicker';
1.538     schulted 9499:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9500:     
1.443     banghart 9501:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9502:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9503:     
                   9504:     my @menu = ({	categorytitle=>'Course Grading',
                   9505:             items =>[
                   9506:                         {	linktext => 'Manual Grading/View Submissions',
                   9507:                     		url => $url1,
                   9508:                     		permission => 'F',
                   9509:                     		icon => 'edit-find-replace.png',
                   9510:                     		linktitle => 'Start the process of hand grading submissions.'
                   9511:                         },
                   9512:                 	    {	linktext => 'Upload Scores',
                   9513:                     		url => $url2,
                   9514:                     		permission => 'F',
                   9515:                     		icon => 'uploadscores.png',
                   9516:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9517:                 	    },
                   9518:                 	    {	linktext => 'Process Clicker',
                   9519:                     		url => $url3,
                   9520:                     		permission => 'F',
                   9521:                     		icon => 'addClickerInfoFile.png',
                   9522:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9523:                 	    },
1.587     raeburn  9524:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9525:                     		url => $url4,
                   9526:                     		permission => 'F',
                   9527:                     		icon => 'stat.png',
1.596.2.4  raeburn  9528:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 9529:                 	    }
                   9530:                     ]
                   9531:             });
                   9532: 
                   9533:     #$fields{'command'} = 'verify';
                   9534:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 9535:     #
                   9536:     # Create the menu
                   9537:     my $Str;
1.444     banghart 9538:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 9539:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9540:     $Str .= '<input type="hidden" name="command" value="" />'.
                   9541:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   9542: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 9543: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 9544: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   9545: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   9546: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9547: 
1.538     schulted 9548:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   9549:     #$menudata->{'jscript'}
1.584     bisitz   9550:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   9551:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 9552:         ' /> '.
                   9553:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   9554:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 9555: 
1.444     banghart 9556:     $Str .="</form>\n";
1.539     riegler  9557:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 9558:     $request->print(<<GRADINGMENUJS);
                   9559: <script type="text/javascript" language="javascript">
                   9560:     function checkChoice(formname,val,cmdx) {
                   9561: 	if (val <= 2) {
                   9562: 	    var cmd = radioSelection(formname.radioChoice);
                   9563: 	    var cmdsave = cmd;
                   9564: 	} else {
                   9565: 	    cmd = cmdx;
                   9566: 	    cmdsave = 'submission';
                   9567: 	}
                   9568: 	formname.command.value = cmd;
                   9569: 	if (val < 5) formname.submit();
                   9570: 	if (val == 5) {
1.458     banghart 9571: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   9572: 	        return false;
                   9573: 	    } else {
                   9574: 	        formname.submit();
                   9575: 	    }
1.445     banghart 9576: 	}
                   9577:     }
1.443     banghart 9578: 
                   9579:     function checkReceiptNo(formname,nospace) {
                   9580: 	var receiptNo = formname.receipt.value;
                   9581: 	var checkOpt = false;
                   9582: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9583: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9584: 	if (checkOpt) {
1.539     riegler  9585: 	    alert("$receiptalert");
1.443     banghart 9586: 	    formname.receipt.value = "";
                   9587: 	    formname.receipt.focus();
                   9588: 	    return false;
                   9589: 	}
                   9590: 	return true;
                   9591:     }
                   9592: </script>
                   9593: GRADINGMENUJS
                   9594:     &commonJSfunctions($request);
                   9595:     return $Str;    
                   9596: }
                   9597: 
                   9598: 
                   9599: #--- Displays the submissions first page -------
                   9600: sub submit_options {
1.72      ng       9601:     my ($request) = @_;
1.324     albertel 9602:     my ($symb)=&get_symb($request);
1.72      ng       9603:     if (!$symb) {return '';}
1.76      ng       9604:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       9605: 
1.539     riegler  9606:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       9607:     $request->print(<<GRADINGMENUJS);
                   9608: <script type="text/javascript" language="javascript">
1.116     ng       9609:     function checkChoice(formname,val,cmdx) {
                   9610: 	if (val <= 2) {
                   9611: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       9612: 	    var cmdsave = cmd;
1.116     ng       9613: 	} else {
                   9614: 	    cmd = cmdx;
1.118     ng       9615: 	    cmdsave = 'submission';
1.116     ng       9616: 	}
                   9617: 	formname.command.value = cmd;
1.118     ng       9618: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 9619: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       9620: 	if (val < 5) formname.submit();
                   9621: 	if (val == 5) {
1.72      ng       9622: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   9623: 	    formname.submit();
                   9624: 	}
1.238     albertel 9625: 	if (val < 7) formname.submit();
1.72      ng       9626:     }
                   9627: 
                   9628:     function checkReceiptNo(formname,nospace) {
                   9629: 	var receiptNo = formname.receipt.value;
                   9630: 	var checkOpt = false;
                   9631: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9632: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9633: 	if (checkOpt) {
1.539     riegler  9634: 	    alert("$receiptalert");
1.72      ng       9635: 	    formname.receipt.value = "";
                   9636: 	    formname.receipt.focus();
                   9637: 	    return false;
                   9638: 	}
                   9639: 	return true;
                   9640:     }
                   9641: </script>
                   9642: GRADINGMENUJS
1.118     ng       9643:     &commonJSfunctions($request);
1.324     albertel 9644:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 9645:     my $result;
1.76      ng       9646:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       9647:     my $savedState = &savedState();
1.118     ng       9648:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       9649:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       9650:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       9651:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       9652: 
1.533     bisitz   9653:     # Preselect sections
                   9654:     my $selsec="";
                   9655:     if (ref($sections)) {
                   9656:         foreach my $section (sort(@$sections)) {
                   9657:             $selsec.='<option value="'.$section.'" '.
                   9658:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   9659:         }
                   9660:     }
                   9661: 
1.72      ng       9662:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 9663: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       9664: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   9665: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       9666: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       9667: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       9668: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       9669: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9670: 
1.472     albertel 9671:     $result.='
1.533     bisitz   9672: <h2>
                   9673:   '.&mt('Grade Current Resource').'
                   9674: </h2>
                   9675: <div>
                   9676:   '.$table.'
                   9677: </div>
                   9678: 
1.537     harmsja  9679: <div class="LC_columnSection">
                   9680:   
1.533     bisitz   9681:     <fieldset>
                   9682:       <legend>
                   9683:        '.&mt('Sections').'
                   9684:       </legend>
                   9685:       <select name="section" multiple="multiple" size="5">'."\n";
                   9686:     $result.= $selsec;
1.401     albertel 9687:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 9688:     $result.='
1.533     bisitz   9689:     </fieldset>
1.537     harmsja  9690:   
1.533     bisitz   9691:     <fieldset>
                   9692:       <legend>
                   9693:         '.&mt('Groups').'
                   9694:       </legend>
                   9695:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9696:     </fieldset>
1.537     harmsja  9697:   
1.533     bisitz   9698:     <fieldset>
                   9699:       <legend>
                   9700:         '.&mt('Access Status').'
                   9701:       </legend>
                   9702:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   9703:     </fieldset>
1.537     harmsja  9704:   
1.533     bisitz   9705:     <fieldset>
                   9706:       <legend>
                   9707:         '.&mt('Submission Status').'
                   9708:       </legend>
                   9709:       <select name="submitonly" size="5">
1.473     albertel 9710: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   9711: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   9712: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   9713: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   9714:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   9715:       </select>
                   9716:     </fieldset>
1.537     harmsja  9717:   
1.533     bisitz   9718: </div>
                   9719: 
                   9720: <br />
                   9721:           <div>
                   9722:             <div>
1.473     albertel 9723:               <label>
                   9724:                 <input type="radio" name="radioChoice" value="submission" '.
                   9725:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   9726:              &mt('Select individual students to grade and view submissions.').'
                   9727: 	      </label> 
                   9728:             </div>
1.533     bisitz   9729:             <div>
1.473     albertel 9730: 	      <label>
                   9731:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   9732:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   9733:                     &mt('Grade all selected students in a grading table.').'
                   9734:               </label>
                   9735:             </div>
1.533     bisitz   9736:             <div>
1.589     bisitz   9737: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9738:             </div>
1.472     albertel 9739:           </div>
1.533     bisitz   9740: 
                   9741: 
1.473     albertel 9742:         <h2>
                   9743:          '.&mt('Grade Complete Folder for One Student').'
                   9744:         </h2>
1.533     bisitz   9745:         <div>
                   9746:             <div>
1.473     albertel 9747:               <label>
                   9748:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   9749: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   9750:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   9751:               </label>
                   9752:             </div>
1.533     bisitz   9753:             <div>
1.589     bisitz   9754: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9755:             </div>
1.472     albertel 9756:         </div>
                   9757:   </form>';
1.499     albertel 9758:     $result .= &show_grading_menu_form($symb);
1.44      ng       9759:     return $result;
1.2       albertel 9760: }
                   9761: 
1.285     albertel 9762: sub reset_perm {
                   9763:     undef(%perm);
                   9764: }
                   9765: 
                   9766: sub init_perm {
                   9767:     &reset_perm();
1.300     albertel 9768:     foreach my $test_perm ('vgr','mgr','opa') {
                   9769: 
                   9770: 	my $scope = $env{'request.course.id'};
                   9771: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9772: 
                   9773: 	    $scope .= '/'.$env{'request.course.sec'};
                   9774: 	    if ( $perm{$test_perm}=
                   9775: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9776: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9777: 	    } else {
                   9778: 		delete($perm{$test_perm});
                   9779: 	    }
1.285     albertel 9780: 	}
                   9781:     }
                   9782: }
                   9783: 
1.596.2.12.2.  (raeburn 9784:): sub init_old_essays {
                   9785:):     my ($symb,$apath,$adom,$aname) = @_;
                   9786:):     if ($symb ne '') {
                   9787:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9788:):         if (keys(%essays) > 0) {
                   9789:):             $old_essays{$symb} = \%essays;
                   9790:):         }
                   9791:):     }
                   9792:):     return;
                   9793:): }
                   9794:): 
                   9795:): sub reset_old_essays {
                   9796:):     undef(%old_essays);
                   9797:): }
                   9798:): 
1.400     www      9799: sub gather_clicker_ids {
1.408     albertel 9800:     my %clicker_ids;
1.400     www      9801: 
                   9802:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9803: 
                   9804:     # Set up a couple variables.
1.407     albertel 9805:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9806:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9807:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9808: 
1.407     albertel 9809:     foreach my $student (keys(%$classlist)) {
1.438     www      9810:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9811:         my $username = $classlist->{$student}->[$username_idx];
                   9812:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9813:         my $clickers =
1.408     albertel 9814: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9815:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9816:             $id=~s/^[\#0]+//;
1.421     www      9817:             $id=~s/[\-\:]//g;
1.407     albertel 9818:             if (exists($clicker_ids{$id})) {
1.408     albertel 9819: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9820:             } else {
1.408     albertel 9821: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9822:             }
                   9823:         }
                   9824:     }
1.407     albertel 9825:     return %clicker_ids;
1.400     www      9826: }
                   9827: 
1.402     www      9828: sub gather_adv_clicker_ids {
1.408     albertel 9829:     my %clicker_ids;
1.402     www      9830:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9831:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9832:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9833:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9834:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9835:             my ($puname,$pudom)=split(/\:/,$person);
                   9836:             my $clickers =
1.408     albertel 9837: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9838:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9839: 		$id=~s/^[\#0]+//;
1.421     www      9840:                 $id=~s/[\-\:]//g;
1.408     albertel 9841: 		if (exists($clicker_ids{$id})) {
                   9842: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9843: 		} else {
                   9844: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9845: 		}
1.405     www      9846:             }
1.402     www      9847:         }
                   9848:     }
1.407     albertel 9849:     return %clicker_ids;
1.402     www      9850: }
                   9851: 
1.413     www      9852: sub clicker_grading_parameters {
                   9853:     return ('gradingmechanism' => 'scalar',
                   9854:             'upfiletype' => 'scalar',
                   9855:             'specificid' => 'scalar',
                   9856:             'pcorrect' => 'scalar',
                   9857:             'pincorrect' => 'scalar');
                   9858: }
                   9859: 
1.400     www      9860: sub process_clicker {
                   9861:     my ($r)=@_;
                   9862:     my ($symb)=&get_symb($r);
                   9863:     if (!$symb) {return '';}
                   9864:     my $result=&checkforfile_js();
                   9865:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   9866:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   9867:     $result.=$table;
                   9868:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   9869:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 9870:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   9871:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  9872:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      9873: # Attempt to restore parameters from last session, set defaults if not present
                   9874:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9875:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9876:                                                  \%Saveable_Parameters);
                   9877:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9878:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9879:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9880:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9881: 
                   9882:     my %checked;
1.521     www      9883:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9884:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9885:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9886:        }
                   9887:     }
                   9888: 
1.400     www      9889:     my $upload=&mt("Upload File");
                   9890:     my $type=&mt("Type");
1.402     www      9891:     my $attendance=&mt("Award points just for participation");
                   9892:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9893:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9894:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9895:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9896:     my $pcorrect=&mt("Percentage points for correct solution");
                   9897:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9898:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  9899:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 9900:):                                                     'interwrite' => 'interwrite PRS',
                   9901:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9902:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      9903:     $result.=<<ENDUPFORM;
1.402     www      9904: <script type="text/javascript">
                   9905: function sanitycheck() {
                   9906: // Accept only integer percentages
                   9907:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9908:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9909: // Find out grading choice
                   9910:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9911:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9912:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9913:       }
                   9914:    }
                   9915: // By default, new choice equals user selection
                   9916:    newgradingchoice=gradingchoice;
                   9917: // Not good to give more points for false answers than correct ones
                   9918:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9919:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9920:    }
                   9921: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9922:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9923:       document.forms.gradesupload.pcorrect.value=100;
                   9924:       document.forms.gradesupload.pincorrect.value=100;
                   9925:    }
                   9926: // If the values are different, cannot be attendance only
                   9927:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9928:        (gradingchoice=='attendance')) {
                   9929:        newgradingchoice='personnel';
                   9930:    }
                   9931: // Change grading choice to new one
                   9932:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9933:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9934:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9935:       } else {
                   9936:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9937:       }
                   9938:    }
                   9939: // Remember the old state
                   9940:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9941: }
                   9942: </script>
1.400     www      9943: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9944: <input type="hidden" name="symb" value="$symb" />
                   9945: <input type="hidden" name="command" value="processclickerfile" />
                   9946: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9947: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   9948: <input type="file" name="upfile" size="50" />
                   9949: <br /><label>$type: $selectform</label>
1.589     bisitz   9950: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   9951: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9952: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9953: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9954: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9955: <br />&nbsp;&nbsp;&nbsp;
                   9956: <input type="text" name="givenanswer" size="50" />
1.413     www      9957: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   9958: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   9959: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9960: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      9961: </form>
                   9962: ENDUPFORM
                   9963:     $result.='</td></tr></table>'."\n".
                   9964:              '</td></tr></table><br /><br />'."\n";
                   9965:     $result.=&show_grading_menu_form($symb);
                   9966:     return $result;
                   9967: }
                   9968: 
                   9969: sub process_clicker_file {
                   9970:     my ($r)=@_;
                   9971:     my ($symb)=&get_symb($r);
                   9972:     if (!$symb) {return '';}
1.413     www      9973: 
                   9974:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9975:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9976:                                               \%Saveable_Parameters);
                   9977: 
1.400     www      9978:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      9979:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9980: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9981: 	return $result.&show_grading_menu_form($symb);
1.404     www      9982:     }
1.522     www      9983:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9984:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9985:         return $result.&show_grading_menu_form($symb);
                   9986:     }
1.522     www      9987:     my $foundgiven=0;
1.521     www      9988:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9989:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9990:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  9991:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9992:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9993:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9994:         $foundgiven=$#answers+1;
1.521     www      9995:     }
1.407     albertel 9996:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9997:     my %correct_ids;
1.404     www      9998:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9999: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10000:     }
                   10001:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10002: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10003: 	   $correct_id=~tr/a-z/A-Z/;
                   10004: 	   $correct_id=~s/\s//gs;
                   10005: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10006:            $correct_id=~s/[\-\:]//g;
1.414     www      10007:            if ($correct_id) {
                   10008: 	      $correct_ids{$correct_id}='specified';
                   10009:            }
                   10010:         }
1.400     www      10011:     }
1.404     www      10012:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10013: 	$result.=&mt('Score based on attendance only');
1.521     www      10014:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10015:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10016:     } else {
1.408     albertel 10017: 	my $number=0;
1.411     www      10018: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10019: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10020: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10021: 	    if ($correct_ids{$id} eq 'specified') {
                   10022: 		$result.=&mt('specified');
                   10023: 	    } else {
                   10024: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10025: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10026: 	    }
                   10027: 	    $number++;
                   10028: 	}
1.411     www      10029:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10030:3):         if ($number==0) {
                   10031:3):             $result .=
                   10032:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10033:3):                      &mt('No IDs found to determine correct answer'),1);
                   10034:3):             return $result,.&show_grading_menu_form($symb);
                   10035:3):         }
1.404     www      10036:     }
1.405     www      10037:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10038:3):         $result .=
                   10039:3):             &Apache::lonhtmlcommon::confirm_success(
                   10040:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10041:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.405     www      10042:         return $result.&show_grading_menu_form($symb);
                   10043:     }
1.410     www      10044: 
                   10045: # Were able to get all the info needed, now analyze the file
                   10046: 
1.411     www      10047:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10048:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      10049:     my $heading=&mt('Scanning clicker file');
                   10050:     $result.=(<<ENDHEADER);
                   10051: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   10052: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  10053: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      10054: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10055: <input type="hidden" name="symb" value="$symb" />
                   10056: <input type="hidden" name="command" value="assignclickergrades" />
                   10057: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10058: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      10059: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10060: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10061: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10062: ENDHEADER
1.522     www      10063:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10064:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10065:     } 
1.408     albertel 10066:     my %responses;
                   10067:     my @questiontitles;
1.405     www      10068:     my $errormsg='';
                   10069:     my $number=0;
                   10070:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10071: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10072:     }
1.419     www      10073:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10074:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10075:     }
1.596.2.12.2.  (raeburn 10076:):     if ($env{'form.upfiletype'} eq 'turning') {
                   10077:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10078:):     }
1.411     www      10079:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10080:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10081:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10082:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10083:              '<br />';
1.522     www      10084:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10085:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   10086:        return $result.&show_grading_menu_form($symb);
                   10087:     } 
1.414     www      10088: # Remember Question Titles
                   10089: # FIXME: Possibly need delimiter other than ":"
                   10090:     for (my $i=0;$i<$number;$i++) {
                   10091:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10092:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10093:     }
1.411     www      10094:     my $correct_count=0;
                   10095:     my $student_count=0;
                   10096:     my $unknown_count=0;
1.414     www      10097: # Match answers with usernames
                   10098: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10099:     foreach my $id (keys(%responses)) {
1.410     www      10100:        if ($correct_ids{$id}) {
1.414     www      10101:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10102:           $correct_count++;
1.410     www      10103:        } elsif ($clicker_ids{$id}) {
1.437     www      10104:           if ($clicker_ids{$id}=~/\,/) {
                   10105: # More than one user with the same clicker!
                   10106:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   10107:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10108:                            "<select name='multi".$id."'>";
                   10109:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10110:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10111:              }
                   10112:              $result.='</select>';
                   10113:              $unknown_count++;
                   10114:           } else {
                   10115: # Good: found one and only one user with the right clicker
                   10116:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10117:              $student_count++;
                   10118:           }
1.410     www      10119:        } else {
1.411     www      10120:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   10121:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10122:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10123:                    "\n".&mt("Domain").": ".
                   10124:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  10125:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10126:           $unknown_count++;
1.410     www      10127:        }
1.405     www      10128:     }
1.412     www      10129:     $result.='<hr />'.
                   10130:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10131:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10132:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10133:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10134:        } elsif ($correct_count>1) {
1.414     www      10135:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10136:        }
                   10137:     }
1.428     www      10138:     if ($number<1) {
                   10139:        $errormsg.="Found no questions.";
                   10140:     }
1.412     www      10141:     if ($errormsg) {
                   10142:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10143:     } else {
                   10144:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10145:     }
                   10146:     $result.='</form></td></tr></table>'."\n".
1.410     www      10147:              '</td></tr></table><br /><br />'."\n";
1.404     www      10148:     return $result.&show_grading_menu_form($symb);
1.400     www      10149: }
                   10150: 
1.405     www      10151: sub iclicker_eval {
1.406     www      10152:     my ($questiontitles,$responses)=@_;
1.405     www      10153:     my $number=0;
                   10154:     my $errormsg='';
                   10155:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10156:         my %components=&Apache::loncommon::record_sep($line);
                   10157:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10158: 	if ($entries[0] eq 'Question') {
                   10159: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10160: 		$$questiontitles[$number]=$entries[$i];
                   10161: 		$number++;
                   10162: 	    }
                   10163: 	}
                   10164: 	if ($entries[0]=~/^\#/) {
                   10165: 	    my $id=$entries[0];
                   10166: 	    my @idresponses;
                   10167: 	    $id=~s/^[\#0]+//;
                   10168: 	    for (my $i=0;$i<$number;$i++) {
                   10169: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10170:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10171: 		push(@idresponses,$entries[$idx]);
                   10172: 	    }
                   10173: 	    $$responses{$id}=join(',',@idresponses);
                   10174: 	}
1.405     www      10175:     }
                   10176:     return ($errormsg,$number);
                   10177: }
                   10178: 
1.419     www      10179: sub interwrite_eval {
                   10180:     my ($questiontitles,$responses)=@_;
                   10181:     my $number=0;
                   10182:     my $errormsg='';
1.420     www      10183:     my $skipline=1;
                   10184:     my $questionnumber=0;
                   10185:     my %idresponses=();
1.419     www      10186:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10187:         my %components=&Apache::loncommon::record_sep($line);
                   10188:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10189:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10190:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10191:         next if $skipline;
                   10192:         if ($entries[0]!=$questionnumber) {
                   10193:            $questionnumber=$entries[0];
                   10194:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10195:            $number++;
1.419     www      10196:         }
1.420     www      10197:         my $id=$entries[4];
                   10198:         $id=~s/^[\#0]+//;
1.421     www      10199:         $id=~s/^v\d*\://i;
                   10200:         $id=~s/[\-\:]//g;
1.420     www      10201:         $idresponses{$id}[$number]=$entries[6];
                   10202:     }
1.524     raeburn  10203:     foreach my $id (keys(%idresponses)) {
1.420     www      10204:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10205:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10206:     }
                   10207:     return ($errormsg,$number);
                   10208: }
                   10209: 
1.596.2.12.2.  (raeburn 10210:): sub turning_eval {
                   10211:):     my ($questiontitles,$responses)=@_;
                   10212:):     my $number=0;
                   10213:):     my $errormsg='';
                   10214:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10215:):         my %components=&Apache::loncommon::record_sep($line);
                   10216:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10217:):         if ($#entries>$number) { $number=$#entries; }
                   10218:):         my $id=$entries[0];
                   10219:):         my @idresponses;
                   10220:):         $id=~s/^[\#0]+//;
                   10221:):         unless ($id) { next; }
                   10222:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10223:):             $entries[$idx]=~s/\,/\;/g;
                   10224:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10225:):             push(@idresponses,$entries[$idx]);
                   10226:):         }
                   10227:):         $$responses{$id}=join(',',@idresponses);
                   10228:):     }
                   10229:):     for (my $i=1; $i<=$number; $i++) {
                   10230:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10231:):     }
                   10232:):     return ($errormsg,$number);
                   10233:): }
                   10234:): 
1.414     www      10235: sub assign_clicker_grades {
                   10236:     my ($r)=@_;
                   10237:     my ($symb)=&get_symb($r);
                   10238:     if (!$symb) {return '';}
1.416     www      10239: # See which part we are saving to
1.582     raeburn  10240:     my $res_error;
                   10241:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10242:     if ($res_error) {
                   10243:         return &navmap_errormsg();
                   10244:     }
1.416     www      10245: # FIXME: This should probably look for the first handgradeable part
                   10246:     my $part=$$partlist[0];
                   10247: # Start screen output
1.596.2.10  raeburn  10248:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  10249: 
1.596.2.10  raeburn  10250:     $result .= '<br />'.
                   10251:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  10252:                &Apache::loncommon::start_data_table_header_row().
                   10253:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10254:                &Apache::loncommon::end_data_table_header_row().
                   10255:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      10256: 
1.414     www      10257: # Get correct result
                   10258: # FIXME: Possibly need delimiter other than ":"
                   10259:     my @correct=();
1.415     www      10260:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10261:     my $number=$env{'form.number'};
                   10262:     if ($gradingmechanism ne 'attendance') {
1.414     www      10263:        foreach my $key (keys(%env)) {
                   10264:           if ($key=~/^form\.correct\:/) {
                   10265:              my @input=split(/\,/,$env{$key});
                   10266:              for (my $i=0;$i<=$#input;$i++) {
                   10267:                  if (($correct[$i]) && ($input[$i]) &&
                   10268:                      ($correct[$i] ne $input[$i])) {
                   10269:                     $result.='<br /><span class="LC_warning">'.
                   10270:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10271:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10272:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10273:                     $correct[$i]=$input[$i];
                   10274:                  }
                   10275:              }
                   10276:           }
                   10277:        }
1.415     www      10278:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10279:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10280:              $result.='<br /><span class="LC_error">'.
                   10281:                       &mt('No correct result given for question "[_1]"!',
                   10282:                           $env{'form.question:'.$i}).'</span>';
                   10283:           }
                   10284:        }
1.596.2.4  raeburn  10285:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10286:     }
                   10287: # Start grading
1.415     www      10288:     my $pcorrect=$env{'form.pcorrect'};
                   10289:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10290:     my $storecount=0;
1.596.2.4  raeburn  10291:     my %users=();
1.415     www      10292:     foreach my $key (keys(%env)) {
1.420     www      10293:        my $user='';
1.415     www      10294:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10295:           $user=$1;
                   10296:        }
                   10297:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10298:           my $id=$1;
                   10299:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10300:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10301:           } elsif ($env{'form.multi'.$id}) {
                   10302:              $user=$env{'form.multi'.$id};
1.420     www      10303:           }
                   10304:        }
1.596.2.4  raeburn  10305:        if ($user) {
                   10306:           if ($users{$user}) {
                   10307:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10308:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10309:                       '</span><br />';
                   10310:           }
                   10311:           $users{$user}=1;
1.415     www      10312:           my @answer=split(/\,/,$env{$key});
                   10313:           my $sum=0;
1.522     www      10314:           my $realnumber=$number;
1.415     www      10315:           for (my $i=0;$i<$number;$i++) {
1.576     www      10316:              if  ($correct[$i] eq '-') {
                   10317:                 $realnumber--;
                   10318:              } elsif ($answer[$i]) {
1.415     www      10319:                 if ($gradingmechanism eq 'attendance') {
                   10320:                    $sum+=$pcorrect;
1.576     www      10321:                 } elsif ($correct[$i] eq '*') {
1.522     www      10322:                    $sum+=$pcorrect;
1.415     www      10323:                 } else {
1.596.2.4  raeburn  10324: # We actually grade if correct or not
                   10325:                    my $increment=$pincorrect;
                   10326: # Special case: numerical answer "0"
                   10327:                    if ($correct[$i] eq '0') {
                   10328:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10329:                          $increment=$pcorrect;
                   10330:                       }
                   10331: # General numerical answer, both evaluate to something non-zero
                   10332:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10333:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10334:                          $increment=$pcorrect;
                   10335:                       }
                   10336: # Must be just alphanumeric
                   10337:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10338:                       $increment=$pcorrect;
1.415     www      10339:                    }
1.596.2.4  raeburn  10340:                    $sum+=$increment;
1.415     www      10341:                 }
                   10342:              }
                   10343:           }
1.522     www      10344:           my $ave=$sum/(100*$realnumber);
1.416     www      10345: # Store
                   10346:           my ($username,$domain)=split(/\:/,$user);
                   10347:           my %grades=();
                   10348:           $grades{"resource.$part.solved"}='correct_by_override';
                   10349:           $grades{"resource.$part.awarded"}=$ave;
                   10350:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10351:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10352:                                                  $env{'request.course.id'},
                   10353:                                                  $domain,$username);
                   10354:           if ($returncode ne 'ok') {
                   10355:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10356:           } else {
                   10357:              $storecount++;
                   10358:           }
1.415     www      10359:        }
                   10360:     }
                   10361: # We are done
1.549     hauer    10362:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10363:              '</td>'.
                   10364:              &Apache::loncommon::end_data_table_row().
                   10365:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      10366:     return $result.&show_grading_menu_form($symb);
                   10367: }
                   10368: 
1.582     raeburn  10369: sub navmap_errormsg {
                   10370:     return '<div class="LC_error">'.
                   10371:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10372:            &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  10373:            '</div>';
                   10374: }
                   10375: 
1.596.2.12.2.  (raeburn 10376:): sub startpage {
                   10377:):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10378:):     if ($nomenu) {
                   10379:):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10380:):     } else {
                   10381:):         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10382:):                                                  {'bread_crumbs' => $crumbs}));
                   10383:):     }
                   10384:):     unless ($nodisplayflag) {
                   10385:):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
                   10386:):     }
                   10387:): }
                   10388:): 
1.1       albertel 10389: sub handler {
1.41      ng       10390:     my $request=$_[0];
1.434     albertel 10391:     &reset_caches();
1.596.2.4  raeburn  10392:     if ($request->header_only) {
                   10393:         &Apache::loncommon::content_type($request,'text/html');
                   10394:         $request->send_http_header;
                   10395:         return OK;
1.41      ng       10396:     }
                   10397:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10398: 
1.324     albertel 10399:     my $symb=&get_symb($request,1);
1.160     albertel 10400:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10401:     my $command=$commands[0];
1.447     foxr     10402: 
1.160     albertel 10403:     if ($#commands > 0) {
                   10404: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10405:     }
1.447     foxr     10406: 
1.513     foxr     10407:     $ssi_error = 0;
1.535     raeburn  10408:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  10409:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.12.2.  (raeburn 10410:):                                                     {'bread_crumbs' => $brcrum});
1.324     albertel 10411:     if ($symb eq '' && $command eq '') {
1.257     albertel 10412: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  10413:             &Apache::loncommon::content_type($request,'text/html');
                   10414:             $request->send_http_header;
                   10415:             $request->print($start_page);
1.257     albertel 10416: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   10417: 		($env{'form.codethree'})) {
                   10418: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   10419: 		    $env{'form.codethree'};
1.41      ng       10420: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   10421: 		    &Apache::lonnet::checkin($token);
                   10422: 		if ($tsymb) {
1.137     albertel 10423: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       10424: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     10425: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 10426: 					  ('grade_username' => $tuname,
                   10427: 					   'grade_domain' => $tudom,
                   10428: 					   'grade_courseid' => $tcrsid,
                   10429: 					   'grade_symb' => $tsymb)));
1.41      ng       10430: 		    } else {
1.45      ng       10431: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 10432: 		    }
1.41      ng       10433: 		} else {
1.45      ng       10434: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       10435: 		}
1.14      www      10436: 	    } else {
1.41      ng       10437: 		$request->print(&Apache::lonxml::tokeninputfield());
                   10438: 	    }
1.596.2.4  raeburn  10439:         } elsif ($env{'request.course.id'}) {
                   10440:             &init_perm(); 
                   10441:             if (!%perm) {
                   10442:                 $request->internal_redirect('/adm/quickgrades');
1.596.2.12.2.  3(raebur 10443:3):                 return OK;
1.596.2.4  raeburn  10444:             } else {
                   10445:                 &Apache::loncommon::content_type($request,'text/html');
                   10446:                 $request->send_http_header;
                   10447:                 $request->print($start_page);
                   10448:             }
                   10449:         }
1.41      ng       10450:     } else {
1.596.2.4  raeburn  10451:         &init_perm();
                   10452:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  10453:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10454:                     ($command =~ /^scantronupload/)) {
                   10455:                 # Not in a course.
                   10456:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10457:                 return HTTP_NOT_ACCEPTABLE;
                   10458:             }
1.596.2.4  raeburn  10459:         } elsif (!%perm) {
                   10460:             $request->internal_redirect('/adm/quickgrades');
                   10461:         }
                   10462:         &Apache::loncommon::content_type($request,'text/html');
                   10463:         $request->send_http_header;
1.596.2.12.2.  (raeburn 10464:):         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
                   10465:):             $request->print($start_page); 
                   10466:):         }
1.104     albertel 10467: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.596.2.12.2.  (raeburn 10468:):             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10469:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10470:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10471:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10472:):                                               $env{'form.userdom'});
                   10473:):             }
                   10474:):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10475:):             if ($versionform) {
                   10476:):                 $request->print($versionform);
                   10477:):             }
                   10478:):             $request->print('<br clear="all" />');
1.257     albertel 10479: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.596.2.12.2.  (raeburn 10480:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10481:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10482:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10483:):                                           $env{'form.userdom'},
                   10484:):                                           $env{'form.inhibitmenu'});
                   10485:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10486:):             if ($versionform) {
                   10487:):                 $request->print($versionform);
                   10488:):             }
                   10489:):             $request->print('<br clear="all" />');
                   10490:):             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10491: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       10492: 	    &pickStudentPage($request);
1.103     albertel 10493: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       10494: 	    &displayPage($request);
1.104     albertel 10495: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       10496: 	    &updateGradeByPage($request);
1.104     albertel 10497: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       10498: 	    &processGroup($request);
1.104     albertel 10499: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 10500: 	    $request->print(&grading_menu($request));
                   10501: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   10502: 	    $request->print(&submit_options($request));
1.104     albertel 10503: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       10504: 	    $request->print(&viewgrades($request));
1.104     albertel 10505: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       10506: 	    $request->print(&processHandGrade($request));
1.106     albertel 10507: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       10508: 	    $request->print(&editgrades($request));
1.106     albertel 10509: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       10510: 	    $request->print(&verifyreceipt($request));
1.400     www      10511:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   10512:             $request->print(&process_clicker($request));
                   10513:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   10514:             $request->print(&process_clicker_file($request));
1.414     www      10515:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   10516:             $request->print(&assign_clicker_grades($request));
1.106     albertel 10517: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       10518: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 10519: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       10520: 	    $request->print(&csvupload($request));
1.106     albertel 10521: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       10522: 	    $request->print(&csvuploadmap($request));
1.246     albertel 10523: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10524: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 10525: 		$request->print(&csvuploadoptions($request));
1.41      ng       10526: 	    } else {
1.257     albertel 10527: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10528: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10529: 		} else {
1.257     albertel 10530: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10531: 		}
                   10532: 		$request->print(&csvuploadmap($request));
                   10533: 	    }
1.246     albertel 10534: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10535: 	    $request->print(&csvuploadassign($request));
1.106     albertel 10536: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 10537: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 10538:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10539:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 10540: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   10541: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 10542: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 10543: 	    $request->print(&scantron_process_students($request));
1.157     albertel 10544:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10545:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10546: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 10547:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 10548:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10549:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10550: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 10551:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 10552:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10553: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 10554:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  10555:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   10556:             $request->print(&checkscantron_results($request));     
1.106     albertel 10557: 	} elsif ($command) {
1.562     bisitz   10558: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10559: 	}
1.2       albertel 10560:     }
1.513     foxr     10561:     if ($ssi_error) {
                   10562: 	&ssi_print_error($request);
                   10563:     }
1.353     albertel 10564:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 10565:     &reset_caches();
1.596.2.4  raeburn  10566:     return OK;
1.44      ng       10567: }
                   10568: 
1.1       albertel 10569: 1;
                   10570: 
1.13      albertel 10571: __END__;
1.531     jms      10572: 
                   10573: 
                   10574: =head1 NAME
                   10575: 
                   10576: Apache::grades
                   10577: 
                   10578: =head1 SYNOPSIS
                   10579: 
                   10580: Handles the viewing of grades.
                   10581: 
                   10582: This is part of the LearningOnline Network with CAPA project
                   10583: described at http://www.lon-capa.org.
                   10584: 
                   10585: =head1 OVERVIEW
                   10586: 
                   10587: Do an ssi with retries:
                   10588: While I'd love to factor out this with the vesrion in lonprintout,
                   10589: 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
                   10590: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10591: 
                   10592: At least the logic that drives this has been pulled out into loncommon.
                   10593: 
                   10594: 
                   10595: 
                   10596: ssi_with_retries - Does the server side include of a resource.
                   10597:                      if the ssi call returns an error we'll retry it up to
                   10598:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 10599:4):                      If we still have a problem, no text is appended to the
1.531     jms      10600:                      output and we set some global variables.
                   10601:                      to indicate to the caller an SSI error occurred.  
                   10602:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 10603:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      10604:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10605:                      by informing the user that this happened.
                   10606: 
                   10607: Parameters:
                   10608:   resource   - The resource to include.  This is passed directly, without
                   10609:                interpretation to lonnet::ssi.
                   10610:   form       - The form hash parameters that guide the interpretation of the resource
                   10611:                
                   10612:   retries    - Number of retries allowed before giving up completely.
                   10613: Returns:
                   10614:   On success, returns the rendered resource identified by the resource parameter.
                   10615: Side Effects:
                   10616:   The following global variables can be set:
                   10617:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10618:                               It is up to the caller to initialize this to false
                   10619:                               if desired.
                   10620:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10621:                               of the resource that could not be rendered by the ssi
                   10622:                               call.
                   10623:    ssi_error_message   - The error string fetched from the ssi response
                   10624:                               in the event of an error.
                   10625: 
                   10626: 
                   10627: =head1 HANDLER SUBROUTINE
                   10628: 
                   10629: ssi_with_retries()
                   10630: 
                   10631: =head1 SUBROUTINES
                   10632: 
                   10633: =over
                   10634: 
                   10635: =item scantron_get_correction() : 
                   10636: 
                   10637:    Builds the interface screen to interact with the operator to fix a
                   10638:    specific error condition in a specific scanline
                   10639: 
                   10640:  Arguments:
                   10641:     $r           - Apache request object
                   10642:     $i           - number of the current scanline
                   10643:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10644:     $scan_config - hash ref as returned from &get_scantron_config()
                   10645:     $line        - full contents of the current scanline
                   10646:     $error       - error condition, valid values are
                   10647:                    'incorrectCODE', 'duplicateCODE',
                   10648:                    'doublebubble', 'missingbubble',
                   10649:                    'duplicateID', 'incorrectID'
                   10650:     $arg         - extra information needed
                   10651:        For errors:
                   10652:          - duplicateID   - paper number that this studentID was seen before on
                   10653:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10654:                            seen on before
                   10655:          - incorrectCODE - current incorrect CODE 
                   10656:          - doublebubble  - array ref of the bubble lines that have double
                   10657:                            bubble errors
                   10658:          - missingbubble - array ref of the bubble lines that have missing
                   10659:                            bubble errors
                   10660: 
1.596.2.12.2.  6(raebur 10661:3):    $randomorder - True if exam folder has randomorder set
                   10662:3):    $randompick  - True if exam folder has randompick set
                   10663:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10664:3):                      for current line to question number used for same question
                   10665:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   10666:3):    $startline   - Reference to hash where key is question number (0 is first)
                   10667:3):                   and value is number of first bubble line for current student
                   10668:3):                   or code-based randompick and/or randomorder.
                   10669:3): 
                   10670:3): 
1.531     jms      10671: =item  scantron_get_maxbubble() : 
                   10672: 
1.582     raeburn  10673:    Arguments:
                   10674:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10675:                       failure to retrieve a navmap object.
                   10676:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10677:        calling routine should trap the error condition and display the warning
                   10678:        found in &navmap_errormsg().
                   10679: 
1.596.2.12.2.  (raeburn 10680:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   10681:): 
1.531     jms      10682:    Returns the maximum number of bubble lines that are expected to
                   10683:    occur. Does this by walking the selected sequence rendering the
                   10684:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10685:    for what the current value of the problem counter is.
                   10686: 
                   10687:    Caches the results to $env{'form.scantron_maxbubble'},
                   10688:    $env{'form.scantron.bubble_lines.n'}, 
                   10689:    $env{'form.scantron.first_bubble_line.n'} and
                   10690:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 10691:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      10692:    lines for response n and number of the first bubble line for response n,
                   10693:    and a comma separated list of numbers of bubble lines for sub-questions
                   10694:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10695: 
                   10696: 
                   10697: =item  scantron_validate_missingbubbles() : 
                   10698: 
                   10699:    Validates all scanlines in the selected file to not have any
                   10700:     answers that don't have bubbles that have not been verified
                   10701:     to be bubble free.
                   10702: 
                   10703: =item  scantron_process_students() : 
                   10704: 
1.596.2.6  raeburn  10705:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10706: 
                   10707:    The parsed scanline hash is added to %env 
                   10708: 
                   10709:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10710:    foreach resource , with the form data of
                   10711: 
                   10712: 	'submitted'     =>'scantron' 
                   10713: 	'grade_target'  =>'grade',
                   10714: 	'grade_username'=> username of student
                   10715: 	'grade_domain'  => domain of student
                   10716: 	'grade_courseid'=> of course
                   10717: 	'grade_symb'    => symb of resource to grade
                   10718: 
                   10719:     This triggers a grading pass. The problem grading code takes care
                   10720:     of converting the bubbled letter information (now in %env) into a
                   10721:     valid submission.
                   10722: 
                   10723: =item  scantron_upload_scantron_data() :
                   10724: 
1.596.2.6  raeburn  10725:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10726: 
                   10727: =item  scantron_upload_scantron_data_save() : 
                   10728: 
                   10729:    Adds a provided bubble information data file to the course if user
                   10730:    has the correct privileges to do so. 
                   10731: 
                   10732: =item  valid_file() :
                   10733: 
                   10734:    Validates that the requested bubble data file exists in the course.
                   10735: 
                   10736: =item  scantron_download_scantron_data() : 
                   10737: 
                   10738:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  10739:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10740:    course.
                   10741: 
                   10742: =item  scantron_validate_ID() : 
                   10743: 
                   10744:    Validates all scanlines in the selected file to not have any
1.556     weissno  10745:    invalid or underspecified student/employee IDs
1.531     jms      10746: 
1.582     raeburn  10747: =item navmap_errormsg() :
                   10748: 
                   10749:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   10750:    Should be called whenever the request to instantiate a navmap object fails.  
                   10751: 
1.531     jms      10752: =back
                   10753: 
                   10754: =cut

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