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

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.  1.2.4(ra    4:eb-19): # $Id: grades.pm,v 1.596.2.12.2.41.2.3 2019/02/03 20:47:11 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.  1(raebur  357:7):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
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.  1(raebur  365:7):             if ($scancode) {
                    366:7):                 if (ref($add_to_form) eq 'HASH') {
                    367:7):                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    368:7):                 } else {
                    369:7):                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    370:7):                 }
                    371:7):             }
          (raeburn  372:):             my $analyze =
                    373:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    374:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   375:             if (ref($analyze) eq 'HASH') {
                    376:                 %analysis = %{$analyze};
                    377:             }
                    378:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    379:                 foreach my $part (@{$analysis{'parts'}}) {
                    380:                     my ($id,$respid) = split(/\./,$part);
                    381:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    382:                         push(@parts,$part);
                    383:                     }
                    384:                 }
                    385:             }
                    386:         }
                    387:         return (\%analysis,\@parts);
                    388:     }
                    389: 
1.148     albertel  390: }
1.434     albertel  391: 
1.118     ng        392: #--- Clean response type for display
1.335     albertel  393: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    394: #        response types only.
1.118     ng        395: sub cleanRecord {
1.336     albertel  396:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   397: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  398:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  399:     if ($response =~ /^(option|rank)$/) {
                    400: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  401:4):         my @answer = %answer;
                    402:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  403: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    404: 	my ($toprow,$bottomrow);
                    405: 	foreach my $foil (@$order) {
                    406: 	    if ($grading{$foil} == 1) {
                    407: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    408: 	    } else {
                    409: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    410: 	    }
1.398     albertel  411: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  412: 	}
                    413: 	return '<blockquote><table border="1">'.
1.466     albertel  414: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    415: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   416: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  417:     } elsif ($response eq 'match') {
                    418: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  419:4):         my @answer = %answer;
                    420:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  421: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    422: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    423: 	my ($toprow,$middlerow,$bottomrow);
                    424: 	foreach my $foil (@$order) {
                    425: 	    my $item=shift(@items);
                    426: 	    if ($grading{$foil} == 1) {
                    427: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  428: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  429: 	    } else {
                    430: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  431: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  432: 	    }
1.398     albertel  433: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        434: 	}
1.126     ng        435: 	return '<blockquote><table border="1">'.
1.466     albertel  436: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    437: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  438: 	    $middlerow.'</tr>'.
1.466     albertel  439: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   440: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  441:     } elsif ($response eq 'radiobutton') {
                    442: 	my %answer=&Apache::lonnet::str2hash($answer);
                    443: 	my ($toprow,$bottomrow);
1.434     albertel  444: 	my $correct = 
1.596.2.2  raeburn   445: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  446: 	foreach my $foil (@$order) {
1.148     albertel  447: 	    if (exists($answer{$foil})) {
1.434     albertel  448: 		if ($foil eq $correct) {
1.466     albertel  449: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  450: 		} else {
1.466     albertel  451: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  452: 		}
                    453: 	    } else {
1.466     albertel  454: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  455: 	    }
1.398     albertel  456: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  457: 	}
                    458: 	return '<blockquote><table border="1">'.
1.466     albertel  459: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    460: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   461: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  462:     } elsif ($response eq 'essay') {
1.257     albertel  463: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        464: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  465: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    466: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        467: 
1.257     albertel  468: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    469: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    470: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    471: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    472: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    473: 	    $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        474: 	}
1.596.2.12.2.  2(raebur  475:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  476:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  477:4):         my $result=&mt('Smile representation: [_1]',
                    478:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  479: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    480: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    481: 	return $result;
1.335     albertel  482:     } elsif ( $response eq 'Task') {
                    483: 	if ( $answer eq 'SUBMITTED') {
                    484: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  485: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  486: 	    return $result;
                    487: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    488: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    489: 			       keys(%{$record}));
                    490: 	    return join('<br />',($version,@matches));
                    491: 			       
                    492: 			       
                    493: 	} else {
                    494: 	    my $result =
                    495: 		'<p>'
                    496: 		.&mt('Overall result: [_1]',
                    497: 		     $record->{$version."resource.$respid.$partid.status"})
                    498: 		.'</p>';
                    499: 	    
                    500: 	    $result .= '<ul>';
                    501: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    502: 			     keys(%{$record}));
                    503: 	    foreach my $grade (sort(@grade)) {
                    504: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    505: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    506: 				     $dim, $record->{$grade}).
                    507: 			  '</li>';
                    508: 	    }
                    509: 	    $result.='</ul>';
                    510: 	    return $result;
                    511: 	}
1.596.2.12.2.  8(raebur  512:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    513:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  514: 	$answer = 
                    515: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    516: 							      $answer);
1.596.2.12.2.  8(raebur  517:4):         return $answer;
1.122     ng        518:     }
1.596.2.12.2.  8(raebur  519:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        520: }
                    521: 
                    522: #-- A couple of common js functions
                    523: sub commonJSfunctions {
                    524:     my $request = shift;
                    525:     $request->print(<<COMMONJSFUNCTIONS);
                    526: <script type="text/javascript" language="javascript">
                    527:     function radioSelection(radioButton) {
                    528: 	var selection=null;
                    529: 	if (radioButton.length > 1) {
                    530: 	    for (var i=0; i<radioButton.length; i++) {
                    531: 		if (radioButton[i].checked) {
                    532: 		    return radioButton[i].value;
                    533: 		}
                    534: 	    }
                    535: 	} else {
                    536: 	    if (radioButton.checked) return radioButton.value;
                    537: 	}
                    538: 	return selection;
                    539:     }
                    540: 
                    541:     function pullDownSelection(selectOne) {
                    542: 	var selection="";
                    543: 	if (selectOne.length > 1) {
                    544: 	    for (var i=0; i<selectOne.length; i++) {
                    545: 		if (selectOne[i].selected) {
                    546: 		    return selectOne[i].value;
                    547: 		}
                    548: 	    }
                    549: 	} else {
1.138     albertel  550:             // only one value it must be the selected one
                    551: 	    return selectOne.value;
1.118     ng        552: 	}
                    553:     }
                    554: </script>
                    555: COMMONJSFUNCTIONS
                    556: }
                    557: 
1.44      ng        558: #--- Dumps the class list with usernames,list of sections,
                    559: #--- section, ids and fullnames for each user.
                    560: sub getclasslist {
1.449     banghart  561:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  562:     my @getsec;
1.450     banghart  563:     my @getgroup;
1.442     banghart  564:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  565:     if (!ref($getsec)) {
                    566: 	if ($getsec ne '' && $getsec ne 'all') {
                    567: 	    @getsec=($getsec);
                    568: 	}
                    569:     } else {
                    570: 	@getsec=@{$getsec};
                    571:     }
                    572:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  573:     if (!ref($getgroup)) {
                    574: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    575: 	    @getgroup=($getgroup);
                    576: 	}
                    577:     } else {
                    578: 	@getgroup=@{$getgroup};
                    579:     }
                    580:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  581: 
1.449     banghart  582:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  583:     # Bail out if we were unable to get the classlist
1.56      matthew   584:     return if (! defined($classlist));
1.449     banghart  585:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   586:     #
                    587:     my %sections;
                    588:     my %fullnames;
1.205     matthew   589:     foreach my $student (keys(%$classlist)) {
                    590:         my $end      = 
                    591:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    592:         my $start    = 
                    593:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    594:         my $id       = 
                    595:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    596:         my $section  = 
                    597:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    598:         my $fullname = 
                    599:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    600:         my $status   = 
                    601:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  602:         my $group   = 
                    603:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        604: 	# filter students according to status selected
1.442     banghart  605: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    606: 	    if (!($stu_status =~ $status)) {
1.450     banghart  607: 		delete($classlist->{$student});
1.76      ng        608: 		next;
                    609: 	    }
                    610: 	}
1.450     banghart  611: 	# filter students according to groups selected
1.453     banghart  612: 	my @stu_groups = split(/,/,$group);
1.450     banghart  613: 	if (@getgroup) {
                    614: 	    my $exclude = 1;
1.454     banghart  615: 	    foreach my $grp (@getgroup) {
                    616: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  617: 	            if ($stu_group eq $grp) {
                    618: 	                $exclude = 0;
                    619:     	            } 
1.450     banghart  620: 	        }
1.453     banghart  621:     	        if (($grp eq 'none') && !$group) {
                    622:         	        $exclude = 0;
                    623:         	}
1.450     banghart  624: 	    }
                    625: 	    if ($exclude) {
                    626: 	        delete($classlist->{$student});
                    627: 	    }
                    628: 	}
1.205     matthew   629: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  630: 	if (&canview($section)) {
1.291     albertel  631: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  632: 		$sections{$section}++;
1.450     banghart  633: 		if ($classlist->{$student}) {
                    634: 		    $fullnames{$student}=$fullname;
                    635: 		}
1.103     albertel  636: 	    } else {
1.205     matthew   637: 		delete($classlist->{$student});
1.103     albertel  638: 	    }
                    639: 	} else {
1.205     matthew   640: 	    delete($classlist->{$student});
1.103     albertel  641: 	}
1.44      ng        642:     }
                    643:     my %seen = ();
1.56      matthew   644:     my @sections = sort(keys(%sections));
                    645:     return ($classlist,\@sections,\%fullnames);
1.44      ng        646: }
                    647: 
1.103     albertel  648: sub canmodify {
                    649:     my ($sec)=@_;
                    650:     if ($perm{'mgr'}) {
                    651: 	if (!defined($perm{'mgr_section'})) {
                    652: 	    # can modify whole class
                    653: 	    return 1;
                    654: 	} else {
                    655: 	    if ($sec eq $perm{'mgr_section'}) {
                    656: 		#can modify the requested section
                    657: 		return 1;
                    658: 	    } else {
                    659: 		# can't modify the request section
                    660: 		return 0;
                    661: 	    }
                    662: 	}
                    663:     }
                    664:     #can't modify
                    665:     return 0;
                    666: }
                    667: 
                    668: sub canview {
                    669:     my ($sec)=@_;
                    670:     if ($perm{'vgr'}) {
                    671: 	if (!defined($perm{'vgr_section'})) {
                    672: 	    # can modify whole class
                    673: 	    return 1;
                    674: 	} else {
                    675: 	    if ($sec eq $perm{'vgr_section'}) {
                    676: 		#can modify the requested section
                    677: 		return 1;
                    678: 	    } else {
                    679: 		# can't modify the request section
                    680: 		return 0;
                    681: 	    }
                    682: 	}
                    683:     }
                    684:     #can't modify
                    685:     return 0;
                    686: }
                    687: 
1.44      ng        688: #--- Retrieve the grade status of a student for all the parts
                    689: sub student_gradeStatus {
1.324     albertel  690:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  691:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        692:     my %partstatus = ();
                    693:     foreach (@$partlist) {
1.128     ng        694: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        695: 	$status              = 'nothing' if ($status eq '');
                    696: 	$partstatus{$_}      = $status;
                    697: 	my $subkey           = "resource.$_.submitted_by";
                    698: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    699:     }
                    700:     return %partstatus;
                    701: }
                    702: 
1.45      ng        703: # hidden form and javascript that calls the form
                    704: # Use by verifyscript and viewgrades
                    705: # Shows a student's view of problem and submission
                    706: sub jscriptNform {
1.324     albertel  707:     my ($symb) = @_;
1.442     banghart  708:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        709:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    710: 	'    function viewOneStudent(user,domain) {'."\n".
                    711: 	'	document.onestudent.student.value = user;'."\n".
                    712: 	'	document.onestudent.userdom.value = domain;'."\n".
                    713: 	'	document.onestudent.submit();'."\n".
                    714: 	'    }'."\n".
                    715: 	'</script>'."\n";
                    716:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  717: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  718: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    719: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  720: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        721: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    722: 	'<input type="hidden" name="student" value="" />'."\n".
                    723: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    724: 	'</form>'."\n";
                    725:     return $jscript;
                    726: }
1.39      ng        727: 
1.447     foxr      728: 
                    729: 
1.315     bowersj2  730: # Given the score (as a number [0-1] and the weight) what is the final
                    731: # point value? This function will round to the nearest tenth, third,
                    732: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  733: sub compute_points {
1.315     bowersj2  734:     my ($score, $weight) = @_;
                    735:     
                    736:     my $tolerance = .00001;
                    737:     my $points = $score * $weight;
                    738: 
                    739:     # Check for nearness to 1/x.
                    740:     my $check_for_nearness = sub {
                    741:         my ($factor) = @_;
                    742:         my $num = ($points * $factor) + $tolerance;
                    743:         my $floored_num = floor($num);
1.316     albertel  744:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  745:             return $floored_num / $factor;
                    746:         }
                    747:         return $points;
                    748:     };
                    749: 
                    750:     $points = $check_for_nearness->(10);
                    751:     $points = $check_for_nearness->(3);
                    752:     $points = $check_for_nearness->(4);
                    753:     
                    754:     return $points;
                    755: }
                    756: 
1.44      ng        757: #------------------ End of general use routines --------------------
1.87      www       758: 
                    759: #
                    760: # Find most similar essay
                    761: #
                    762: 
                    763: sub most_similar {
1.596.2.12.2.  (raeburn  764:):     my ($uname,$udom,$symb,$uessay)=@_;
                    765:): 
                    766:):     unless ($symb) { return ''; }
                    767:): 
                    768:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       769: 
                    770: # ignore spaces and punctuation
                    771: 
                    772:     $uessay=~s/\W+/ /gs;
                    773: 
1.282     www       774: # ignore empty submissions (occuring when only files are sent)
                    775: 
1.596.2.4  raeburn   776:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       777: 
1.87      www       778: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       779:     my $limit=0.6;
1.87      www       780:     my $sname='';
                    781:     my $sdom='';
                    782:     my $scrsid='';
                    783:     my $sessay='';
                    784: # go through all essays ...
1.596.2.12.2.  (raeburn  785:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  786: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       787: # ... except the same student
1.426     albertel  788:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  789:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  790: 	$tessay=~s/\W+/ /gs;
1.87      www       791: # String similarity gives up if not even limit
1.426     albertel  792: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       793: # Found one
1.426     albertel  794: 	if ($tsimilar>$limit) {
                    795: 	    $limit=$tsimilar;
                    796: 	    $sname=$tname;
                    797: 	    $sdom=$tdom;
                    798: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  799:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  800: 	}
1.87      www       801:     }
1.88      www       802:     if ($limit>0.6) {
1.87      www       803:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    804:     } else {
                    805:        return ('','','','',0);
                    806:     }
                    807: }
                    808: 
1.44      ng        809: #-------------------------------------------------------------------
                    810: 
                    811: #------------------------------------ Receipt Verification Routines
1.45      ng        812: #
1.44      ng        813: #--- Check whether a receipt number is valid.---
                    814: sub verifyreceipt {
                    815:     my $request  = shift;
                    816: 
1.257     albertel  817:     my $courseid = $env{'request.course.id'};
1.184     www       818:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  819: 	$env{'form.receipt'};
1.44      ng        820:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  821:     my ($symb)   = &get_symb($request);
1.44      ng        822: 
1.487     albertel  823:     my $title.=
                    824: 	'<h3><span class="LC_info">'.
1.584     bisitz    825: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  826: 	'</span></h3>'."\n".
1.596.2.12.2.  2(raebur  827:3): 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
1.487     albertel  828: 	'</h4>'."\n";
1.44      ng        829: 
                    830:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   831:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  832:     
                    833:     my $receiptparts=0;
1.390     albertel  834:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    835: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  836:     my $parts=['0'];
1.582     raeburn   837:     if ($receiptparts) {
                    838:         my $res_error; 
                    839:         ($parts)=&response_type($symb,\$res_error);
                    840:         if ($res_error) {
                    841:             return &navmap_errormsg();
                    842:         } 
                    843:     }
1.486     albertel  844:     
                    845:     my $header = 
                    846: 	&Apache::loncommon::start_data_table().
                    847: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  848: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    849: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    850: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  851:     if ($receiptparts) {
1.487     albertel  852: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  853:     }
                    854:     $header.=
                    855: 	&Apache::loncommon::end_data_table_header_row();
                    856: 
1.294     albertel  857:     foreach (sort 
                    858: 	     {
                    859: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    860: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    861: 		 }
                    862: 		 return $a cmp $b;
                    863: 	     } (keys(%$fullname))) {
1.44      ng        864: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  865: 	foreach my $part (@$parts) {
                    866: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  867: 		$contents.=
                    868: 		    &Apache::loncommon::start_data_table_row().
                    869: 		    '<td>&nbsp;'."\n".
1.177     albertel  870: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  871: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  872: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    873: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    874: 		if ($receiptparts) {
                    875: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    876: 		}
1.486     albertel  877: 		$contents.= 
                    878: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  879: 		
                    880: 		$matches++;
                    881: 	    }
1.44      ng        882: 	}
                    883:     }
                    884:     if ($matches == 0) {
1.584     bisitz    885:         $string = $title
                    886:                  .'<p class="LC_warning">'
                    887:                  .&mt('No match found for the above receipt number.')
                    888:                  .'</p>';
1.44      ng        889:     } else {
1.324     albertel  890: 	$string = &jscriptNform($symb).$title.
1.487     albertel  891: 	    '<p>'.
1.584     bisitz    892: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  893: 	    '</p>'.
1.486     albertel  894: 	    $header.
                    895: 	    $contents.
                    896: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        897:     }
1.324     albertel  898:     return $string.&show_grading_menu_form($symb);
1.44      ng        899: }
                    900: 
                    901: #--- This is called by a number of programs.
                    902: #--- Called from the Grading Menu - View/Grade an individual student
                    903: #--- Also called directly when one clicks on the subm button 
                    904: #    on the problem page.
1.30      ng        905: sub listStudents {
1.41      ng        906:     my ($request) = shift;
1.49      albertel  907: 
1.324     albertel  908:     my ($symb) = &get_symb($request);
1.257     albertel  909:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    910:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    911:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  912:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  913:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    914:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  915:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    916: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  917: 
1.548     bisitz    918:     my $result='<h3><span class="LC_info">&nbsp;'
                    919: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  920: 	.'</span></h3>';
1.118     ng        921: 
1.324     albertel  922:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  923: 
1.596.2.12.2.  6(raebur  924:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   925: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    926: 		'single'   => 'Please select the student before clicking on the Next button.',
                    927: 	     );
1.596.2.12.2.  6(raebur  928:6):     &js_escape(\%js_lt);
1.45      ng        929:     $request->print(<<LISTJAVASCRIPT);
                    930: <script type="text/javascript" language="javascript">
1.110     ng        931:     function checkSelect(checkBox) {
                    932: 	var ctr=0;
                    933: 	var sense="";
                    934: 	if (checkBox.length > 1) {
                    935: 	    for (var i=0; i<checkBox.length; i++) {
                    936: 		if (checkBox[i].checked) {
                    937: 		    ctr++;
                    938: 		}
                    939: 	    }
1.596.2.12.2.  6(raebur  940:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng        941: 	} else {
                    942: 	    if (checkBox.checked) {
                    943: 		ctr = 1;
                    944: 	    }
1.596.2.12.2.  6(raebur  945:6): 	    sense = '$js_lt{'single'}';
1.110     ng        946: 	}
                    947: 	if (ctr == 0) {
1.485     albertel  948: 	    alert(sense);
1.110     ng        949: 	    return false;
                    950: 	}
                    951: 	document.gradesub.submit();
                    952:     }
                    953: 
                    954:     function reLoadList(formname) {
1.112     ng        955: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        956: 	formname.command.value = 'submission';
                    957: 	formname.submit();
                    958:     }
1.45      ng        959: </script>
                    960: LISTJAVASCRIPT
                    961: 
1.118     ng        962:     &commonJSfunctions($request);
1.41      ng        963:     $request->print($result);
1.39      ng        964: 
1.401     albertel  965:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    966:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  967:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  968: 	"\n".$table;
                    969: 	
1.561     bisitz    970:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    971:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    972:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    973:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    974:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    975:                   .&Apache::lonhtmlcommon::row_closure();
                    976:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    977:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    978:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    979:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    980:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  981: 
                    982:     my $submission_options;
1.257     albertel  983:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  984: 	$submission_options.=
                    985: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  986:     }
1.442     banghart  987:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    988:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  989:     $env{'form.Status'} = $saveStatus;
1.485     albertel  990:     $submission_options.=
1.592     bisitz    991:         '<span class="LC_nobreak">'.
                    992:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    993:         &mt('last submission only').' </label></span>'."\n".
                    994:         '<span class="LC_nobreak">'.
                    995:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    996:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    997:         '<span class="LC_nobreak">'.
                    998:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    999:         &mt('by dates and submissions').'</label></span>'."\n".
                   1000:         '<span class="LC_nobreak">'.
                   1001:         '<label><input type="radio" name="lastSub" value="all" /> '.
                   1002:         &mt('all details').'</label></span>';
1.561     bisitz   1003:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                   1004:                   .$submission_options
                   1005:                   .&Apache::lonhtmlcommon::row_closure();
                   1006: 
                   1007:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1008:                   .'<select name="increment">'
                   1009:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1010:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1011:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1012:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1013:                   .'</select>'
                   1014:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1015: 
                   1016:     $gradeTable .= 
1.432     banghart 1017:         &build_section_inputs().
1.45      ng       1018: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel 1019: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                   1020: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                   1021: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1022: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1023: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1024: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1025: 
1.257     albertel 1026:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz   1027: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1028:     } else {
1.561     bisitz   1029:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1030:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1031:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1032:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1033:     }
1.112     ng       1034: 
1.561     bisitz   1035:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1036:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1037:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1038:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1039: 
                   1040:     $gradeTable .= '<p>'
                   1041:                   .&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"
                   1042:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1043:                   .'</p>';
1.249     albertel 1044: 
                   1045: # checkall buttons
                   1046:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1047:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1048:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1049:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1050:     $gradeTable.=&check_buttons();
1.450     banghart 1051:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1052:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1053: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1054:     my $loop = 0;
                   1055:     while ($loop < 2) {
1.485     albertel 1056: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1057: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1058: 	if ($env{'form.showgrading'} eq 'yes' 
                   1059: 	    && $submitonly ne 'queued'
                   1060: 	    && $submitonly ne 'all') {
1.485     albertel 1061: 	    foreach my $part (sort(@$partlist)) {
                   1062: 		my $display_part=
                   1063: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1064: 		$gradeTable.=
                   1065: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1066: 	    }
1.301     albertel 1067: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1068: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1069: 	}
                   1070: 	$loop++;
1.126     ng       1071: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1072:     }
1.474     albertel 1073:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1074: 
1.45      ng       1075:     my $ctr = 0;
1.294     albertel 1076:     foreach my $student (sort 
                   1077: 			 {
                   1078: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1079: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1080: 			     }
                   1081: 			     return $a cmp $b;
                   1082: 			 }
                   1083: 			 (keys(%$fullname))) {
1.41      ng       1084: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1085: 
1.110     ng       1086: 	my %status = ();
1.301     albertel 1087: 
                   1088: 	if ($submitonly eq 'queued') {
                   1089: 	    my %queue_status = 
                   1090: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1091: 							$udom,$uname);
                   1092: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1093: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1094: 	}
                   1095: 
                   1096: 	if ($env{'form.showgrading'} eq 'yes' 
                   1097: 	    && $submitonly ne 'queued'
                   1098: 	    && $submitonly ne 'all') {
1.324     albertel 1099: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1100: 	    my $submitted = 0;
1.164     albertel 1101: 	    my $graded = 0;
1.248     albertel 1102: 	    my $incorrect = 0;
1.110     ng       1103: 	    foreach (keys(%status)) {
1.145     albertel 1104: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1105: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1106: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1107: 		
1.110     ng       1108: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1109: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1110: 		    $submitted = 0;
1.150     albertel 1111: 		    my ($part)=split(/\./,$partid);
1.110     ng       1112: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1113: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1114: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1115: 		}
1.41      ng       1116: 	    }
1.248     albertel 1117: 	    
1.156     albertel 1118: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1119: 				     $submitonly eq 'incorrect' ||
                   1120: 				     $submitonly eq 'graded'));
1.248     albertel 1121: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1122: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1123: 	}
1.34      ng       1124: 
1.45      ng       1125: 	$ctr++;
1.249     albertel 1126: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1127:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1128: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1129: 	    if ($ctr%2 ==1) {
                   1130: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1131: 	    }
1.126     ng       1132: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1133:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1134:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1135: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1136: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1137: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1138: 
1.257     albertel 1139: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1140: 		foreach (sort(keys(%status))) {
1.485     albertel 1141: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1142: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1143: 		}
1.41      ng       1144: 	    }
1.126     ng       1145: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1146: 	    if ($ctr%2 ==0) {
                   1147: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1148: 	    }
1.41      ng       1149: 	}
                   1150:     }
1.110     ng       1151:     if ($ctr%2 ==1) {
1.126     ng       1152: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1153: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1154: 		&& $submitonly ne 'queued'
                   1155: 		&& $submitonly ne 'all') {
1.110     ng       1156: 		foreach (@$partlist) {
                   1157: 		    $gradeTable.='<td>&nbsp;</td>';
                   1158: 		}
1.301     albertel 1159: 	    } elsif ($submitonly eq 'queued') {
                   1160: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1161: 	    }
1.474     albertel 1162: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1163:     }
                   1164: 
1.474     albertel 1165:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1166:         '<input type="button" '.
                   1167:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1168:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1169:     if ($ctr == 0) {
1.96      albertel 1170: 	my $num_students=(scalar(keys(%$fullname)));
                   1171: 	if ($num_students eq 0) {
1.485     albertel 1172: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1173: 	} else {
1.171     albertel 1174: 	    my $submissions='submissions';
                   1175: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1176: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1177: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1178: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1179:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1180: 		    $num_students).
                   1181: 		'</span><br />';
1.96      albertel 1182: 	}
1.46      ng       1183:     } elsif ($ctr == 1) {
1.474     albertel 1184: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1185:     }
1.324     albertel 1186:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1187:     $request->print($gradeTable);
1.44      ng       1188:     return '';
1.10      ng       1189: }
                   1190: 
1.44      ng       1191: #---- Called from the listStudents routine
1.249     albertel 1192: 
                   1193: sub check_script {
                   1194:     my ($form, $type)=@_;
                   1195:     my $chkallscript='<script type="text/javascript">
                   1196:     function checkall() {
                   1197:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1198:             ele = document.forms.'.$form.'.elements[i];
                   1199:             if (ele.name == "'.$type.'") {
                   1200:             document.forms.'.$form.'.elements[i].checked=true;
                   1201:                                        }
                   1202:         }
                   1203:     }
                   1204: 
                   1205:     function checksec() {
                   1206:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1207:             ele = document.forms.'.$form.'.elements[i];
                   1208:            string = document.forms.'.$form.'.chksec.value;
                   1209:            if
                   1210:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1211:               document.forms.'.$form.'.elements[i].checked=true;
                   1212:             }
                   1213:         }
                   1214:     }
                   1215: 
                   1216: 
                   1217:     function uncheckall() {
                   1218:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1219:             ele = document.forms.'.$form.'.elements[i];
                   1220:             if (ele.name == "'.$type.'") {
                   1221:             document.forms.'.$form.'.elements[i].checked=false;
                   1222:                                        }
                   1223:         }
                   1224:     }
                   1225: 
                   1226: </script>'."\n";
                   1227:     return $chkallscript;
                   1228: }
                   1229: 
                   1230: sub check_buttons {
1.485     albertel 1231:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1232:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1233:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1234:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1235:     return $buttons;
                   1236: }
                   1237: 
1.44      ng       1238: #     Displays the submissions for one student or a group of students
1.34      ng       1239: sub processGroup {
1.41      ng       1240:     my ($request)  = shift;
                   1241:     my $ctr        = 0;
1.155     albertel 1242:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1243:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1244: 
1.396     banghart 1245:     foreach my $student (@stuchecked) {
                   1246: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1247: 	$env{'form.student'}        = $uname;
                   1248: 	$env{'form.userdom'}        = $udom;
                   1249: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1250: 	&submission($request,$ctr,$total);
                   1251: 	$ctr++;
                   1252:     }
                   1253:     return '';
1.35      ng       1254: }
1.34      ng       1255: 
1.44      ng       1256: #------------------------------------------------------------------------------------
                   1257: #
                   1258: #-------------------------- Next few routines handles grading by student, essentially
                   1259: #                           handles essay response type problem/part
                   1260: #
                   1261: #--- Javascript to handle the submission page functionality ---
                   1262: sub sub_page_js {
                   1263:     my $request = shift;
1.596.2.12.2.  6(raebur 1264:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1265:6):     &js_escape(\$alertmsg);
1.44      ng       1266:     $request->print(<<SUBJAVASCRIPT);
                   1267: <script type="text/javascript" language="javascript">
1.71      ng       1268:     function updateRadio(formname,id,weight) {
1.125     ng       1269: 	var gradeBox = formname["GD_BOX"+id];
                   1270: 	var radioButton = formname["RADVAL"+id];
                   1271: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1272: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1273: 	gradeBox.value = pts;
                   1274: 	var resetbox = false;
                   1275: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1276: 	    alert("$alertmsg"+pts);
1.71      ng       1277: 	    for (var i=0; i<radioButton.length; i++) {
                   1278: 		if (radioButton[i].checked) {
                   1279: 		    gradeBox.value = i;
                   1280: 		    resetbox = true;
                   1281: 		}
                   1282: 	    }
                   1283: 	    if (!resetbox) {
                   1284: 		formtextbox.value = "";
                   1285: 	    }
                   1286: 	    return;
1.44      ng       1287: 	}
1.71      ng       1288: 
                   1289: 	if (pts > weight) {
                   1290: 	    var resp = confirm("You entered a value ("+pts+
                   1291: 			       ") greater than the weight for the part. Accept?");
                   1292: 	    if (resp == false) {
1.125     ng       1293: 		gradeBox.value = oldpts;
1.71      ng       1294: 		return;
                   1295: 	    }
1.44      ng       1296: 	}
1.13      albertel 1297: 
1.71      ng       1298: 	for (var i=0; i<radioButton.length; i++) {
                   1299: 	    radioButton[i].checked=false;
                   1300: 	    if (pts == i && pts != "") {
                   1301: 		radioButton[i].checked=true;
                   1302: 	    }
                   1303: 	}
                   1304: 	updateSelect(formname,id);
1.125     ng       1305: 	formname["stores"+id].value = "0";
1.41      ng       1306:     }
1.5       albertel 1307: 
1.72      ng       1308:     function writeBox(formname,id,pts) {
1.125     ng       1309: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1310: 	if (checkSolved(formname,id) == 'update') {
                   1311: 	    gradeBox.value = pts;
                   1312: 	} else {
1.125     ng       1313: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1314: 	    gradeBox.value = oldpts;
1.125     ng       1315: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1316: 	    for (var i=0; i<radioButton.length; i++) {
                   1317: 		radioButton[i].checked=false;
1.72      ng       1318: 		if (i == oldpts) {
1.71      ng       1319: 		    radioButton[i].checked=true;
                   1320: 		}
                   1321: 	    }
1.41      ng       1322: 	}
1.125     ng       1323: 	formname["stores"+id].value = "0";
1.71      ng       1324: 	updateSelect(formname,id);
                   1325: 	return;
1.41      ng       1326:     }
1.44      ng       1327: 
1.71      ng       1328:     function clearRadBox(formname,id) {
                   1329: 	if (checkSolved(formname,id) == 'noupdate') {
                   1330: 	    updateSelect(formname,id);
                   1331: 	    return;
                   1332: 	}
1.125     ng       1333: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1334: 	for (var i=0; i<gradeSelect.length; i++) {
                   1335: 	    if (gradeSelect[i].selected) {
                   1336: 		var selectx=i;
                   1337: 	    }
                   1338: 	}
1.125     ng       1339: 	var stores = formname["stores"+id];
1.71      ng       1340: 	if (selectx == stores.value) { return };
1.125     ng       1341: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1342: 	gradeBox.value = "";
1.125     ng       1343: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1344: 	for (var i=0; i<radioButton.length; i++) {
                   1345: 	    radioButton[i].checked=false;
                   1346: 	}
                   1347: 	stores.value = selectx;
                   1348:     }
1.5       albertel 1349: 
1.71      ng       1350:     function checkSolved(formname,id) {
1.125     ng       1351: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1352: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1353: 	    if (!reply) {return "noupdate";}
1.120     ng       1354: 	    formname.overRideScore.value = 'yes';
1.41      ng       1355: 	}
1.71      ng       1356: 	return "update";
1.13      albertel 1357:     }
1.71      ng       1358: 
                   1359:     function updateSelect(formname,id) {
1.125     ng       1360: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1361: 	return;
1.41      ng       1362:     }
1.33      ng       1363: 
1.121     ng       1364: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1365:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1366: 	formname.gradeOpt.value = val;
1.71      ng       1367: 	if (val == "Save & Next") {
                   1368: 	    for (i=0;i<=total;i++) {
                   1369: 		for (j=0;j<parttot;j++) {
1.125     ng       1370: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1371: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1372: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1373: 			if (points == "") {
1.125     ng       1374: 			    var name = formname["name"+i].value;
1.129     ng       1375: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1376: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1377: 					       ", part "+partid+". Continue?");
1.71      ng       1378: 			    if (resp == false) {
1.125     ng       1379: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1380: 				return false;
                   1381: 			    }
                   1382: 			}
                   1383: 		    }
                   1384: 		}
                   1385: 	    }
                   1386: 	}
1.121     ng       1387: 	if (val == "Grade Student") {
                   1388: 	    formname.showgrading.value = "yes";
                   1389: 	    if (formname.Status.value == "") {
                   1390: 		formname.Status.value = "Active";
                   1391: 	    }
                   1392: 	    formname.studentNo.value = total;
                   1393: 	}
1.120     ng       1394: 	formname.submit();
                   1395:     }
                   1396: 
1.71      ng       1397: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1398:     function checkSubmitPage(formname,total) {
                   1399: 	noscore = new Array(100);
                   1400: 	var ptr = 0;
                   1401: 	for (i=1;i<total;i++) {
1.125     ng       1402: 	    var partid = formname["q_"+i].value;
1.127     ng       1403: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1404: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1405: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1406: 		if (points == "" && status != "correct_by_student") {
                   1407: 		    noscore[ptr] = i;
                   1408: 		    ptr++;
                   1409: 		}
                   1410: 	    }
                   1411: 	}
                   1412: 	if (ptr != 0) {
                   1413: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1414: 	    var prolist = "";
                   1415: 	    if (ptr == 1) {
                   1416: 		prolist = noscore[0];
                   1417: 	    } else {
                   1418: 		var i = 0;
                   1419: 		while (i < ptr-1) {
                   1420: 		    prolist += noscore[i]+", ";
                   1421: 		    i++;
                   1422: 		}
                   1423: 		prolist += "and "+noscore[i];
                   1424: 	    }
                   1425: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1426: 	    if (resp == false) {
                   1427: 		return false;
                   1428: 	    }
                   1429: 	}
1.45      ng       1430: 
1.71      ng       1431: 	formname.submit();
                   1432:     }
                   1433: </script>
                   1434: SUBJAVASCRIPT
                   1435: }
1.45      ng       1436: 
1.71      ng       1437: #--- javascript for essay type problem --
                   1438: sub sub_page_kw_js {
                   1439:     my $request = shift;
1.80      ng       1440:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1441:     &commonJSfunctions($request);
1.350     albertel 1442: 
1.351     albertel 1443:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1444:     <script text="text/javascript">
                   1445:     function checkInput() {
                   1446:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1447:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1448:       var usrctr = document.msgcenter.usrctr.value;
                   1449:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1450:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1451: 
                   1452:       var msgchk = "";
                   1453:       if (document.msgcenter.subchk.checked) {
                   1454:          msgchk = "msgsub,";
                   1455:       }
                   1456:       var includemsg = 0;
                   1457:       for (var i=1; i<=nmsg; i++) {
                   1458:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1459:           var frmmsg = document.msgcenter["msg"+i];
                   1460:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1461:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1462:           showflg.value = "1";
                   1463:           var chkbox = document.msgcenter["msgn"+i];
                   1464:           if (chkbox.checked) {
                   1465:              msgchk += "savemsg"+i+",";
                   1466:              includemsg = 1;
                   1467:           }
                   1468:       }
                   1469:       if (document.msgcenter.newmsgchk.checked) {
                   1470:          msgchk += "newmsg"+usrctr;
                   1471:          includemsg = 1;
                   1472:       }
                   1473:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1474:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1475:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1476:       includemsg.value = msgchk;
                   1477: 
                   1478:       self.close()
                   1479: 
                   1480:     }
                   1481:     </script>
                   1482: INNERJS
                   1483: 
1.351     albertel 1484:     my $inner_js_highlight_central=<<INNERJS;
                   1485:  <script type="text/javascript">
                   1486:     function updateChoice(flag) {
                   1487:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1488:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1489:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1490:       opener.document.SCORE.refresh.value = "on";
                   1491:       if (opener.document.SCORE.keywords.value!=""){
                   1492:          opener.document.SCORE.submit();
                   1493:       }
                   1494:       self.close()
                   1495:     }
                   1496: </script>
                   1497: INNERJS
                   1498: 
                   1499:     my $start_page_msg_central = 
                   1500:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1501: 				       {'js_ready'  => 1,
                   1502: 					'only_body' => 1,
                   1503: 					'bgcolor'   =>'#FFFFFF',});
                   1504:     my $end_page_msg_central = 
                   1505: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1506: 
                   1507: 
                   1508:     my $start_page_highlight_central = 
                   1509:         &Apache::loncommon::start_page('Highlight Central',
                   1510: 				       $inner_js_highlight_central,
1.350     albertel 1511: 				       {'js_ready'  => 1,
                   1512: 					'only_body' => 1,
                   1513: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1514:     my $end_page_highlight_central = 
1.350     albertel 1515: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1516: 
1.219     www      1517:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1518:     $docopen=~s/^document\.//;
1.596.2.12.2.  6(raebur 1519:6):     my %js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1520:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1521:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1522:                 adds => 'Add selection to keyword list? Edit if desired.',
1.596.2.12.2.  6(raebur 1523:6):                 col1 => 'red',
                   1524:6):                 col2 => 'green',
                   1525:6):                 col3 => 'blue',
                   1526:6):                 siz1 => 'normal',
                   1527:6):                 siz2 => '+1',
                   1528:6):                 siz3 => '+2',
                   1529:6):                 sty1 => 'normal',
                   1530:6):                 sty2 => 'italic',
                   1531:6):                 sty3 => 'bold',
                   1532:6):              );
                   1533:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1534:                 comp => 'Compose Message for: ',
                   1535:                 incl => 'Include',
                   1536:                 type => 'Type',
                   1537:                 subj => 'Subject',
                   1538:                 mesa => 'Message',
                   1539:                 new  => 'New',
                   1540:                 save => 'Save',
                   1541:                 canc => 'Cancel',
                   1542:                 kehi => 'Keyword Highlight Options',
                   1543:                 txtc => 'Text Color',
                   1544:                 font => 'Font Size',
                   1545:                 fnst => 'Font Style',
                   1546:              );
1.596.2.12.2.  6(raebur 1547:6):     &js_escape(\%js_lt);
                   1548:6):     &html_escape(\%html_js_lt);
                   1549:6):     &js_escape(\%html_js_lt);
1.71      ng       1550:     $request->print(<<SUBJAVASCRIPT);
                   1551: <script type="text/javascript" language="javascript">
1.45      ng       1552: 
1.44      ng       1553: //===================== Show list of keywords ====================
1.122     ng       1554:   function keywords(formname) {
1.596.2.12.2.  6(raebur 1555:6):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1556:     if (nret==null) return;
1.122     ng       1557:     formname.keywords.value = nret;
1.44      ng       1558: 
1.122     ng       1559:     if (formname.keywords.value != "") {
1.128     ng       1560: 	formname.refresh.value = "on";
1.122     ng       1561: 	formname.submit();
1.44      ng       1562:     }
                   1563:     return;
                   1564:   }
                   1565: 
                   1566: //===================== Script to view submitted by ==================
                   1567:   function viewSubmitter(submitter) {
                   1568:     document.SCORE.refresh.value = "on";
                   1569:     document.SCORE.NCT.value = "1";
                   1570:     document.SCORE.unamedom0.value = submitter;
                   1571:     document.SCORE.submit();
                   1572:     return;
                   1573:   }
                   1574: 
                   1575: //===================== Script to add keyword(s) ==================
                   1576:   function getSel() {
                   1577:     if (document.getSelection) txt = document.getSelection();
                   1578:     else if (document.selection) txt = document.selection.createRange().text;
                   1579:     else return;
                   1580:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1581:     if (cleantxt=="") {
1.596.2.12.2.  6(raebur 1582:6): 	alert("$js_lt{'plse'}");
1.44      ng       1583: 	return;
                   1584:     }
1.596.2.12.2.  6(raebur 1585:6):     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1586:     if (nret==null) return;
1.127     ng       1587:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1588:     if (document.SCORE.keywords.value != "") {
1.127     ng       1589: 	document.SCORE.refresh.value = "on";
1.44      ng       1590: 	document.SCORE.submit();
                   1591:     }
                   1592:     return;
                   1593:   }
                   1594: 
                   1595: //====================== Script for composing message ==============
1.80      ng       1596:    // preload images
                   1597:    img1 = new Image();
                   1598:    img1.src = "$iconpath/mailbkgrd.gif";
                   1599:    img2 = new Image();
                   1600:    img2.src = "$iconpath/mailto.gif";
                   1601: 
1.44      ng       1602:   function msgCenter(msgform,usrctr,fullname) {
                   1603:     var Nmsg  = msgform.savemsgN.value;
                   1604:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1605:     var subject = msgform.msgsub.value;
1.127     ng       1606:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1607:     re = /msgsub/;
                   1608:     var shwsel = "";
                   1609:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1610:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1611:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1612:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1613: 	var testmsg = "savemsg"+i+",";
                   1614: 	re = new RegExp(testmsg,"g");
1.44      ng       1615: 	shwsel = "";
                   1616: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1617: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1618: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1619: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1620: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1621:     }
1.125     ng       1622:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1623:     shwsel = "";
                   1624:     re = /newmsg/;
                   1625:     if (re.test(msgchk)) { shwsel = "checked" }
                   1626:     newMsg(newmsg,shwsel);
                   1627:     msgTail(); 
                   1628:     return;
                   1629:   }
                   1630: 
1.123     ng       1631:   function checkEntities(strx) {
                   1632:     if (strx.length == 0) return strx;
                   1633:     var orgStr = ["&", "<", ">", '"']; 
                   1634:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1635:     var counter = 0;
                   1636:     while (counter < 4) {
                   1637: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1638: 	counter++;
                   1639:     }
                   1640:     return strx;
                   1641:   }
                   1642: 
                   1643:   function strReplace(strx, orgStr, newStr) {
                   1644:     return strx.split(orgStr).join(newStr);
                   1645:   }
                   1646: 
1.44      ng       1647:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1648:     var height = 70*Nmsg+250;
1.44      ng       1649:     if (height > 600) {
                   1650: 	height = 600;
                   1651:     }
1.118     ng       1652:     var xpos = (screen.width-600)/2;
                   1653:     xpos = (xpos < 0) ? '0' : xpos;
                   1654:     var ypos = (screen.height-height)/2-30;
                   1655:     ypos = (ypos < 0) ? '0' : ypos;
                   1656: 
1.596.2.12.2.  (raeburn 1657:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1658:     pWin.focus();
                   1659:     pDoc = pWin.document;
1.219     www      1660:     pDoc.$docopen;
1.351     albertel 1661:     pDoc.write('$start_page_msg_central');
1.76      ng       1662: 
                   1663:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1664:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  6(raebur 1665:6):     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1666: 
1.564     bisitz   1667:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1668:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.12.2.  6(raebur 1669:6):     pDoc.write("<td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1670: }
                   1671:     function displaySubject(msg,shwsel) {
1.76      ng       1672:     pDoc = pWin.document;
                   1673:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.12.2.  6(raebur 1674:6):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.465     albertel 1675:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1676:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1677: }
                   1678: 
1.72      ng       1679:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1680:     pDoc = pWin.document;
                   1681:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1682:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1683:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1684:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1685: }
                   1686: 
                   1687:   function newMsg(newmsg,shwsel) {
1.76      ng       1688:     pDoc = pWin.document;
                   1689:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.12.2.  6(raebur 1690:6):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1691:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1692:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1693: }
                   1694: 
                   1695:   function msgTail() {
1.76      ng       1696:     pDoc = pWin.document;
1.465     albertel 1697:     pDoc.write("<\\/table>");
                   1698:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1699:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1700:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1701:     pDoc.write("<\\/form>");
1.351     albertel 1702:     pDoc.write('$end_page_msg_central');
1.128     ng       1703:     pDoc.close();
1.44      ng       1704: }
                   1705: 
                   1706: //====================== Script for keyword highlight options ==============
                   1707:   function kwhighlight() {
                   1708:     var kwclr    = document.SCORE.kwclr.value;
                   1709:     var kwsize   = document.SCORE.kwsize.value;
                   1710:     var kwstyle  = document.SCORE.kwstyle.value;
                   1711:     var redsel = "";
                   1712:     var grnsel = "";
                   1713:     var blusel = "";
1.596.2.12.2.  6(raebur 1714:6):     var txtcol1 = "$js_lt{'col1'}";
                   1715:6):     var txtcol2 = "$js_lt{'col2'}";
                   1716:6):     var txtcol3 = "$js_lt{'col3'}";
                   1717:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1718:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1719:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1720:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1721:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1722:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1723:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1724:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1725:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1726:     var sznsel = "";
                   1727:     var sz1sel = "";
                   1728:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1729:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1730:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1731:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1732:     var synsel = "";
                   1733:     var syisel = "";
                   1734:     var sybsel = "";
1.596.2.12.2.  8(raebur 1735:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1736:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1737:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1738:     highlightCentral();
1.596.2.12.2.  8(raebur 1739:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1740:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1741:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1742:     highlightend();
                   1743:     return;
                   1744:   }
                   1745: 
                   1746:   function highlightCentral() {
1.76      ng       1747: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1748:     var xpos = (screen.width-400)/2;
                   1749:     xpos = (xpos < 0) ? '0' : xpos;
                   1750:     var ypos = (screen.height-330)/2-30;
                   1751:     ypos = (ypos < 0) ? '0' : ypos;
                   1752: 
1.206     albertel 1753:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1754:     hwdWin.focus();
                   1755:     var hDoc = hwdWin.document;
1.219     www      1756:     hDoc.$docopen;
1.351     albertel 1757:     hDoc.write('$start_page_highlight_central');
1.76      ng       1758:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1759:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1760: 
1.596.2.12.2.  8(raebur 1761:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1762:6):     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1763:   }
                   1764: 
                   1765:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1766:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1767:4):     hDoc.write("<tr>");
1.76      ng       1768:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1769:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1770:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1771:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1772:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1773:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1774:     hDoc.write("<\\/tr>");
1.44      ng       1775:   }
                   1776: 
                   1777:   function highlightend() { 
1.76      ng       1778:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1779:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1780:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1781:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1782:     hDoc.write("<\\/form>");
1.351     albertel 1783:     hDoc.write('$end_page_highlight_central');
1.128     ng       1784:     hDoc.close();
1.44      ng       1785:   }
                   1786: 
                   1787: </script>
                   1788: SUBJAVASCRIPT
                   1789: }
                   1790: 
1.349     albertel 1791: sub get_increment {
1.348     bowersj2 1792:     my $increment = $env{'form.increment'};
                   1793:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1794:         $increment != .1) {
                   1795:         $increment = 1;
                   1796:     }
                   1797:     return $increment;
                   1798: }
                   1799: 
1.585     bisitz   1800: sub gradeBox_start {
                   1801:     return (
                   1802:         &Apache::loncommon::start_data_table()
                   1803:        .&Apache::loncommon::start_data_table_header_row()
                   1804:        .'<th>'.&mt('Part').'</th>'
                   1805:        .'<th>'.&mt('Points').'</th>'
                   1806:        .'<th>&nbsp;</th>'
                   1807:        .'<th>'.&mt('Assign Grade').'</th>'
                   1808:        .'<th>'.&mt('Weight').'</th>'
                   1809:        .'<th>'.&mt('Grade Status').'</th>'
                   1810:        .&Apache::loncommon::end_data_table_header_row()
                   1811:     );
                   1812: }
                   1813: 
                   1814: sub gradeBox_end {
                   1815:     return (
                   1816:         &Apache::loncommon::end_data_table()
                   1817:     );
                   1818: }
1.71      ng       1819: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1820: sub gradeBox {
1.322     albertel 1821:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1822:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1823: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1824:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1825:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1826:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1827:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1828:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1829: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1830:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1831:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1832:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1833: 				       [$partid]);
                   1834:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1835:     if ($last_resets{$partid}) {
                   1836:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1837:     }
1.596.2.12.2.  8(raebur 1838:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1839:     my $ctr = 0;
1.348     bowersj2 1840:     my $thisweight = 0;
1.349     albertel 1841:     my $increment = &get_increment();
1.485     albertel 1842: 
                   1843:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1844:     while ($thisweight<=$wgt) {
1.532     bisitz   1845: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1846:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1847: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1848: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1849: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1850:         $thisweight += $increment;
1.71      ng       1851: 	$ctr++;
                   1852:     }
1.485     albertel 1853:     $radio.='</tr></table>';
                   1854: 
                   1855:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1856: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1857: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1858: 	$wgt.')" /></td>'."\n";
1.485     albertel 1859:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1860: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1861: 	' </td>'."\n";
                   1862:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1863: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1864:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1865: 	$line.='<option></option>'.
                   1866: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1867:     } else {
1.485     albertel 1868: 	$line.='<option selected="selected"></option>'.
                   1869: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1870:     }
1.485     albertel 1871:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1872: 
                   1873: 
                   1874:     $result .= 
1.596.2.12.2.  8(raebur 1875:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1876:3):     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1.71      ng       1877:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1878: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1879: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1880: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1881:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1882:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1883:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1884:         $aggtries.'" />'."\n";
1.582     raeburn  1885:     my $res_error;
                   1886:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 1887:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1888:     if ($res_error) {
                   1889:         return &navmap_errormsg();
                   1890:     }
1.318     banghart 1891:     return $result;
                   1892: }
1.322     albertel 1893: 
                   1894: sub handback_box {
1.582     raeburn  1895:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1896:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1897:     my (@respids);
1.596.2.4  raeburn  1898:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1899:     foreach my $part_response_id (@part_response_id) {
                   1900:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1901:         if ($part eq $partid) {
1.375     albertel 1902:             push(@respids,$resp);
1.323     banghart 1903:         }
                   1904:     }
1.318     banghart 1905:     my $result;
1.323     banghart 1906:     foreach my $respid (@respids) {
1.322     albertel 1907: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1908: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1909: 	next if (!@$files);
1.596.2.4  raeburn  1910: 	my $file_counter = 0;
1.313     banghart 1911: 	foreach my $file (@$files) {
1.368     banghart 1912: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1913:                 $file_counter++;
1.368     banghart 1914:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1915:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1916:     	        $file_disp = "$name.$ext";
                   1917:     	        $file = $file_path.$file_disp;
                   1918:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1919:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1920:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1921:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1922: 	    }
1.322     albertel 1923: 	}
1.596.2.4  raeburn  1924:         if ($file_counter) {
                   1925:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1926:                        '<span class="LC_info">'.
                   1927:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1928:         }
1.313     banghart 1929:     }
1.318     banghart 1930:     return $result;    
1.71      ng       1931: }
1.44      ng       1932: 
1.58      albertel 1933: sub show_problem {
1.382     albertel 1934:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1935:     my $rendered;
1.382     albertel 1936:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1937:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1938:     if ($mode eq 'both' or $mode eq 'text') {
                   1939: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1940: 						       $env{'request.course.id'},
                   1941: 						       undef,\%form);
1.144     albertel 1942:     }
1.58      albertel 1943:     if ($removeform) {
                   1944: 	$rendered=~s|<form(.*?)>||g;
                   1945: 	$rendered=~s|</form>||g;
1.374     albertel 1946: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1947:     }
1.144     albertel 1948:     my $companswer;
                   1949:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1950: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1951: 	$companswer=
                   1952: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1953: 						    $env{'request.course.id'},
                   1954: 						    %form);
1.144     albertel 1955:     }
1.58      albertel 1956:     if ($removeform) {
                   1957: 	$companswer=~s|<form(.*?)>||g;
                   1958: 	$companswer=~s|</form>||g;
1.144     albertel 1959: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1960:     }
1.596.2.12.2.  (raeburn 1961:):     my $renderheading = &mt('View of the problem');
                   1962:):     my $answerheading = &mt('Correct answer');
                   1963:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1964:):         my $stu_fullname = $env{'form.fullname'};
                   1965:):         if ($stu_fullname eq '') {
                   1966:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1967:):         }
                   1968:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1969:):         if ($forwhom ne '') {
                   1970:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1971:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1972:):         }
                   1973:):     }
1.468     albertel 1974:     $rendered=
1.588     bisitz   1975:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1976:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1977:        .$rendered
                   1978:        .'</div>';
1.468     albertel 1979:     $companswer=
1.588     bisitz   1980:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1981:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1982:        .$companswer
                   1983:        .'</div>';
1.468     albertel 1984:     my $result;
1.144     albertel 1985:     if ($mode eq 'both') {
1.588     bisitz   1986:         $result=$rendered.$companswer;
1.144     albertel 1987:     } elsif ($mode eq 'text') {
1.588     bisitz   1988:         $result=$rendered;
1.144     albertel 1989:     } elsif ($mode eq 'answer') {
1.588     bisitz   1990:         $result=$companswer;
1.144     albertel 1991:     }
1.71      ng       1992:     return $result;
1.58      albertel 1993: }
1.397     albertel 1994: 
1.396     banghart 1995: sub files_exist {
                   1996:     my ($r, $symb) = @_;
                   1997:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1998: 
1.396     banghart 1999:     foreach my $student (@students) {
                   2000:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2001:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2002: 					      $udom,$uname);
1.396     banghart 2003:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2004:         foreach my $submission (@$string) {
                   2005:             my ($partid,$respid) =
                   2006: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2007:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2008: 					   \%record);
                   2009:             return 1 if (@$files);
1.396     banghart 2010:         }
                   2011:     }
1.397     albertel 2012:     return 0;
1.396     banghart 2013: }
1.397     albertel 2014: 
1.394     banghart 2015: sub download_all_link {
                   2016:     my ($r,$symb) = @_;
1.395     albertel 2017:     my $all_students = 
                   2018: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2019: 
                   2020:     my $parts =
                   2021: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2022: 
1.394     banghart 2023:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2024:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2025:                              'cgi.'.$identifier.'.symb' => $symb,
                   2026:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2027:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2028: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 2029:     return
                   2030: }
1.395     albertel 2031: 
1.432     banghart 2032: sub build_section_inputs {
                   2033:     my $section_inputs;
                   2034:     if ($env{'form.section'} eq '') {
                   2035:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2036:     } else {
                   2037:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2038:         foreach my $section (@sections) {
1.432     banghart 2039:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2040:         }
                   2041:     }
                   2042:     return $section_inputs;
                   2043: }
                   2044: 
1.44      ng       2045: # --------------------------- show submissions of a student, option to grade 
                   2046: sub submission {
                   2047:     my ($request,$counter,$total) = @_;
1.257     albertel 2048:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2049:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2050:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2051:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  (raeburn 2052:):     my ($symb) = &get_symb($request); 
1.324     albertel 2053:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2054: 
                   2055:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2056:4):         $request->print(
                   2057:4):             '<span class="LC_warning">'.
                   2058:4):             &mt('Unable to view requested student.').
                   2059:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2060:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2061:4):             '</span>');
1.324     albertel 2062: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2063: 	return;
                   2064:     }
                   2065: 
1.257     albertel 2066:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2067:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2068:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2069:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2070:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2071: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2072: 	'/check.gif" height="16" border="0" />';
1.41      ng       2073: 
                   2074:     # header info
                   2075:     if ($counter == 0) {
                   2076: 	&sub_page_js($request);
1.257     albertel 2077: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2078: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2079: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2080: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2081: 	    &download_all_link($request, $symb);
                   2082: 	}
1.485     albertel 2083: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1.596.2.12.2.  2(raebur 2084:3): 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2085: 
1.44      ng       2086: 	# option to display problem, only once else it cause problems 
                   2087:         # with the form later since the problem has a form.
1.257     albertel 2088: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2089: 	    my $mode;
1.257     albertel 2090: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2091: 		$mode='both';
1.257     albertel 2092: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2093: 		$mode='text';
1.257     albertel 2094: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2095: 		$mode='answer';
                   2096: 	    }
1.329     albertel 2097: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2098: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2099: 	}
1.441     www      2100: 
1.596.2.12.2.  0(raebur 2101:3): 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2102:         # if this subroutine has been called once.
1.41      ng       2103: 	my %keyhash = ();
1.257     albertel 2104: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2105: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2106: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2107: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2108: 
1.257     albertel 2109: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2110: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2111: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2112: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2113: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2114: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2115: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2116: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2117: 	}
1.257     albertel 2118: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2119: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2120: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2121: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2122: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2123: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2124: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2125: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2126: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2127: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2128: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2129: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2130: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2131: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2132: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2133: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2134: 			&build_section_inputs().
1.326     albertel 2135: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2136: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2137: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2138: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2139: 	if ($env{'form.handgrade'} eq 'yes') {
                   2140: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2141: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2142: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2143: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2144: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2145: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2146: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2147: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2148: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2149: 	    }
1.123     ng       2150: 	}
1.41      ng       2151: 	
                   2152: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2153: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2154: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2155: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2156: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2157: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2158: 		'" />'."\n".
                   2159: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2160: 	    $cts++;
                   2161: 	}
                   2162: 	$request->print($prnmsg);
1.32      ng       2163: 
1.257     albertel 2164: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2165: 
                   2166:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2167:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2168:                           keyw => 'Keyword Options',
                   2169:                           list => 'List',
                   2170:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2171:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2172:                      );
1.88      www      2173: #
                   2174: # Print out the keyword options line
                   2175: #
1.596.2.12.2.  8(raebur 2176:4):             $request->print(
                   2177:4):                 '<div class="LC_columnSection">'
                   2178:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2179:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2180:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2181:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2182:4):  class="page">'.$lt{'past'}.'</a>',
                   2183:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2184:4):                     {legend => $lt{'keyw'}})
                   2185:4):                .'</fieldset></div>'
                   2186:4):             );
                   2187:4): 
1.88      www      2188: #
                   2189: # Load the other essays for similarity check
                   2190: #
1.324     albertel 2191:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2192: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2193: 	    $apath=&escape($apath);
1.88      www      2194: 	    $apath=~s/\W/\_/gs;
1.596.2.12.2.  (raeburn 2195:):             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2196:         }
                   2197:     }
1.44      ng       2198: 
1.441     www      2199: # This is where output for one specific student would start
1.592     bisitz   2200:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2201:     $request->print(
                   2202:         "\n\n"
                   2203:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2204:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2205:        ."\n"
                   2206:     );
1.441     www      2207: 
1.592     bisitz   2208:     # Show additional functions if allowed
                   2209:     if ($perm{'vgr'}) {
                   2210:         $request->print(
                   2211:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2212:3):                 'View recent activity',
1.592     bisitz   2213:                 $uname,$udom,'check')
                   2214:            .' '
                   2215:         );
                   2216:     }
                   2217:     if ($perm{'opa'}) {
                   2218:         $request->print(
                   2219:             &Apache::loncommon::pprmlink(
                   2220:                 &mt('Set/Change parameters'),
                   2221:                 $uname,$udom,$symb,'check'));
                   2222:     }
                   2223: 
                   2224:     # Show Problem
1.257     albertel 2225:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2226: 	my $mode;
1.257     albertel 2227: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2228: 	    $mode='both';
1.257     albertel 2229: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2230: 	    $mode='text';
1.257     albertel 2231: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2232: 	    $mode='answer';
                   2233: 	}
1.329     albertel 2234: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2235: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2236:     }
1.144     albertel 2237: 
1.257     albertel 2238:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2239:     my $res_error;
                   2240:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2241:     if ($res_error) {
                   2242:         $request->print(&navmap_errormsg());
                   2243:         return;
                   2244:     }
1.41      ng       2245: 
1.44      ng       2246:     # Display student info
1.41      ng       2247:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2248: 
                   2249:     my $result='<div class="LC_Box">'
                   2250:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2251:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2252:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2253:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2254:         $result.='<p class="LC_info">'
                   2255:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2256:                 ."</p>\n";
1.469     albertel 2257:     }
                   2258: 
1.118     ng       2259:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2260:     my $fullname;
                   2261:     my $col_fullnames = [];
1.257     albertel 2262:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2263: 	(my $sub_result,$fullname,$col_fullnames)=
                   2264: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2265: 				 $counter);
                   2266: 	$result.=$sub_result;
1.41      ng       2267:     }
1.44      ng       2268:     $request->print($result."\n");
1.588     bisitz   2269: 
1.44      ng       2270:     # print student answer/submission
1.588     bisitz   2271:     # Options are (1) Handgraded submission only
1.44      ng       2272:     #             (2) Last submission, includes submission that is not handgraded 
                   2273:     #                  (for multi-response type part)
                   2274:     #             (3) Last submission plus the parts info
                   2275:     #             (4) The whole record for this student
1.596.2.12.2.  1(raebur 2276:3): 
1.151     albertel 2277: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2278: 	
                   2279: 	my $lastsubonly;
                   2280: 
1.588     bisitz   2281:         if ($$timestamp eq '') {
                   2282:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2283:         } else {
1.592     bisitz   2284:             $lastsubonly =
                   2285:                 '<div class="LC_grade_submissions_body">'
                   2286:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2287: 
1.151     albertel 2288: 	    my %seenparts;
1.375     albertel 2289: 	    my @part_response_id = &flatten_responseType($responseType);
                   2290: 	    foreach my $part (@part_response_id) {
1.393     albertel 2291: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2292: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2293: 
1.375     albertel 2294: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2295: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2296: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2297: 		    if (exists($seenparts{$partid})) { next; }
                   2298: 		    $seenparts{$partid}=1;
1.596.2.12.2.  8(raebur 2299:3):                     $request->print(
                   2300:3):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2301:3):                         ' <b>'.&mt('Collaborative submission by: [_1]',
                   2302:3):                                    '<a href="javascript:viewSubmitter(\''.
                   2303:3):                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2304:3):                                    '\');" target="_self">'.
                   2305:3):                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2306:3):                         '<br />');
1.151     albertel 2307: 		    next;
                   2308: 		}
                   2309: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2310: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2311:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2312:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2313:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2314:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2315:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2316: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2317: 		    next;
                   2318: 		}
1.468     albertel 2319: 		foreach my $submission (@$string) {
                   2320: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2321: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596.2.12.2.  0(raebur 2322:4): 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.151     albertel 2323: 		    # Similarity check
                   2324: 		    my $similar='';
1.596.2.2  raeburn  2325:                     my ($type,$trial,$rndseed);
                   2326:                     if ($hide eq 'rand') {
                   2327:                         $type = 'randomizetry';
                   2328:                         $trial = $record{"resource.$partid.tries"};
                   2329:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2330:                     }
1.596.2.12.2.  1(raebur 2331:3): 		    if ($env{'form.checkPlag'}) {
1.151     albertel 2332: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.596.2.12.2.  (raeburn 2333:): 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2334: 			if ($osim) {
                   2335: 			    $osim=int($osim*100.0);
1.426     albertel 2336: 			    my %old_course_desc = 
                   2337: 				&Apache::lonnet::coursedescription($ocrsid,
                   2338: 								   {'one_time' => 1});
                   2339: 
1.596.2.2  raeburn  2340:                             if ($hide eq 'anon') {
1.596     raeburn  2341:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2342:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2343:                             } else {
                   2344: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2345: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2346: 				        $osim,
                   2347: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2348: 				        $old_course_desc{'description'},
                   2349: 				        $old_course_desc{'num'},
                   2350: 				        $old_course_desc{'domain'}).
                   2351: 				    '</span></h3><blockquote><i>'.
                   2352: 				    &keywords_highlight($oessay).
                   2353: 				    '</i></blockquote><hr />';
                   2354:                             }
1.151     albertel 2355: 			}
1.150     albertel 2356: 		    }
1.596.2.2  raeburn  2357: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2358:                                          undef,$type,$trial,$rndseed);
1.596.2.12.2.  1(raebur 2359:3):                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
                   2360:3):                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2361: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2362:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2363:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2364:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2365:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2366:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2367: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2368: 			if (@$files) {
1.596.2.2  raeburn  2369:                             if ($hide eq 'anon') {
1.596     raeburn  2370:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2371:                             } else {
1.596.2.12.2.  8(raebur 2372:3):                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2373:3):                                             .'<br /><span class="LC_warning">';
                   2374:3):                                 if(@$files == 1) {
                   2375:3):                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2376:3):                                 } else {
                   2377:3):                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2378:3):                                 }
                   2379:3):                                 $lastsubonly .= '</span>';
                   2380:3): 
1.596     raeburn  2381:                                 foreach my $file (@$files) {
                   2382:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
1.596.2.12.2.  8(raebur 2383:3):                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2384:                                 }
                   2385:                             }
1.236     albertel 2386: 			    $lastsubonly.='<br />';
1.41      ng       2387: 			}
1.596.2.2  raeburn  2388:                         if ($hide eq 'anon') {
1.596.2.12.2.  8(raebur 2389:3):                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
1.596     raeburn  2390:                         } else {
1.596.2.12.2.  0(raebur 2391:4): 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2392:4):                             if ($draft) {
                   2393:4):                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2394:4):                             }
                   2395:4):                             $subval =
1.596     raeburn  2396: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2397: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596.2.12.2.  0(raebur 2398:4):                             if ($responsetype eq 'essay') {
                   2399:4):                                 $subval =~ s{\n}{<br />}g;
                   2400:4):                             }
                   2401:4):                             $lastsubonly.=$subval."\n";
1.596     raeburn  2402:                         }
1.151     albertel 2403: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2404: 			$lastsubonly.='</div>';
1.41      ng       2405: 		    }
                   2406: 		}
                   2407: 	    }
1.588     bisitz   2408: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2409: 	}
                   2410: 	$request->print($lastsubonly);
1.596.2.12.2.  1(raebur 2411:3):    if ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2412: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2413: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2414:3):     }
                   2415:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2416:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2417: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2418: 								 $env{'request.course.id'},
1.44      ng       2419: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2420:5): 								 'Apache::grades::keywords_highlight',
                   2421:5):                                                                  $usec,$identifier));
1.41      ng       2422:     }
1.120     ng       2423: 
1.121     ng       2424:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2425: 	.$udom.'" />'."\n");
1.44      ng       2426:     # return if view submission with no grading option
1.257     albertel 2427:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2428: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2429: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2430: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2431: 	$toGrade.='</div>'."\n";
1.257     albertel 2432: 	if (($env{'form.command'} eq 'submission') || 
                   2433: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2434: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2435: 	}
1.180     albertel 2436: 	$request->print($toGrade);
1.41      ng       2437: 	return;
1.180     albertel 2438:     } else {
1.468     albertel 2439: 	$request->print('</div>'."\n");
1.41      ng       2440:     }
1.33      ng       2441: 
1.121     ng       2442:     # essay grading message center
1.257     albertel 2443:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2444: 	my $result='<div class="LC_grade_message_center">';
                   2445:     
                   2446: 	$result.='<div class="LC_grade_message_center_header">'.
                   2447: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2448: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2449: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2450: 	if (scalar(@$col_fullnames) > 0) {
                   2451: 	    my $lastone = pop(@$col_fullnames);
                   2452: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2453: 	}
                   2454: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2455: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2456: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2457: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2458: 	    ',\''.$msgfor.'\');" target="_self">'.
1.596.2.12.2.  8(raebur 2459:3): 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2460: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.596.2.12.2.  8(raebur 2461:3): 	    ' <img src="'.$request->dir_config('lonIconsURL').
1.118     ng       2462: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2463: 	    '<br />&nbsp;('.
1.468     albertel 2464: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2465: 	$result.='</div></div>';
1.121     ng       2466: 	$request->print($result);
1.118     ng       2467:     }
1.41      ng       2468: 
                   2469:     my %seen = ();
                   2470:     my @partlist;
1.129     ng       2471:     my @gradePartRespid;
1.375     albertel 2472:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2473:     $request->print(
1.588     bisitz   2474:         '<div class="LC_Box">'
                   2475:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2476:     );
1.592     bisitz   2477:     $request->print(&gradeBox_start());
1.375     albertel 2478:     foreach my $part_response_id (@part_response_id) {
                   2479:     	my ($partid,$respid) = @{ $part_response_id };
                   2480: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2481: 	next if ($seen{$partid} > 0);
1.41      ng       2482: 	$seen{$partid}++;
1.393     albertel 2483: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2484: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2485: 	push(@partlist,$partid);
                   2486: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2487: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2488:     }
1.585     bisitz   2489:     $request->print(&gradeBox_end()); # </div>
                   2490:     $request->print('</div>');
1.468     albertel 2491: 
                   2492:     $request->print('<div class="LC_grade_info_links">');
                   2493:     $request->print('</div>');
                   2494: 
1.45      ng       2495:     $result='<input type="hidden" name="partlist'.$counter.
                   2496: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2497:     $result.='<input type="hidden" name="gradePartRespid'.
                   2498: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2499:     my $ctr = 0;
                   2500:     while ($ctr < scalar(@partlist)) {
                   2501: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2502: 	    $partlist[$ctr].'" />'."\n";
                   2503: 	$ctr++;
                   2504:     }
1.468     albertel 2505:     $request->print($result.''."\n");
1.41      ng       2506: 
1.441     www      2507: # Done with printing info for one student
                   2508: 
1.468     albertel 2509:     $request->print('</div>');#LC_grade_show_user
1.441     www      2510: 
                   2511: 
1.41      ng       2512:     # print end of form
                   2513:     if ($counter == $total) {
1.592     bisitz   2514:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2515: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2516: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2517: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2518: 	my $ntstu ='<select name="NTSTU">'.
                   2519: 	    '<option>1</option><option>2</option>'.
                   2520: 	    '<option>3</option><option>5</option>'.
                   2521: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2522: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2523: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2524:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2525: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2526: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2527: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2528: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2529:         $endform.='<span class="LC_warning">'.
                   2530:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2531:                   '</span>'."\n" ;
1.349     albertel 2532:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2533:             "' name='increment' />";
1.485     albertel 2534: 	$endform.='</td></tr></table></form>';
1.324     albertel 2535: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2536: 	$request->print($endform);
                   2537:     }
                   2538:     return '';
1.38      ng       2539: }
                   2540: 
1.464     albertel 2541: sub check_collaborators {
                   2542:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2543:     my ($result,@col_fullnames);
                   2544:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2545:     foreach my $part (keys(%$handgrade)) {
                   2546: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2547: 					'.maxcollaborators',
                   2548: 					$symb,$udom,$uname);
                   2549: 	next if ($ncol <= 0);
                   2550: 	$part =~ s/\_/\./g;
                   2551: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2552: 	my (@good_collaborators, @bad_collaborators);
                   2553: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2554: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2555: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2556: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2557: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2558: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2559: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2560: 	    # Doing this grep allows 'fuzzy' specification
                   2561: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2562: 			       keys(%$classlist));
                   2563: 	    if (! scalar(@matches)) {
                   2564: 		push(@bad_collaborators, $possible_collaborator);
                   2565: 	    } else {
                   2566: 		push(@good_collaborators, @matches);
                   2567: 	    }
                   2568: 	}
                   2569: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2570: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2571: 	    foreach my $name (@good_collaborators) {
                   2572: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2573: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2574: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2575: 	    }
1.596.2.4  raeburn  2576: 	    $result.='</ol><br />'."\n";
1.466     albertel 2577: 	    my ($part)=split(/\./,$part);
1.464     albertel 2578: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2579: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2580: 		"\n";
                   2581: 	}
                   2582: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2583: 	    $result.='<div class="LC_warning">';
1.464     albertel 2584: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2585: 	    $result .= '</div>';
                   2586: 	}         
                   2587: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2588: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2589: 	    $result .= &mt('This student has submitted too many '.
                   2590: 		'collaborators.  Maximum is [_1].',$ncol);
                   2591: 	    $result .= '</div>';
                   2592: 	}
                   2593:     }
                   2594:     return ($result,$fullname,\@col_fullnames);
                   2595: }
                   2596: 
1.44      ng       2597: #--- Retrieve the last submission for all the parts
1.38      ng       2598: sub get_last_submission {
1.119     ng       2599:     my ($returnhash)=@_;
1.596     raeburn  2600:     my (@string,$timestamp,%lasthidden);
1.119     ng       2601:     if ($$returnhash{'version'}) {
1.46      ng       2602: 	my %lasthash=();
                   2603: 	my ($version);
1.119     ng       2604: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2605: 	    foreach my $key (sort(split(/\:/,
                   2606: 					$$returnhash{$version.':keys'}))) {
                   2607: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2608: 		$timestamp = 
1.545     raeburn  2609: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2610: 	    }
                   2611: 	}
1.596.2.2  raeburn  2612:         my (%typeparts,%randombytry);
1.596     raeburn  2613:         my $showsurv = 
                   2614:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2615:         foreach my $key (sort(keys(%lasthash))) {
                   2616:             if ($key =~ /\.type$/) {
                   2617:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2618:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2619:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2620:                     my ($ign,@parts) = split(/\./,$key);
                   2621:                     pop(@parts);
1.596.2.3  raeburn  2622:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2623:                     if ($lasthash{$key} eq 'randomizetry') {
                   2624:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2625:                     } else {
                   2626:                         unless ($showsurv) {
                   2627:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2628:                         }
1.596     raeburn  2629:                     }
                   2630:                     delete($lasthash{$key});
                   2631:                 }
                   2632:             }
                   2633:         }
                   2634:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2635:         my @randomize = keys(%randombytry);
1.397     albertel 2636: 	foreach my $key (keys(%lasthash)) {
                   2637: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2638:             my $hide;
                   2639:             if (@hidden) {
                   2640:                 foreach my $id (@hidden) {
                   2641:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2642:                         $hide = 'anon';
1.596     raeburn  2643:                         last;
                   2644:                     }
                   2645:                 }
                   2646:             }
1.596.2.2  raeburn  2647:             unless ($hide) {
                   2648:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2649:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2650:                         if ($key =~ /^\Q$id\E/) {
                   2651:                             $hide = 'rand';
                   2652:                             last;
                   2653:                         }
                   2654:                     }
                   2655:                 }
                   2656:             }
1.397     albertel 2657: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  0(raebur 2658:4): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
                   2659:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2660:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2661:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2662: 	}
                   2663:     }
1.397     albertel 2664:     if (!@string) {
                   2665: 	$string[0] =
1.539     riegler  2666: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2667:     }
                   2668:     return (\@string,\$timestamp);
1.38      ng       2669: }
1.35      ng       2670: 
1.44      ng       2671: #--- High light keywords, with style choosen by user.
1.38      ng       2672: sub keywords_highlight {
1.44      ng       2673:     my $string    = shift;
1.257     albertel 2674:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2675:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2676:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2677:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2678:     foreach my $keyword (@keylist) {
                   2679: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2680:     }
                   2681:     return $string;
1.38      ng       2682: }
1.36      ng       2683: 
1.596.2.12.2.  (raeburn 2684:): # For Tasks provide a mechanism to display previous version for one specific student
                   2685:): 
                   2686:): sub show_previous_task_version {
                   2687:):     my ($request,$symb) = @_;
                   2688:):     if ($symb eq '') {
          8(raebur 2689:4):         $request->print(
                   2690:4):             '<span class="LC_error">'.
                   2691:4):             &mt('Unable to handle ambiguous references.').
                   2692:4):             '</span>');
          (raeburn 2693:):         return '';
                   2694:):     }
                   2695:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2696:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2697:):     if (!&canview($usec)) {
          8(raebur 2698:4):         $request->print('<span class="LC_warning">'.
                   2699:4):                         &mt('Unable to view previous version for requested student.').
                   2700:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2701:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2702:4):                         '</span>');
          (raeburn 2703:):         return;
                   2704:):     }
                   2705:):     my $mode = 'both';
                   2706:):     my $isTask = ($symb =~/\.task$/);
                   2707:):     if ($isTask) {
                   2708:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2709:):             if ($env{'form.fullname'} eq '') {
                   2710:):                 $env{'form.fullname'} =
                   2711:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2712:):             }
                   2713:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2714:):             $request->print("\n\n".
                   2715:):                             '<div class="LC_grade_show_user">'.
                   2716:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2717:):                             '</h2>'."\n");
                   2718:):             &Apache::lonxml::clear_problem_counter();
                   2719:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2720:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2721:):             $request->print("\n</div>");
                   2722:):         }
                   2723:):     }
                   2724:):     return;
                   2725:): }
                   2726:): 
                   2727:): sub choose_task_version_form {
                   2728:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2729:):     my $isTask = ($symb =~/\.task$/);
                   2730:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2731:):     if ($isTask) {
                   2732:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2733:):                                               $udom,$uname);
                   2734:):         if (($record{'resource.0.version'} eq '') ||
                   2735:):             ($record{'resource.0.version'} < 2)) {
                   2736:):             return ($record{'resource.0.version'},
                   2737:):                     $record{'resource.0.version'},$result,$js);
                   2738:):         } else {
                   2739:):             $current = $record{'resource.0.version'};
                   2740:):         }
                   2741:):         if ($env{'form.previousversion'}) {
                   2742:):             $displayed = $env{'form.previousversion'};
                   2743:):             $rowtitle = &mt('Choose another version:')
                   2744:):         } else {
                   2745:):             $displayed = $current;
                   2746:):             $rowtitle = &mt('Show earlier version:');
                   2747:):         }
                   2748:):         $result = '<div class="LC_left_float">';
                   2749:):         my $list;
                   2750:):         my $numversions = 0;
                   2751:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2752:):             if ($i == $current) {
                   2753:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   2754:):                     next;
                   2755:):                 } else {
                   2756:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2757:):                     $numversions ++;
                   2758:):                 }
                   2759:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2760:):                 unless ($i == $env{'form.previousversion'}) {
                   2761:):                     $numversions ++;
                   2762:):                 }
                   2763:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2764:):             }
                   2765:):         }
                   2766:):         if ($numversions) {
                   2767:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2768:):             $result .=
                   2769:):                 '<form name="getprev" method="post" action=""'.
                   2770:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2771:):                 &Apache::loncommon::start_data_table().
                   2772:):                 &Apache::loncommon::start_data_table_row().
                   2773:):                 '<th align="left">'.$rowtitle.'</th>'.
                   2774:):                 '<td><select name="version">'.
                   2775:):                 '<option>'.&mt('Select').'</option>'.
                   2776:):                 $list.
                   2777:):                 '</select></td>'.
                   2778:):                 &Apache::loncommon::end_data_table_row();
                   2779:):             unless ($nomenu) {
                   2780:):                 $result .= &Apache::loncommon::start_data_table_row().
                   2781:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2782:):                 '<td><span class="LC_nobreak">'.
                   2783:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2784:):                 &mt('Yes').'</label>'.
                   2785:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2786:):                 '</span></td>'.
                   2787:):                 &Apache::loncommon::end_data_table_row();
                   2788:):             }
                   2789:):             $result .=
                   2790:):                 &Apache::loncommon::start_data_table_row().
                   2791:):                 '<th align="left">&nbsp;</th>'.
                   2792:):                 '<td>'.
                   2793:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2794:):                 '</td>'.
                   2795:):                 &Apache::loncommon::end_data_table_row().
                   2796:):                 &Apache::loncommon::end_data_table().
                   2797:):                 '</form>';
                   2798:):             $js = &previous_display_javascript($nomenu,$current);
                   2799:):         } elsif ($displayed && $nomenu) {
                   2800:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2801:):         } else {
                   2802:):             $result .= &mt('No previous versions to show for this student');
                   2803:):         }
                   2804:):         $result .= '</div>';
                   2805:):     }
                   2806:):     return ($current,$displayed,$result,$js);
                   2807:): }
                   2808:): 
                   2809:): sub previous_display_javascript {
                   2810:):     my ($nomenu,$current) = @_;
                   2811:):     my $js = <<"JSONE";
                   2812:): <script type="text/javascript">
                   2813:): // <![CDATA[
                   2814:): function previousVersion(uname,udom,symb) {
                   2815:):     var current = '$current';
                   2816:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2817:):     var prevstr = new RegExp("^\\\\d+\$");
                   2818:):     if (!prevstr.test(version)) {
                   2819:):         return false;
                   2820:):     }
                   2821:):     var url = '';
                   2822:):     if (version == current) {
                   2823:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2824:):     } else {
                   2825:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2826:):     }
                   2827:): JSONE
                   2828:):     if ($nomenu) {
                   2829:):         $js .= <<"JSTWO";
                   2830:):     document.location.href = url;
                   2831:): JSTWO
                   2832:):     } else {
                   2833:):         $js .= <<"JSTHREE";
                   2834:):     var newwin = 0;
                   2835:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2836:):         if (document.getprev.prevwin[i].checked == true) {
                   2837:):             newwin = document.getprev.prevwin[i].value;
                   2838:):         }
                   2839:):     }
                   2840:):     if (newwin == 1) {
                   2841:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2842:):         url = url+'&inhibitmenu=yes';
                   2843:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2844:):             previousWin = window.open(url,'',options,1);
                   2845:):         } else {
                   2846:):             previousWin.location.href = url;
                   2847:):         }
                   2848:):         previousWin.focus();
                   2849:):         return false;
                   2850:):     } else {
                   2851:):         document.location.href = url;
                   2852:):         return false;
                   2853:):     }
                   2854:): JSTHREE
                   2855:):     }
                   2856:):     $js .= <<"ENDJS";
                   2857:):     return false;
                   2858:): }
                   2859:): // ]]>
                   2860:): </script>
                   2861:): ENDJS
                   2862:): 
                   2863:): }
                   2864:): 
1.44      ng       2865: #--- Called from submission routine
1.38      ng       2866: sub processHandGrade {
1.41      ng       2867:     my ($request) = shift;
1.596.2.12.2.  (raeburn 2868:):     my ($symb)   = &get_symb($request);
1.324     albertel 2869:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2870:     my $button = $env{'form.gradeOpt'};
                   2871:     my $ngrade = $env{'form.NCT'};
                   2872:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2873:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2874:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2875: 
1.44      ng       2876:     if ($button eq 'Save & Next') {
                   2877: 	my $ctr = 0;
                   2878: 	while ($ctr < $ngrade) {
1.257     albertel 2879: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 2880:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2881:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2882: 	    if ($errorflag eq 'no_score') {
                   2883: 		$ctr++;
                   2884: 		next;
                   2885: 	    }
1.104     albertel 2886: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 2887:4):                 $request->print(
                   2888:4):                     '<span class="LC_error">'
                   2889:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2890:4):                    .'</span>');
1.104     albertel 2891: 		$ctr++;
                   2892: 		next;
                   2893: 	    }
1.596.2.12.2.  1(raebur 2894:5):             if ($numhidden) {
                   2895:5):                 $request->print(
                   2896:5):                     '<span class="LC_info">'
                   2897:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2898:5):                    .'</span><br />');
                   2899:5):             }
1.257     albertel 2900: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2901: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2902: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2903:             my ($feedurl,$showsymb) =
                   2904: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2905: 	    my $messagetail;
1.62      albertel 2906: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2907: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2908: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2909: 		$subject.=' ['.$restitle.']';
1.44      ng       2910: 		my (@msgnum) = split(/,/,$includemsg);
                   2911: 		foreach (@msgnum) {
1.257     albertel 2912: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2913: 		}
1.80      ng       2914: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2915: 		if ($env{'form.withgrades'.$ctr}) {
                   2916: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2917: 		    $messagetail = " for <a href=\"".
1.418     albertel 2918: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2919: 		}
                   2920: 		$msgstatus = 
                   2921:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2922: 						     $message.$messagetail,
1.418     albertel 2923:                                                      undef,$feedurl,undef,
1.386     raeburn  2924:                                                      undef,undef,$showsymb,
                   2925:                                                      $restitle);
1.574     bisitz   2926: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2927: 				$msgstatus.'<br />');
1.44      ng       2928: 	    }
1.257     albertel 2929: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2930: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2931: 		foreach my $collabstr (@collabstrs) {
                   2932: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2933: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2934: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2935: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2936: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2937: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2938: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2939: 			    next;
1.418     albertel 2940: 			} elsif ($message ne '') {
                   2941: 			    my ($baseurl,$showsymb) = 
                   2942: 				&get_feedurl_and_symb($symb,$collaborator,
                   2943: 						      $udom);
                   2944: 			    if ($env{'form.withgrades'.$ctr}) {
                   2945: 				$messagetail = " for <a href=\"".
1.386     raeburn  2946:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2947: 			    }
1.418     albertel 2948: 			    $msgstatus = 
                   2949: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2950: 			}
1.44      ng       2951: 		    }
                   2952: 		}
                   2953: 	    }
                   2954: 	    $ctr++;
                   2955: 	}
                   2956:     }
                   2957: 
1.257     albertel 2958:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2959: 	# Keywords sorted in alphabatical order
1.257     albertel 2960: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2961: 	my %keyhash = ();
1.257     albertel 2962: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2963: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2964: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2965: 	$env{'form.keywords'} = join(' ',@keywords);
                   2966: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2967: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2968: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2969: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2970: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2971: 
                   2972: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2973: 	# New messages are saved in env for the next student.
1.119     ng       2974: 	# All messages are saved in nohist_handgrade.db
                   2975: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2976: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2977: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2978: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2979: 		$idx++;
                   2980: 	    }
                   2981: 	    $ctr++;
1.41      ng       2982: 	}
1.119     ng       2983: 	$ctr = 0;
                   2984: 	while ($ctr < $ngrade) {
1.257     albertel 2985: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2986: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2987: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2988: 		$idx++;
                   2989: 	    }
                   2990: 	    $ctr++;
1.41      ng       2991: 	}
1.257     albertel 2992: 	$env{'form.savemsgN'} = --$idx;
                   2993: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2994: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2995: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2996:     }
1.44      ng       2997:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2998:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2999:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3000: 	my ($ctr,$total) = (0,0);
                   3001: 	while ($ctr < $ngrade) {
1.257     albertel 3002: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3003: 	    $ctr++;
                   3004: 	}
1.257     albertel 3005: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3006: 	$ctr = 0;
                   3007: 	while ($ctr < $total) {
1.257     albertel 3008: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3009: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3010: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       3011: 	    &submission($request,$ctr,$total-1);
1.41      ng       3012: 	    $ctr++;
                   3013: 	}
                   3014: 	return '';
                   3015:     }
1.36      ng       3016: 
1.121     ng       3017: # Go directly to grade student - from submission or link from chart page
1.120     ng       3018:     if ($button eq 'Grade Student') {
1.324     albertel 3019: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 3020: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   3021: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3022: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       3023: 	&submission($request,0,0);
                   3024: 	return '';
                   3025:     }
                   3026: 
1.44      ng       3027:     # Get the next/previous one or group of students
1.257     albertel 3028:     my $firststu = $env{'form.unamedom0'};
                   3029:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3030:     my $ctr = 2;
1.41      ng       3031:     while ($laststu eq '') {
1.257     albertel 3032: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3033: 	$ctr++;
                   3034: 	$laststu = $firststu if ($ctr > $ngrade);
                   3035:     }
1.44      ng       3036: 
1.41      ng       3037:     my (@parsedlist,@nextlist);
                   3038:     my ($nextflg) = 0;
1.524     raeburn  3039:     foreach my $item (sort 
1.294     albertel 3040: 	     {
                   3041: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3042: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3043: 		 }
                   3044: 		 return $a cmp $b;
                   3045: 	     } (keys(%$fullname))) {
1.41      ng       3046: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3047: 	    push(@parsedlist,$item);
1.41      ng       3048: 	}
1.524     raeburn  3049: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3050: 	if ($button eq 'Previous') {
1.524     raeburn  3051: 	    last if ($item eq $firststu);
                   3052: 	    push(@parsedlist,$item);
1.41      ng       3053: 	}
                   3054:     }
                   3055:     $ctr = 0;
                   3056:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3057:     my $res_error;
                   3058:     my ($partlist) = &response_type($symb,\$res_error);
                   3059:     if ($res_error) {
                   3060:         $request->print(&navmap_errormsg());
                   3061:         return;
                   3062:     }
1.41      ng       3063:     foreach my $student (@parsedlist) {
1.257     albertel 3064: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3065: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3066: 	
                   3067: 	if ($submitonly eq 'queued') {
                   3068: 	    my %queue_status = 
                   3069: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3070: 							$udom,$uname);
                   3071: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3072: 	}
                   3073: 
1.156     albertel 3074: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3075: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3076: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3077: 	    my $submitted = 0;
1.248     albertel 3078: 	    my $ungraded = 0;
                   3079: 	    my $incorrect = 0;
1.524     raeburn  3080: 	    foreach my $item (keys(%status)) {
                   3081: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3082: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3083: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3084: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3085: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3086: 		    $submitted = 0;
                   3087: 		}
1.41      ng       3088: 	    }
1.156     albertel 3089: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3090: 				     $submitonly eq 'incorrect' ||
                   3091: 				     $submitonly eq 'graded'));
1.248     albertel 3092: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3093: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3094: 	}
1.524     raeburn  3095: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3096: 	last if ($ctr == $ntstu);
1.41      ng       3097: 	$ctr++;
                   3098:     }
1.36      ng       3099: 
1.41      ng       3100:     $ctr = 0;
                   3101:     my $total = scalar(@nextlist)-1;
1.39      ng       3102: 
1.524     raeburn  3103:     foreach (sort(@nextlist)) {
1.41      ng       3104: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3105: 	$env{'form.student'}  = $uname;
                   3106: 	$env{'form.userdom'}  = $udom;
                   3107: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       3108: 	&submission($request,$ctr,$total);
                   3109: 	$ctr++;
                   3110:     }
                   3111:     if ($total < 0) {
1.485     albertel 3112: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  3113: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 3114: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 3115: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       3116: 	$request->print($the_end);
                   3117:     }
                   3118:     return '';
1.38      ng       3119: }
1.36      ng       3120: 
1.44      ng       3121: #---- Save the score and award for each student, if changed
1.38      ng       3122: sub saveHandGrade {
1.324     albertel 3123:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3124:     my @version_parts;
1.104     albertel 3125:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3126: 					   $env{'request.course.id'});
1.104     albertel 3127:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3128:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3129:     my @parts_graded;
1.77      ng       3130:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3131:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3132:     my %aggregate = ();
                   3133:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3134:5):     if ($env{'form.HIDE'.$newflg}) {
                   3135:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3136:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3137:5):         $totchg += $numchgs;
                   3138:5):     }
1.301     albertel 3139:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3140:     foreach my $new_part (@parts) {
1.337     banghart 3141: 	#collaborator ($submi may vary for different parts
1.259     banghart 3142: 	if ($submitter && $new_part ne $part) { next; }
                   3143: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3144: 	if ($dropMenu eq 'excused') {
1.259     banghart 3145: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3146: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3147: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3148: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3149: 		}
1.364     banghart 3150: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3151: 	    }
1.125     ng       3152: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3153: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3154: 	    foreach my $key (keys(%record)) {
1.259     banghart 3155: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3156: 	    }
1.259     banghart 3157: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3158: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3159:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3160: 
                   3161:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3162: 					       [$new_part]);
                   3163:             my $aggtries =$totaltries;
1.269     raeburn  3164:             if ($last_resets{$new_part}) {
1.270     albertel 3165:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3166: 					   $new_part);
1.269     raeburn  3167:             }
1.270     albertel 3168: 
                   3169:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3170:             if ($aggtries > 0) {
1.327     albertel 3171:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3172:                 $aggregateflag = 1;
                   3173:             }
1.125     ng       3174: 	} elsif ($dropMenu eq '') {
1.259     banghart 3175: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3176: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3177: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3178: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3179: 		next;
                   3180: 	    }
1.259     banghart 3181: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3182: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3183: 	    my $partial= $pts/$wgt;
1.259     banghart 3184: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3185: 		#do not update score for part if not changed.
1.346     banghart 3186:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3187: 		next;
1.251     banghart 3188: 	    } else {
1.524     raeburn  3189: 	        push(@parts_graded,$new_part);
1.153     albertel 3190: 	    }
1.259     banghart 3191: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3192: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3193: 	    }
1.259     banghart 3194: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3195: 	    if ($partial == 0) {
1.153     albertel 3196: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3197: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3198: 		}
1.41      ng       3199: 	    } else {
1.153     albertel 3200: 		if ($record{$reckey} ne 'correct_by_override') {
                   3201: 		    $newrecord{$reckey} = 'correct_by_override';
                   3202: 		}
                   3203: 	    }	    
                   3204: 	    if ($submitter && 
1.259     banghart 3205: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3206: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3207: 	    }
1.259     banghart 3208: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3209: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3210: 	}
1.259     banghart 3211: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3212: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3213: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3214: 	        $dropMenu eq 'reset status')
                   3215: 	   {
1.524     raeburn  3216: 	    push(@version_parts,$new_part);
1.259     banghart 3217: 	}
1.41      ng       3218:     }
1.301     albertel 3219:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3220:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3221: 
1.344     albertel 3222:     if (%newrecord) {
                   3223:         if (@version_parts) {
1.364     banghart 3224:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3225:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3226: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3227: 	    foreach my $new_part (@version_parts) {
                   3228: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3229: 				$new_part,\%newrecord);
                   3230: 	    }
1.259     banghart 3231:         }
1.44      ng       3232: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3233: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3234: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3235: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3236:     }
1.269     raeburn  3237:     if ($aggregateflag) {
                   3238:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3239: 			      $cdom,$cnum);
1.269     raeburn  3240:     }
1.596.2.12.2.  1(raebur 3241:5):     return ('',$pts,$wgt,$totchg);
                   3242:5): }
                   3243:5): 
                   3244:5): sub makehidden {
                   3245:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3246:5):     return unless (ref($record) eq 'HASH');
                   3247:5):     my %modified;
                   3248:5):     my $numchanged = 0;
                   3249:5):     if (exists($record->{$version.':keys'})) {
                   3250:5):         my $partsregexp = $parts;
                   3251:5):         $partsregexp =~ s/,/|/g;
                   3252:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3253:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3254:5):                  my $item = $1;
                   3255:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3256:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3257:5):                  }
                   3258:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3259:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3260:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3261:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3262:5):             }
                   3263:5):         }
                   3264:5):         if (keys(%modified)) {
                   3265:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3266:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3267:5):                 $numchanged ++;
                   3268:5):             }
                   3269:5):         }
                   3270:5):     }
                   3271:5):     return $numchanged;
1.36      ng       3272: }
1.322     albertel 3273: 
1.380     albertel 3274: sub check_and_remove_from_queue {
                   3275:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3276:     my @ungraded_parts;
                   3277:     foreach my $part (@{$parts}) {
                   3278: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3279: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3280: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3281: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3282: 		) {
                   3283: 	    push(@ungraded_parts, $part);
                   3284: 	}
                   3285:     }
                   3286:     if ( !@ungraded_parts ) {
                   3287: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3288: 					       $cnum,$domain,$stuname);
                   3289:     }
                   3290: }
                   3291: 
1.337     banghart 3292: sub handback_files {
                   3293:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3294:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3295:     my $res_error;
                   3296:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3297:     if ($res_error) {
                   3298:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3299:         return;
                   3300:     }
1.596.2.4  raeburn  3301:     my @handedback;
                   3302:     my $file_msg;
1.375     albertel 3303:     my @part_response_id = &flatten_responseType($responseType);
                   3304:     foreach my $part_response_id (@part_response_id) {
                   3305:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3306: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3307:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3308:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3309:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3310: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3311:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3312:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3313:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3314:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3315: 		        &file_name_version_ext($answer_file);
1.355     banghart 3316: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3317:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3318:):                     my ($dir_list,$listerror) =
                   3319:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3320:):                                                  $domain,$stuname,$getpropath);
                   3321:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3322:3):                     # fix filename
1.355     banghart 3323:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3324:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3325:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3326:             	                                $save_file_name);
1.337     banghart 3327:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3328:                         $request->print('<br /><span class="LC_error">'.
                   3329:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3330:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3331:                                         '</span>');
1.356     banghart 3332:                     } else {
1.360     banghart 3333:                         # mark the file as read only
1.596.2.4  raeburn  3334:                         push(@handedback,$save_file_name);
1.367     albertel 3335: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3336: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3337: 			}
                   3338:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3339: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3340: 
1.337     banghart 3341:                     }
1.596.2.12.2.  3(raebur 3342: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 3343:                 }
                   3344:             }
                   3345:         }
1.596.2.4  raeburn  3346:     }
                   3347:     if (@handedback > 0) {
                   3348:         $request->print('<br />');
                   3349:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3350:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3351:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3352:         my ($subject,$message);
                   3353:         if (scalar(@handedback) == 1) {
                   3354:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3355:         } else {
                   3356:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3357:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3358:         }
                   3359:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3360:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3361:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3362:         my ($feedurl,$showsymb) =
                   3363:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3364:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3365:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3366:         my $msgstatus =
                   3367:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3368:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3369:                  $restitle);
                   3370:         if ($msgstatus) {
                   3371:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3372:         }
                   3373:     }
1.338     banghart 3374:     return;
1.337     banghart 3375: }
                   3376: 
1.418     albertel 3377: sub get_feedurl_and_symb {
                   3378:     my ($symb,$uname,$udom) = @_;
                   3379:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3380:     $url = &Apache::lonnet::clutter($url);
                   3381:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3382: 					$symb,$udom,$uname);
                   3383:     if ($encrypturl =~ /^yes$/i) {
                   3384: 	&Apache::lonenc::encrypted(\$url,1);
                   3385: 	&Apache::lonenc::encrypted(\$symb,1);
                   3386:     }
                   3387:     return ($url,$symb);
                   3388: }
                   3389: 
1.313     banghart 3390: sub get_submitted_files {
                   3391:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3392:     my @files;
                   3393:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3394:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3395:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3396:     	    push(@files,$file_url.$file);
                   3397:         }
                   3398:     }
                   3399:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3400:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3401:     }
                   3402:     return (\@files);
                   3403: }
1.322     albertel 3404: 
1.269     raeburn  3405: # ----------- Provides number of tries since last reset.
                   3406: sub get_num_tries {
                   3407:     my ($record,$last_reset,$part) = @_;
                   3408:     my $timestamp = '';
                   3409:     my $num_tries = 0;
                   3410:     if ($$record{'version'}) {
                   3411:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3412:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3413:                 $timestamp = $$record{$version.':timestamp'};
                   3414:                 if ($timestamp > $last_reset) {
                   3415:                     $num_tries ++;
                   3416:                 } else {
                   3417:                     last;
                   3418:                 }
                   3419:             }
                   3420:         }
                   3421:     }
                   3422:     return $num_tries;
                   3423: }
                   3424: 
                   3425: # ----------- Determine decrements required in aggregate totals 
                   3426: sub decrement_aggs {
                   3427:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3428:     my %decrement = (
                   3429:                         attempts => 0,
                   3430:                         users => 0,
                   3431:                         correct => 0
                   3432:                     );
                   3433:     $decrement{'attempts'} = $aggtries;
                   3434:     if ($solvedstatus =~ /^correct/) {
                   3435:         $decrement{'correct'} = 1;
                   3436:     }
                   3437:     if ($aggtries == $totaltries) {
                   3438:         $decrement{'users'} = 1;
                   3439:     }
1.524     raeburn  3440:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3441:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3442:     }
                   3443:     return;
                   3444: }
                   3445: 
                   3446: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3447: sub get_last_resets {
1.270     albertel 3448:     my ($symb,$courseid,$partids) =@_;
                   3449:     my %last_resets;
1.269     raeburn  3450:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3451:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3452:     my @keys;
                   3453:     foreach my $part (@{$partids}) {
                   3454: 	push(@keys,"$symb\0$part\0resettime");
                   3455:     }
                   3456:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3457: 				     $cdom,$cname);
                   3458:     foreach my $part (@{$partids}) {
                   3459: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3460:     }
1.270     albertel 3461:     return %last_resets;
1.269     raeburn  3462: }
                   3463: 
1.251     banghart 3464: # ----------- Handles creating versions for portfolio files as answers
                   3465: sub version_portfiles {
1.343     banghart 3466:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3467:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3468:     my @returned_keys;
1.255     banghart 3469:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3470:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3471:     foreach my $key (keys(%$record)) {
1.259     banghart 3472:         my $new_portfiles;
1.263     banghart 3473:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3474:             my @versioned_portfiles;
1.367     albertel 3475:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3476:             foreach my $file (@portfiles) {
1.306     banghart 3477:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3478:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3479: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3480: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3481:):                 my $getpropath = 1;
                   3482:):                 my ($dir_list,$listerror) =
                   3483:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3484:):                                              $stu_name,$getpropath);
                   3485:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3486:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3487:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3488:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3489:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3490:                         [$directory.$new_answer],
1.306     banghart 3491:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3492:                 }
1.252     banghart 3493:             }
1.343     banghart 3494:             $$record{$key} = join(',',@versioned_portfiles);
                   3495:             push(@returned_keys,$key);
1.251     banghart 3496:         }
                   3497:     } 
1.343     banghart 3498:     return (@returned_keys);   
1.305     banghart 3499: }
                   3500: 
1.307     banghart 3501: sub get_next_version {
1.341     banghart 3502:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3503:     my $version;
1.596.2.12.2.  (raeburn 3504:):     if (ref($dir_list) eq 'ARRAY') {
                   3505:):         foreach my $row (@{$dir_list}) {
                   3506:):             my ($file) = split(/\&/,$row,2);
                   3507:):             my ($file_name,$file_version,$file_ext) =
                   3508:): 	        &file_name_version_ext($file);
                   3509:):             if (($file_name eq $answer_name) && 
                   3510:): 	        ($file_ext eq $answer_ext)) {
                   3511:):                 # gets here if filename and extension match, 
                   3512:):                 # regardless of version
1.307     banghart 3513:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3514:):                     # a versioned file is found  so save it for later
                   3515:):                     if ($file_version > $version) {
                   3516:): 		        $version = $file_version;
                   3517:):                     }
1.307     banghart 3518: 	        }
                   3519:             }
                   3520:         }
1.596.2.12.2.  (raeburn 3521:):     }
1.307     banghart 3522:     $version ++;
                   3523:     return($version);
                   3524: }
                   3525: 
1.305     banghart 3526: sub version_selected_portfile {
1.306     banghart 3527:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3528:     my ($answer_name,$answer_ver,$answer_ext) =
                   3529:         &file_name_version_ext($file_name);
                   3530:     my $new_answer;
                   3531:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3532:     if($env{'form.copy'} eq '-1') {
                   3533:         $new_answer = 'problem getting file';
                   3534:     } else {
                   3535:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3536:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3537:                             $stu_name,$domain,'copy',
                   3538: 		        '/portfolio'.$directory.$new_answer);
                   3539:     }    
                   3540:     return ($new_answer);
1.251     banghart 3541: }
                   3542: 
1.304     albertel 3543: sub file_name_version_ext {
                   3544:     my ($file)=@_;
                   3545:     my @file_parts = split(/\./, $file);
                   3546:     my ($name,$version,$ext);
                   3547:     if (@file_parts > 1) {
                   3548: 	$ext=pop(@file_parts);
                   3549: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3550: 	    $version=pop(@file_parts);
                   3551: 	}
                   3552: 	$name=join('.',@file_parts);
                   3553:     } else {
                   3554: 	$name=join('.',@file_parts);
                   3555:     }
                   3556:     return($name,$version,$ext);
                   3557: }
                   3558: 
1.44      ng       3559: #--------------------------------------------------------------------------------------
                   3560: #
                   3561: #-------------------------- Next few routines handles grading by section or whole class
                   3562: #
                   3563: #--- Javascript to handle grading by section or whole class
1.42      ng       3564: sub viewgrades_js {
                   3565:     my ($request) = shift;
                   3566: 
1.539     riegler  3567:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3568:6):     &js_escape(\$alertmsg);
1.41      ng       3569:     $request->print(<<VIEWJAVASCRIPT);
                   3570: <script type="text/javascript" language="javascript">
1.45      ng       3571:    function writePoint(partid,weight,point) {
1.125     ng       3572: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3573: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3574: 	if (point == "textval") {
1.125     ng       3575: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3576: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3577: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3578: 		var resetbox = false;
                   3579: 		for (var i=0; i<radioButton.length; i++) {
                   3580: 		    if (radioButton[i].checked) {
                   3581: 			textbox.value = i;
                   3582: 			resetbox = true;
                   3583: 		    }
                   3584: 		}
                   3585: 		if (!resetbox) {
                   3586: 		    textbox.value = "";
                   3587: 		}
                   3588: 		return;
                   3589: 	    }
1.109     matthew  3590: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3591: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3592: 				   ") greater than the weight for the part. Accept?");
                   3593: 		if (resp == false) {
                   3594: 		    textbox.value = "";
                   3595: 		    return;
                   3596: 		}
                   3597: 	    }
1.42      ng       3598: 	    for (var i=0; i<radioButton.length; i++) {
                   3599: 		radioButton[i].checked=false;
1.109     matthew  3600: 		if (parseFloat(point) == i) {
1.42      ng       3601: 		    radioButton[i].checked=true;
                   3602: 		}
                   3603: 	    }
1.41      ng       3604: 
1.42      ng       3605: 	} else {
1.125     ng       3606: 	    textbox.value = parseFloat(point);
1.42      ng       3607: 	}
1.41      ng       3608: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3609: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3610: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3611: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3612: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3613: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3614: 	    if (saveval != "correct") {
                   3615: 		scorename.value = point;
1.43      ng       3616: 		if (selname[0].selected != true) {
                   3617: 		    selname[0].selected = true;
                   3618: 		}
1.42      ng       3619: 	    }
                   3620: 	}
1.125     ng       3621: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3622:     }
                   3623: 
                   3624:     function writeRadText(partid,weight) {
1.125     ng       3625: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3626: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3627:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3628: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3629: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3630: 	    for (var i=0; i<radioButton.length; i++) {
                   3631: 		radioButton[i].checked=false;
                   3632: 
                   3633: 	    }
                   3634: 	    textbox.value = "";
                   3635: 
                   3636: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3637: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3638: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3639: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3640: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3641: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3642: 		if ((saveval != "correct") || override) {
1.42      ng       3643: 		    scorename.value = "";
1.125     ng       3644: 		    if (selval[1].selected) {
                   3645: 			selname[1].selected = true;
                   3646: 		    } else {
                   3647: 			selname[2].selected = true;
                   3648: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3649: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3650: 		    }
1.42      ng       3651: 		}
                   3652: 	    }
1.43      ng       3653: 	} else {
                   3654: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3655: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3656: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3657: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3658: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3659: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3660: 		if ((saveval != "correct") || override) {
1.125     ng       3661: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3662: 		    selname[0].selected = true;
                   3663: 		}
                   3664: 	    }
                   3665: 	}	    
1.42      ng       3666:     }
                   3667: 
                   3668:     function changeSelect(partid,user) {
1.125     ng       3669: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3670: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3671: 	var point  = textbox.value;
1.125     ng       3672: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3673: 
1.109     matthew  3674: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3675: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3676: 	    textbox.value = "";
                   3677: 	    return;
                   3678: 	}
1.109     matthew  3679: 	if (parseFloat(point) > parseFloat(weight)) {
                   3680: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3681: 			       ") greater than the weight of the part. Accept?");
                   3682: 	    if (resp == false) {
                   3683: 		textbox.value = "";
                   3684: 		return;
                   3685: 	    }
                   3686: 	}
1.42      ng       3687: 	selval[0].selected = true;
                   3688:     }
                   3689: 
                   3690:     function changeOneScore(partid,user) {
1.125     ng       3691: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3692: 	if (selval[1].selected || selval[2].selected) {
                   3693: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3694: 	    if (selval[2].selected) {
                   3695: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3696: 	    }
1.269     raeburn  3697:         }
1.42      ng       3698:     }
                   3699: 
                   3700:     function resetEntry(numpart) {
                   3701: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3702: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3703: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3704: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3705: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3706: 	    for (var i=0; i<radioButton.length; i++) {
                   3707: 		radioButton[i].checked=false;
                   3708: 
                   3709: 	    }
                   3710: 	    textbox.value = "";
                   3711: 	    selval[0].selected = true;
                   3712: 
                   3713: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3714: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3715: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3716: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3717: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3718: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3719: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3720: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3721: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3722: 		if (saveselval == "excused") {
1.43      ng       3723: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3724: 		} else {
1.43      ng       3725: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3726: 		}
                   3727: 	    }
1.41      ng       3728: 	}
1.42      ng       3729:     }
                   3730: 
1.41      ng       3731: </script>
                   3732: VIEWJAVASCRIPT
1.42      ng       3733: }
                   3734: 
1.44      ng       3735: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3736: sub viewgrades {
                   3737:     my ($request) = shift;
                   3738:     &viewgrades_js($request);
1.41      ng       3739: 
1.324     albertel 3740:     my ($symb) = &get_symb($request);
1.168     albertel 3741:     #need to make sure we have the correct data for later EXT calls, 
                   3742:     #thus invalidate the cache
                   3743:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3744:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3745:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3746:     &Apache::lonnet::clear_EXT_cache_status();
                   3747: 
1.398     albertel 3748:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.596.2.12.2.  9(raebur 3749:3):     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3750: 
                   3751:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3752:     $result.=&jscriptNform($symb);
1.41      ng       3753: 
1.44      ng       3754:     #beginning of class grading form
1.442     banghart 3755:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3756:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3757: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3758: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3759: 	&build_section_inputs().
1.257     albertel 3760: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3761: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3762: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3763: 
1.596.2.12.2.  7(raebur 3764:6):     #retrieve selected groups
                   3765:6):     my (@groups,$group_display);
          8(raebur 3766:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 3767:6):     if (grep(/^all$/,@groups)) {
                   3768:6):         @groups = ('all');
                   3769:6):     } elsif (grep(/^none$/,@groups)) {
                   3770:6):         @groups = ('none');
                   3771:6):     } elsif (@groups > 0) {
                   3772:6):         $group_display = join(', ',@groups);
                   3773:6):     }
                   3774:6): 
                   3775:6):     my ($common_header,$specific_header,@sections,$section_display);
                   3776:6):     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3777:6):     if (grep(/^all$/,@sections)) {
                   3778:6):         @sections = ('all');
                   3779:6):         if ($group_display) {
                   3780:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3781:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3782:6):         } elsif (grep(/^none$/,@groups)) {
                   3783:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3784:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3785:6):         } else {
                   3786:6):             $common_header = &mt('Assign Common Grade to Class');
                   3787:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3788:6):         }
                   3789:6):     } elsif (grep(/^none$/,@sections)) {
                   3790:6):         @sections = ('none');
                   3791:6):         if ($group_display) {
                   3792:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3793:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3794:6):         } elsif (grep(/^none$/,@groups)) {
                   3795:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3796:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3797:6):         } else {
                   3798:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3799:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3800:6):         }
                   3801:6):     } else {
                   3802:6):         $section_display = join (", ",@sections);
                   3803:6):         if ($group_display) {
                   3804:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3805:6):                                  $section_display,$group_display);
                   3806:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3807:6):                                    $section_display,$group_display);
                   3808:6):         } elsif (grep(/^none$/,@groups)) {
                   3809:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3810:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3811:6):         } else {
                   3812:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3813:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3814:6):         }
1.52      albertel 3815:     }
1.596.2.12.2.  7(raebur 3816:6):     my %submit_types = &substatus_options();
                   3817:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3818:6): 
                   3819:6):     if ($env{'form.submitonly'} eq 'all') {
                   3820:6):         $result.= '<h3>'.$common_header.'</h3>';
                   3821:6):     } else {
                   3822:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   3823:6):     }
                   3824:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3825:     #radio buttons/text box for assigning points for a section or class.
                   3826:     #handles different parts of a problem
1.582     raeburn  3827:     my $res_error;
                   3828:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3829:     if ($res_error) {
                   3830:         return &navmap_errormsg();
                   3831:     }
1.42      ng       3832:     my %weight = ();
                   3833:     my $ctsparts = 0;
1.45      ng       3834:     my %seen = ();
1.375     albertel 3835:     my @part_response_id = &flatten_responseType($responseType);
                   3836:     foreach my $part_response_id (@part_response_id) {
                   3837:     	my ($partid,$respid) = @{ $part_response_id };
                   3838: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3839: 	next if $seen{$partid};
                   3840: 	$seen{$partid}++;
1.375     albertel 3841: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3842: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3843: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3844: 
1.324     albertel 3845: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3846: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3847: 	my $ctr = 0;
1.42      ng       3848: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3849: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3850: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3851: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3852: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3853: 	    $ctr++;
                   3854: 	}
1.485     albertel 3855: 	$radio.='</tr></table>';
                   3856: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3857: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3858: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3859: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 3860:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3861:3):                 '<select name="SELVAL_'.$partid.'" '.
                   3862:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3863: 		$weight{$partid}.')"> '.
1.401     albertel 3864: 	    '<option selected="selected"> </option>'.
1.485     albertel 3865: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3866: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3867: 	    '</select></td>'.
                   3868:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3869: 	$line.='<input type="hidden" name="partid_'.
                   3870: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3871: 	$line.='<input type="hidden" name="weight_'.
                   3872: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3873: 
                   3874: 	$result.=
                   3875: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3876: 	    '<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 3877: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3878: 	$ctsparts++;
1.41      ng       3879:     }
1.474     albertel 3880:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3881: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3882:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3883: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3884: 
1.44      ng       3885:     #table listing all the students in a section/class
                   3886:     #header of table
1.596.2.12.2.  7(raebur 3887:6):     if ($env{'form.submitonly'} eq 'all') { 
                   3888:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   3889:6):     } else {
                   3890:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   3891:6):     }
                   3892:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3893: 	      &Apache::loncommon::start_data_table_header_row().
                   3894: 	      '<th>'.&mt('No.').'</th>'.
                   3895: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3896:     my $partserror;
                   3897:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3898:     if ($partserror) {
                   3899:         return &navmap_errormsg();
                   3900:     }
1.324     albertel 3901:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3902:     my @partids = ();
1.41      ng       3903:     foreach my $part (@parts) {
                   3904: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3905:         my $narrowtext = &mt('Tries');
                   3906: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3907: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3908: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3909:         push(@partids,$partid);
1.324     albertel 3910: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3911: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3912: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 3913:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   3914:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3915: 	    next;
1.485     albertel 3916: 	    
1.207     albertel 3917: 	} else {
1.485     albertel 3918: 	    if ($display =~ /Problem Status/) {
                   3919: 		my $grade_status_mt = &mt('Grade Status');
                   3920: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3921: 	    }
                   3922: 	    my $part_mt = &mt('Part:');
                   3923: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3924: 	}
1.485     albertel 3925: 
1.474     albertel 3926: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3927:     }
1.474     albertel 3928:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3929: 
1.270     albertel 3930:     my %last_resets = 
                   3931: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3932: 
1.41      ng       3933:     #get info for each student
1.44      ng       3934:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 3935:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3936:     my $ctr = 0;
1.294     albertel 3937:     foreach (sort 
                   3938: 	     {
                   3939: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3940: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3941: 		 }
                   3942: 		 return $a cmp $b;
                   3943: 	     } (keys(%$fullname))) {
1.324     albertel 3944: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 3945:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       3946:     }
1.474     albertel 3947:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3948:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3949:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3950: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 3951:6):     if ($ctr == 0) {
1.442     banghart 3952:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 3953:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3954:6):                 '<span class="LC_warning">';
                   3955:6):         if ($env{'form.submitonly'} eq 'all') {
                   3956:6):             if (grep(/^all$/,@sections)) {
                   3957:6):                 if (grep(/^all$/,@groups)) {
                   3958:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3959:6):                                    $stu_status);
                   3960:6):                 } elsif (grep(/^none$/,@groups)) {
                   3961:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3962:6):                                    $stu_status);
                   3963:6):                 } else {
                   3964:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3965:6):                                    $group_display,$stu_status);
                   3966:6):                 }
                   3967:6):             } elsif (grep(/^none$/,@sections)) {
                   3968:6):                 if (grep(/^all$/,@groups)) {
                   3969:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3970:6):                                    $stu_status);
                   3971:6):                 } elsif (grep(/^none$/,@groups)) {
                   3972:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3973:6):                                    $stu_status);
                   3974:6):                 } else {
                   3975:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3976:6):                                    $group_display,$stu_status);
                   3977:6):                 }
                   3978:6):             } else {
                   3979:6):                 if (grep(/^all$/,@groups)) {
                   3980:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3981:6):                                    $section_display,$stu_status);
                   3982:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 3983:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 3984:6):                                    $section_display,$stu_status);
                   3985:6):                 } else {
                   3986:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3987:6):                                    $section_display,$group_display,$stu_status);
                   3988:6):                 }
                   3989:6):             }
                   3990:6):         } else {
                   3991:6):             if (grep(/^all$/,@sections)) {
                   3992:6):                 if (grep(/^all$/,@groups)) {
                   3993:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3994:6):                                    $stu_status,$submission_status);
                   3995:6):                 } elsif (grep(/^none$/,@groups)) {
                   3996:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3997:6):                                    $stu_status,$submission_status);
                   3998:6):                 } else {
                   3999:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4000:6):                                    $group_display,$stu_status,$submission_status);
                   4001:6):                 }
                   4002:6):             } elsif (grep(/^none$/,@sections)) {
                   4003:6):                 if (grep(/^all$/,@groups)) {
                   4004:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4005:6):                                    $stu_status,$submission_status);
                   4006:6):                 } elsif (grep(/^none$/,@groups)) {
                   4007:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4008:6):                                    $stu_status,$submission_status);
                   4009:6):                 } else {
                   4010:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4011:6):                                    $group_display,$stu_status,$submission_status);
                   4012:6):                 }
                   4013:6):             } else {
                   4014:6):                 if (grep(/^all$/,@groups)) {
                   4015:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4016:6):                                    $section_display,$stu_status,$submission_status);
                   4017:6):                 } elsif (grep(/^none$/,@groups)) {
                   4018:6):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4019:6):                                    $section_display,$stu_status,$submission_status);
                   4020:6):                 } else {
                   4021:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
                   4022:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4023:6):                 }
                   4024:6):             }
                   4025:6): 	}
                   4026:6): 	$result .= '</span><br />';
1.96      albertel 4027:     }
1.324     albertel 4028:     $result.=&show_grading_menu_form($symb);
1.41      ng       4029:     return $result;
                   4030: }
                   4031: 
1.596.2.12.2.  7(raebur 4032:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4033: sub viewstudentgrade {
1.324     albertel 4034:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4035:     my ($uname,$udom) = split(/:/,$student);
                   4036:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4037:6):     my $submitonly = $env{'form.submitonly'};
                   4038:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4039:6):         my %partstatus = ();
                   4040:6):         if (ref($parts) eq 'ARRAY') {
                   4041:6):             foreach my $apart (@{$parts}) {
                   4042:6):                 my ($part,$type) = &split_part_type($apart);
                   4043:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4044:6):                 $status = 'nothing' if ($status eq '');
                   4045:6):                 $partstatus{$part}      = $status;
                   4046:6):                 my $subkey = "resource.$part.submitted_by";
                   4047:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4048:6):             }
                   4049:6):             my $submitted = 0;
                   4050:6):             my $graded = 0;
                   4051:6):             my $incorrect = 0;
                   4052:6):             foreach my $key (keys(%partstatus)) {
                   4053:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4054:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4055:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4056:6): 
                   4057:6):                 my $partid = (split(/\./,$key))[1];
                   4058:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4059:6):                     $submitted = 0;
                   4060:6):                 }
                   4061:6):             }
                   4062:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4063:6):                                        $submitonly eq 'incorrect' ||
                   4064:6):                                        $submitonly eq 'graded'));
                   4065:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4066:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4067:6):         }
                   4068:6):     }
                   4069:6):     if ($submitonly eq 'queued') {
                   4070:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4071:6):         my %queue_status =
                   4072:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4073:6):                                                     $udom,$uname);
                   4074:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4075:6):     }
                   4076:6):     $$ctr++;
                   4077:6):     my %aggregates = ();
1.474     albertel 4078:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4079:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4080:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4081: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4082: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4083: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4084:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4085:     foreach my $apart (@$parts) {
                   4086: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4087: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4088:         $result.='<td align="center">';
1.269     raeburn  4089:         my ($aggtries,$totaltries);
                   4090:         unless (exists($aggregates{$part})) {
1.270     albertel 4091: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4092: 
                   4093: 	    $aggtries = $totaltries;
1.269     raeburn  4094:             if ($$last_resets{$part}) {  
1.270     albertel 4095:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4096: 					   $part);
                   4097:             }
1.269     raeburn  4098:             $result.='<input type="hidden" name="'.
                   4099:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4100:             $result.='<input type="hidden" name="'.
                   4101:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4102:             $aggregates{$part} = 1;
                   4103:         }
1.41      ng       4104: 	if ($type eq 'awarded') {
1.320     albertel 4105: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4106: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4107: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4108: 	    $result.='<input type="text" name="'.
1.89      albertel 4109: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4110:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4111: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4112: 	} elsif ($type eq 'solved') {
                   4113: 	    my ($status,$foo)=split(/_/,$score,2);
                   4114: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4115: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4116: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4117: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4118: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4119:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4120: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4121: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4122: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4123: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4124: 	} else {
                   4125: 	    $result.='<input type="hidden" name="'.
                   4126: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4127: 		    "\n";
1.233     albertel 4128: 	    $result.='<input type="text" name="'.
1.122     ng       4129: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4130: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4131: 	}
                   4132:     }
1.474     albertel 4133:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4134:     return $result;
1.38      ng       4135: }
                   4136: 
1.44      ng       4137: #--- change scores for all the students in a section/class
                   4138: #    record does not get update if unchanged
1.38      ng       4139: sub editgrades {
1.41      ng       4140:     my ($request) = @_;
                   4141: 
1.596.2.12.2.  (raeburn 4142:):     my ($symb)=&get_symb($request);
1.433     banghart 4143:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4144:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4145:3):     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
                   4146:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4147: 
1.477     albertel 4148:     my $result= &Apache::loncommon::start_data_table().
                   4149: 	&Apache::loncommon::start_data_table_header_row().
                   4150: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4151: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4152:     my %scoreptr = (
                   4153: 		    'correct'  =>'correct_by_override',
                   4154: 		    'incorrect'=>'incorrect_by_override',
                   4155: 		    'excused'  =>'excused',
                   4156: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4157:                     'credited' =>'credit_attempted',
1.43      ng       4158: 		    'nothing'  => '',
                   4159: 		    );
1.257     albertel 4160:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4161: 
1.44      ng       4162:     my (@partid);
                   4163:     my %weight = ();
1.54      albertel 4164:     my %columns = ();
1.44      ng       4165:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4166: 
1.582     raeburn  4167:     my $partserror;
                   4168:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4169:     if ($partserror) {
                   4170:         return &navmap_errormsg();
                   4171:     }
1.54      albertel 4172:     my $header;
1.257     albertel 4173:     while ($ctr < $env{'form.totalparts'}) {
                   4174: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4175: 	push(@partid,$partid);
1.257     albertel 4176: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4177: 	$ctr++;
1.54      albertel 4178:     }
1.324     albertel 4179:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  1.2.2(ra 4180:pr-18):     my $totcolspan = 0;
1.54      albertel 4181:     foreach my $partid (@partid) {
1.478     albertel 4182: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4183: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4184: 	$columns{$partid}=2;
                   4185: 	foreach my $stores (@parts) {
                   4186: 	    my ($part,$type) = &split_part_type($stores);
                   4187: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4188: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4189: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4190: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4191:             my $narrowtext = &mt('Tries');
                   4192: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4193: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4194: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4195: 	    $columns{$partid}+=2;
                   4196: 	}
1.596.2.12.2.  1.2.2(ra 4197:pr-18):         $totcolspan += $columns{$partid};
1.54      albertel 4198:     }
                   4199:     foreach my $partid (@partid) {
1.324     albertel 4200: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4201: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4202: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4203: 	    '</th>';
1.54      albertel 4204: 
1.44      ng       4205:     }
1.477     albertel 4206:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4207: 	&Apache::loncommon::start_data_table_header_row().
                   4208: 	$header.
                   4209: 	&Apache::loncommon::end_data_table_header_row();
                   4210:     my @noupdate;
1.126     ng       4211:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4212:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4213: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4214: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4215: 	my %newrecord;
                   4216: 	my $updateflag = 0;
1.108     albertel 4217: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.596.2.12.2.  1.2.2(ra 4218:pr-18):         my $canmodify = &canmodify($usec);
                   4219:pr-18):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4220:pr-18):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4221:pr-18):         if (!$canmodify) {
                   4222:pr-18):             push(@noupdate,
                   4223:pr-18):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4224:pr-18):                  &mt('Not allowed to modify student')."</span></td>");
                   4225:pr-18):             next;
                   4226:pr-18):         }
1.269     raeburn  4227:         my %aggregate = ();
                   4228:         my $aggregateflag = 0;
1.281     albertel 4229: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4230: 	foreach (@partid) {
1.257     albertel 4231: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4232: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4233: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4234: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4235: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4236: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4237: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4238: 	    my $score;
                   4239: 	    if ($partial eq '') {
1.257     albertel 4240: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4241: 	    } elsif ($partial > 0) {
                   4242: 		$score = 'correct_by_override';
                   4243: 	    } elsif ($partial == 0) {
                   4244: 		$score = 'incorrect_by_override';
                   4245: 	    }
1.257     albertel 4246: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4247: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4248: 
1.292     albertel 4249: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4250: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4251: 	    if ($dropMenu eq 'reset status' &&
                   4252: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4253: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4254: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4255: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4256: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4257: 		$updateflag = 1;
1.269     raeburn  4258:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4259:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4260:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4261:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4262:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4263:                     $aggregateflag = 1;
                   4264:                 }
1.139     albertel 4265: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4266: 		$updateflag = 1;
                   4267: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4268: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4269: 		$rec_update++;
1.125     ng       4270: 	    }
                   4271: 
1.93      albertel 4272: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4273: 		'<td align="center">'.$awarded.
                   4274: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4275: 
1.54      albertel 4276: 
                   4277: 	    my $partid=$_;
                   4278: 	    foreach my $stores (@parts) {
                   4279: 		my ($part,$type) = &split_part_type($stores);
                   4280: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4281: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4282: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4283: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4284: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4285: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4286: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4287: 		    $updateflag=1;
                   4288: 		}
1.93      albertel 4289: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4290: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4291: 	    }
1.44      ng       4292: 	}
1.477     albertel 4293: 	$line.="\n";
1.301     albertel 4294: 
                   4295: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4296: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4297: 
1.44      ng       4298: 	if ($updateflag) {
                   4299: 	    $count++;
1.257     albertel 4300: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4301: 				    $udom,$uname);
1.301     albertel 4302: 
                   4303: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4304: 					      $cnum,$udom,$uname)) {
                   4305: 		# need to figure out if should be in queue.
                   4306: 		my %record =  
                   4307: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4308: 					     $udom,$uname);
                   4309: 		my $all_graded = 1;
                   4310: 		my $none_graded = 1;
                   4311: 		foreach my $part (@parts) {
                   4312: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4313: 			$all_graded = 0;
                   4314: 		    } else {
                   4315: 			$none_graded = 0;
                   4316: 		    }
                   4317: 		}
                   4318: 
                   4319: 		if ($all_graded || $none_graded) {
                   4320: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4321: 							   $symb,$cdom,$cnum,
                   4322: 							   $udom,$uname);
                   4323: 		}
                   4324: 	    }
                   4325: 
1.477     albertel 4326: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4327: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4328: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4329: 	    $updateCtr++;
1.93      albertel 4330: 	} else {
1.477     albertel 4331: 	    push(@noupdate,
                   4332: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4333: 	    $noupdateCtr++;
1.44      ng       4334: 	}
1.269     raeburn  4335:         if ($aggregateflag) {
                   4336:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4337: 				  $cdom,$cnum);
1.269     raeburn  4338:         }
1.93      albertel 4339:     }
1.477     albertel 4340:     if (@noupdate) {
1.596.2.12.2.  1.2.2(ra 4341:pr-18):         my $numcols=$totcolspan+2;
1.477     albertel 4342: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4343: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4344: 	    &mt('No Changes Occurred For the Students Below').
                   4345: 	    '</td>'.
1.477     albertel 4346: 	    &Apache::loncommon::end_data_table_row();
                   4347: 	foreach my $line (@noupdate) {
                   4348: 	    $result.=
                   4349: 		&Apache::loncommon::start_data_table_row().
                   4350: 		$line.
                   4351: 		&Apache::loncommon::end_data_table_row();
                   4352: 	}
1.44      ng       4353:     }
1.477     albertel 4354:     $result .= &Apache::loncommon::end_data_table().
                   4355: 	&show_grading_menu_form($symb);
1.478     albertel 4356:     my $msg = '<p><b>'.
                   4357: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4358: 	    $rec_update,$count).'</b><br />'.
                   4359: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4360: 	'</b></p>';
1.44      ng       4361:     return $title.$msg.$result;
1.5       albertel 4362: }
1.54      albertel 4363: 
                   4364: sub split_part_type {
                   4365:     my ($partstr) = @_;
                   4366:     my ($temp,@allparts)=split(/_/,$partstr);
                   4367:     my $type=pop(@allparts);
1.439     albertel 4368:     my $part=join('_',@allparts);
1.54      albertel 4369:     return ($part,$type);
                   4370: }
                   4371: 
1.44      ng       4372: #------------- end of section for handling grading by section/class ---------
                   4373: #
                   4374: #----------------------------------------------------------------------------
                   4375: 
1.5       albertel 4376: 
1.44      ng       4377: #----------------------------------------------------------------------------
                   4378: #
                   4379: #-------------------------- Next few routines handles grading by csv upload
                   4380: #
                   4381: #--- Javascript to handle csv upload
1.27      albertel 4382: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4383:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4384:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4385:6):   &js_escape(\$error1);
                   4386:6):   &js_escape(\$error2);
1.27      albertel 4387:   return(<<ENDPICK);
                   4388:   function verify(vf) {
                   4389:     var foundsomething=0;
                   4390:     var founduname=0;
1.243     albertel 4391:     var foundID=0;
1.27      albertel 4392:     for (i=0;i<=vf.nfields.value;i++) {
                   4393:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4394:       if (i==0 && tw!=0) { foundID=1; }
                   4395:       if (i==1 && tw!=0) { founduname=1; }
                   4396:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4397:     }
1.246     albertel 4398:     if (founduname==0 && foundID==0) {
                   4399: 	alert('$error1');
                   4400: 	return;
1.27      albertel 4401:     }
                   4402:     if (foundsomething==0) {
1.246     albertel 4403: 	alert('$error2');
                   4404: 	return;
1.27      albertel 4405:     }
                   4406:     vf.submit();
                   4407:   }
                   4408:   function flip(vf,tf) {
                   4409:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4410:     var i;
                   4411:     for (i=0;i<=vf.nfields.value;i++) {
                   4412:       //can not pick the same destination field for both name and domain
                   4413:       if (((i ==0)||(i ==1)) && 
                   4414:           ((tf==0)||(tf==1)) && 
                   4415:           (i!=tf) &&
                   4416:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4417:         eval('vf.f'+i+'.selectedIndex=0;')
                   4418:       }
                   4419:     }
                   4420:   }
                   4421: ENDPICK
                   4422: }
                   4423: 
                   4424: sub csvupload_javascript_forward_associate {
1.573     bisitz   4425:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4426:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4427:6):   &js_escape(\$error1);
                   4428:6):   &js_escape(\$error2);
1.27      albertel 4429:   return(<<ENDPICK);
                   4430:   function verify(vf) {
                   4431:     var foundsomething=0;
                   4432:     var founduname=0;
1.243     albertel 4433:     var foundID=0;
1.27      albertel 4434:     for (i=0;i<=vf.nfields.value;i++) {
                   4435:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4436:       if (tw==1) { foundID=1; }
                   4437:       if (tw==2) { founduname=1; }
                   4438:       if (tw>3) { foundsomething=1; }
1.27      albertel 4439:     }
1.246     albertel 4440:     if (founduname==0 && foundID==0) {
                   4441: 	alert('$error1');
                   4442: 	return;
1.27      albertel 4443:     }
                   4444:     if (foundsomething==0) {
1.246     albertel 4445: 	alert('$error2');
                   4446: 	return;
1.27      albertel 4447:     }
                   4448:     vf.submit();
                   4449:   }
                   4450:   function flip(vf,tf) {
                   4451:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4452:     var i;
                   4453:     //can not pick the same destination field twice
                   4454:     for (i=0;i<=vf.nfields.value;i++) {
                   4455:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4456:         eval('vf.f'+i+'.selectedIndex=0;')
                   4457:       }
                   4458:     }
                   4459:   }
                   4460: ENDPICK
                   4461: }
                   4462: 
1.26      albertel 4463: sub csvuploadmap_header {
1.324     albertel 4464:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4465:     my $javascript;
1.257     albertel 4466:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4467: 	$javascript=&csvupload_javascript_reverse_associate();
                   4468:     } else {
                   4469: 	$javascript=&csvupload_javascript_forward_associate();
                   4470:     }
1.45      ng       4471: 
1.324     albertel 4472:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 4473:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4474:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4475:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       4476:     $request->print(<<ENDPICK);
1.26      albertel 4477: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4478: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       4479: $result
1.326     albertel 4480: <hr />
1.26      albertel 4481: <h3>Identify fields</h3>
                   4482: Total number of records found in file: $distotal <hr />
                   4483: Enter as many fields as you can. The system will inform you and bring you back
                   4484: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4485: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4486: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4487: <input type="hidden" name="associate"  value="" />
                   4488: <input type="hidden" name="phase"      value="three" />
                   4489: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4490: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4491: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4492: <input type="hidden" name="upfile_associate" 
1.257     albertel 4493:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4494: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4495: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4496: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4497: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4498: <hr />
                   4499: <script type="text/javascript" language="Javascript">
                   4500: $javascript
                   4501: </script>
                   4502: ENDPICK
1.118     ng       4503:     return '';
1.26      albertel 4504: 
                   4505: }
                   4506: 
                   4507: sub csvupload_fields {
1.582     raeburn  4508:     my ($symb,$errorref) = @_;
                   4509:     my (@parts) = &getpartlist($symb,$errorref);
                   4510:     if (ref($errorref)) {
                   4511:         if ($$errorref) {
                   4512:             return;
                   4513:         }
                   4514:     }
                   4515: 
1.556     weissno  4516:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4517: 		['username','Student Username'],
                   4518: 		['domain','Student Domain']);
1.324     albertel 4519:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4520:     foreach my $part (sort(@parts)) {
                   4521: 	my @datum;
                   4522: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4523: 	my $name=$part;
                   4524: 	if  (!$display) { $display = $name; }
                   4525: 	@datum=($name,$display);
1.244     albertel 4526: 	if ($name=~/^stores_(.*)_awarded/) {
                   4527: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4528: 	}
1.41      ng       4529: 	push(@fields,\@datum);
                   4530:     }
                   4531:     return (@fields);
1.26      albertel 4532: }
                   4533: 
                   4534: sub csvuploadmap_footer {
1.41      ng       4535:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4536:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4537:     $request->print(<<ENDPICK);
1.26      albertel 4538: </table>
                   4539: <input type="hidden" name="nfields" value="$i" />
                   4540: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4541:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4542: </form>
                   4543: ENDPICK
                   4544: }
                   4545: 
1.283     albertel 4546: sub checkforfile_js {
1.539     riegler  4547:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4548:6):     &js_escape(\$alertmsg);
1.86      ng       4549:     my $result =<<CSVFORMJS;
                   4550: <script type="text/javascript" language="javascript">
                   4551:     function checkUpload(formname) {
                   4552: 	if (formname.upfile.value == "") {
1.539     riegler  4553: 	    alert("$alertmsg");
1.86      ng       4554: 	    return false;
                   4555: 	}
                   4556: 	formname.submit();
                   4557:     }
                   4558:     </script>
                   4559: CSVFORMJS
1.283     albertel 4560:     return $result;
                   4561: }
                   4562: 
                   4563: sub upcsvScores_form {
                   4564:     my ($request) = shift;
1.324     albertel 4565:     my ($symb)=&get_symb($request);
1.283     albertel 4566:     if (!$symb) {return '';}
                   4567:     my $result=&checkforfile_js();
1.257     albertel 4568:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4569:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4570:     $result.=$table;
1.326     albertel 4571:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4572:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4573:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4574: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4575:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4576:     my $upload=&mt("Upload Scores");
1.86      ng       4577:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4578:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4579:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4580:     $result.=<<ENDUPFORM;
1.106     albertel 4581: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4582: <input type="hidden" name="symb" value="$symb" />
                   4583: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4584: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4585: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4586: $upfile_select
1.589     bisitz   4587: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4588: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4589: </form>
                   4590: ENDUPFORM
1.370     www      4591:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4592:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4593:     .'</td></tr></table>'."\n";
1.86      ng       4594:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4595:     $result.=&show_grading_menu_form($symb);
1.86      ng       4596:     return $result;
                   4597: }
                   4598: 
                   4599: 
1.26      albertel 4600: sub csvuploadmap {
1.41      ng       4601:     my ($request)= @_;
1.324     albertel 4602:     my ($symb)=&get_symb($request);
1.41      ng       4603:     if (!$symb) {return '';}
1.72      ng       4604: 
1.41      ng       4605:     my $datatoken;
1.257     albertel 4606:     if (!$env{'form.datatoken'}) {
1.41      ng       4607: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4608:     } else {
1.596.2.12.2.  1.2.1(ra 4609:ov-17):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4610:ov-17):         if ($datatoken ne '') {
                   4611:ov-17):             &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4612:ov-17):         }
1.26      albertel 4613:     }
1.41      ng       4614:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4615:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4616:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4617:     my ($i,$keyfields);
                   4618:     if (@records) {
1.582     raeburn  4619:         my $fieldserror;
                   4620: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4621:         if ($fieldserror) {
                   4622:             $request->print(&navmap_errormsg());
                   4623:             return;
                   4624:         }
1.257     albertel 4625: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4626: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4627: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4628: 							  \@fields);
                   4629: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4630: 	    chop($keyfields);
                   4631: 	} else {
                   4632: 	    unshift(@fields,['none','']);
                   4633: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4634: 							    \@fields);
1.311     banghart 4635:             foreach my $rec (@records) {
                   4636:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4637:                 if (%temp) {
                   4638:                     $keyfields=join(',',sort(keys(%temp)));
                   4639:                     last;
                   4640:                 }
                   4641:             }
1.41      ng       4642: 	}
                   4643:     }
                   4644:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4645:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4646: 
1.41      ng       4647:     return '';
1.27      albertel 4648: }
                   4649: 
1.246     albertel 4650: sub csvuploadoptions {
1.41      ng       4651:     my ($request)= @_;
1.324     albertel 4652:     my ($symb)=&get_symb($request);
1.257     albertel 4653:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4654:     my $ignore=&mt('Ignore First Line');
                   4655:     $request->print(<<ENDPICK);
                   4656: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4657: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4658: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4659: <!--
1.246     albertel 4660: <p>
                   4661: <label>
                   4662:    <input type="checkbox" name="show_full_results" />
                   4663:    Show a table of all changes
                   4664: </label>
                   4665: </p>
1.302     albertel 4666: -->
1.246     albertel 4667: <p>
                   4668: <label>
                   4669:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4670:    Overwrite any existing score
                   4671: </label>
                   4672: </p>
                   4673: ENDPICK
                   4674:     my %fields=&get_fields();
                   4675:     if (!defined($fields{'domain'})) {
1.257     albertel 4676: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4677: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4678:     }
1.257     albertel 4679:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4680: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4681: 	my $cleankey=$1;
                   4682: 	if ($cleankey eq 'command') { next; }
                   4683: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4684: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4685:     }
                   4686:     # FIXME do a check for any duplicated user ids...
                   4687:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4688:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4689: <hr /></form>'."\n");
1.324     albertel 4690:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4691:     return '';
                   4692: }
                   4693: 
                   4694: sub get_fields {
                   4695:     my %fields;
1.257     albertel 4696:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4697:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4698: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4699: 	    if ($env{'form.f'.$i} ne 'none') {
                   4700: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4701: 	    }
                   4702: 	} else {
1.257     albertel 4703: 	    if ($env{'form.f'.$i} ne 'none') {
                   4704: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4705: 	    }
                   4706: 	}
1.27      albertel 4707:     }
1.246     albertel 4708:     return %fields;
                   4709: }
                   4710: 
                   4711: sub csvuploadassign {
                   4712:     my ($request)= @_;
1.324     albertel 4713:     my ($symb)=&get_symb($request);
1.246     albertel 4714:     if (!$symb) {return '';}
1.345     bowersj2 4715:     my $error_msg = '';
1.596.2.12.2.  1.2.1(ra 4716:ov-17):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4717:ov-17):     if ($datatoken ne '') {
                   4718:ov-17):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4719:ov-17):     }
1.246     albertel 4720:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4721:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4722:     my %fields=&get_fields();
1.41      ng       4723:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4724:     my $courseid=$env{'request.course.id'};
1.97      albertel 4725:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4726:     my @notallowed;
1.41      ng       4727:     my @skipped;
1.596.2.4  raeburn  4728:     my @warnings;
1.41      ng       4729:     my $countdone=0;
                   4730:     foreach my $grade (@gradedata) {
                   4731: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4732: 	my $domain;
                   4733: 	if ($entries{$fields{'domain'}}) {
                   4734: 	    $domain=$entries{$fields{'domain'}};
                   4735: 	} else {
1.257     albertel 4736: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4737: 	}
1.243     albertel 4738: 	$domain=~s/\s//g;
1.41      ng       4739: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4740: 	$username=~s/\s//g;
1.243     albertel 4741: 	if (!$username) {
                   4742: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4743: 	    $id=~s/\s//g;
1.243     albertel 4744: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4745: 	    $username=$ids{$id};
                   4746: 	}
1.41      ng       4747: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4748: 	    my $id=$entries{$fields{'ID'}};
                   4749: 	    $id=~s/\s//g;
                   4750: 	    if ($id) {
                   4751: 		push(@skipped,"$id:$domain");
                   4752: 	    } else {
                   4753: 		push(@skipped,"$username:$domain");
                   4754: 	    }
1.41      ng       4755: 	    next;
                   4756: 	}
1.108     albertel 4757: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4758: 	if (!&canmodify($usec)) {
                   4759: 	    push(@notallowed,"$username:$domain");
                   4760: 	    next;
                   4761: 	}
1.244     albertel 4762: 	my %points;
1.41      ng       4763: 	my %grades;
                   4764: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4765: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4766: 		$dest eq 'domain') { next; }
                   4767: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4768: 	    if ($dest=~/stores_(.*)_points/) {
                   4769: 		my $part=$1;
                   4770: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4771: 					      $symb,$domain,$username);
1.345     bowersj2 4772:                 if ($wgt) {
                   4773:                     $entries{$fields{$dest}}=~s/\s//g;
                   4774:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4775:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4776:                                           : 'correct_by_override';
1.596.2.4  raeburn  4777:                     if ($pcr>1) {
                   4778:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4779:                     }
1.345     bowersj2 4780:                     $grades{"resource.$part.awarded"}=$pcr;
                   4781:                     $grades{"resource.$part.solved"}=$award;
                   4782:                     $points{$part}=1;
                   4783:                 } else {
                   4784:                     $error_msg = "<br />" .
                   4785:                         &mt("Some point values were assigned"
                   4786:                             ." for problems with a weight "
                   4787:                             ."of zero. These values were "
                   4788:                             ."ignored.");
                   4789:                 }
1.244     albertel 4790: 	    } else {
                   4791: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4792: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4793: 		my $store_key=$dest;
                   4794: 		$store_key=~s/^stores/resource/;
                   4795: 		$store_key=~s/_/\./g;
                   4796: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4797: 	    }
1.41      ng       4798: 	}
1.508     www      4799: 	if (! %grades) { 
                   4800:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4801:         } else {
                   4802: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4803: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4804: 					   $env{'request.course.id'},
                   4805: 					   $domain,$username);
1.508     www      4806: 	   if ($result eq 'ok') {
                   4807: 	      $request->print('.');
1.596.2.4  raeburn  4808: # Remove from grading queue
                   4809:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4810:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4811:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4812:                                              $domain,$username);
1.508     www      4813: 	   } else {
                   4814: 	      $request->print("<p><span class=\"LC_error\">".
                   4815:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4816:                                   "$username:$domain",$result)."</span></p>");
                   4817: 	   }
                   4818: 	   $request->rflush();
                   4819: 	   $countdone++;
                   4820:         }
1.41      ng       4821:     }
1.570     www      4822:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4823:     if (@warnings) {
                   4824:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4825:         $request->print(join(', ',@warnings));
                   4826:     }
1.41      ng       4827:     if (@skipped) {
1.571     www      4828: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4829:         $request->print(join(', ',@skipped));
1.106     albertel 4830:     }
                   4831:     if (@notallowed) {
1.571     www      4832: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4833: 	$request->print(join(', ',@notallowed));
1.41      ng       4834:     }
1.106     albertel 4835:     $request->print("<br />\n");
1.324     albertel 4836:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4837:     return $error_msg;
1.26      albertel 4838: }
1.44      ng       4839: #------------- end of section for handling csv file upload ---------
                   4840: #
                   4841: #-------------------------------------------------------------------
                   4842: #
1.122     ng       4843: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4844: #
                   4845: #--- Select a page/sequence and a student to grade
1.68      ng       4846: sub pickStudentPage {
                   4847:     my ($request) = shift;
                   4848: 
1.539     riegler  4849:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 4850:6):     &js_escape(\$alertmsg);
1.68      ng       4851:     $request->print(<<LISTJAVASCRIPT);
                   4852: <script type="text/javascript" language="javascript">
                   4853: 
                   4854: function checkPickOne(formname) {
1.76      ng       4855:     if (radioSelection(formname.student) == null) {
1.539     riegler  4856: 	alert("$alertmsg");
1.68      ng       4857: 	return;
                   4858:     }
1.125     ng       4859:     ptr = pullDownSelection(formname.selectpage);
                   4860:     formname.page.value = formname["page"+ptr].value;
                   4861:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4862:     formname.submit();
                   4863: }
                   4864: 
                   4865: </script>
                   4866: LISTJAVASCRIPT
1.118     ng       4867:     &commonJSfunctions($request);
1.324     albertel 4868:     my ($symb) = &get_symb($request);
1.257     albertel 4869:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4870:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4871:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4872: 
1.398     albertel 4873:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4874: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4875: 
1.80      ng       4876:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4877:     my $map_error;
                   4878:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4879:     if ($map_error) {
                   4880:         $request->print(&navmap_errormsg());
                   4881:         return; 
                   4882:     }
1.137     albertel 4883:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4884: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4885: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4886:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4887:     my $ctr=0;
1.68      ng       4888:     foreach (@$titles) {
                   4889: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4890: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4891: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4892: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4893: 	$ctr++;
1.68      ng       4894:     }
1.485     albertel 4895:     $select.= '</select>';
1.539     riegler  4896:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4897: 
1.70      ng       4898:     $ctr=0;
                   4899:     foreach (@$titles) {
                   4900: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4901: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4902: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4903: 	$ctr++;
                   4904:     }
1.72      ng       4905:     $result.='<input type="hidden" name="page" />'."\n".
                   4906: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4907: 
1.485     albertel 4908:     my $options =
                   4909: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4910: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4911:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4912: 
                   4913:     $options =
                   4914: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4915: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4916: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4917:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4918:     
                   4919:     $result.=&build_section_inputs();
1.442     banghart 4920:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4921:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4922: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4923: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4924: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4925: 
1.539     riegler  4926:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4927: 
1.80      ng       4928:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4929:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4930: 
1.68      ng       4931:     $request->print($result);
                   4932: 
1.485     albertel 4933:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4934: 	&Apache::loncommon::start_data_table().
                   4935: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4936: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4937: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4938: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4939: 	'<th>'.&nameUserString('header').'</th>'.
                   4940: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4941:  
1.76      ng       4942:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4943:     my $ptr = 1;
1.294     albertel 4944:     foreach my $student (sort 
                   4945: 			 {
                   4946: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4947: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4948: 			     }
                   4949: 			     return $a cmp $b;
                   4950: 			 } (keys(%$fullname))) {
1.68      ng       4951: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4952: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4953:                                   : '</td>');
1.126     ng       4954: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4955: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4956: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4957: 	$studentTable.=
                   4958: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4959:                          : '');
1.68      ng       4960: 	$ptr++;
                   4961:     }
1.484     albertel 4962:     if ($ptr%2 == 0) {
                   4963: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4964: 	    &Apache::loncommon::end_data_table_row();
                   4965:     }
                   4966:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4967:     $studentTable.='<input type="button" '.
1.589     bisitz   4968:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4969: 
1.324     albertel 4970:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4971:     $request->print($studentTable);
                   4972: 
                   4973:     return '';
                   4974: }
                   4975: 
                   4976: sub getSymbMap {
1.582     raeburn  4977:     my ($map_error) = @_;
1.132     bowersj2 4978:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4979:     unless (ref($navmap)) {
                   4980:         if (ref($map_error)) {
                   4981:             $$map_error = 'navmap';
                   4982:         }
                   4983:         return;
                   4984:     }
1.68      ng       4985:     my %symbx = ();
                   4986:     my @titles = ();
1.117     bowersj2 4987:     my $minder = 0;
                   4988: 
                   4989:     # Gather every sequence that has problems.
1.240     albertel 4990:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4991: 					       1,0,1);
1.117     bowersj2 4992:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4993: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4994: 	    my $title = $minder.'.'.
                   4995: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4996: 	    push(@titles, $title); # minder in case two titles are identical
                   4997: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4998: 	    $minder++;
1.241     albertel 4999: 	}
1.68      ng       5000:     }
                   5001:     return \@titles,\%symbx;
                   5002: }
                   5003: 
1.72      ng       5004: #
                   5005: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5006: sub displayPage {
                   5007:     my ($request) = shift;
                   5008: 
1.324     albertel 5009:     my ($symb) = &get_symb($request);
1.257     albertel 5010:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5011:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5012:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5013:     my $pageTitle = $env{'form.page'};
1.103     albertel 5014:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5015:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5016:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5017: 
                   5018:     #need to make sure we have the correct data for later EXT calls, 
                   5019:     #thus invalidate the cache
                   5020:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5021:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5022:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5023:     &Apache::lonnet::clear_EXT_cache_status();
                   5024: 
1.103     albertel 5025:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 5026:4): 	$request->print('<span class="LC_warning">'.
                   5027:4):                         &mt('Unable to view requested student. ([_1])',
                   5028:4):                             $env{'form.student'}).
                   5029:4):                         '</span>');
                   5030:4):         $request->print(&show_grading_menu_form($symb));
                   5031:4):         return;
1.103     albertel 5032:     }
1.398     albertel 5033:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5034:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5035: 	'</h3>'."\n";
1.500     albertel 5036:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5037:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5038: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5039:     } else {
                   5040: 	delete($env{'form.CODE'});
                   5041:     }
1.71      ng       5042:     &sub_page_js($request);
                   5043:     $request->print($result);
                   5044: 
1.132     bowersj2 5045:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5046:     unless (ref($navmap)) {
                   5047:         $request->print(&navmap_errormsg());
                   5048:         $request->print(&show_grading_menu_form($symb));
                   5049:         return;
                   5050:     }
1.257     albertel 5051:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5052:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5053:     if (!$map) {
1.485     albertel 5054: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 5055: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5056: 	return; 
                   5057:     }
1.68      ng       5058:     my $iterator = $navmap->getIterator($map->map_start(),
                   5059: 					$map->map_finish());
                   5060: 
1.71      ng       5061:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5062: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5063: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5064: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5065: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5066: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5067: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       5068: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 5069: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       5070: 
1.382     albertel 5071:     if (defined($env{'form.CODE'})) {
                   5072: 	$studentTable.=
                   5073: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5074:     }
1.381     albertel 5075:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5076: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5077: 
1.594     bisitz   5078:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5079:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5080:         '</span>'."\n".
1.484     albertel 5081: 	&Apache::loncommon::start_data_table().
                   5082: 	&Apache::loncommon::start_data_table_header_row().
                   5083: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 5084: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5085: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5086: 
1.329     albertel 5087:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5088:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5089:     $iterator->next(); # skip the first BEGIN_MAP
                   5090:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5091:     while ($depth > 0) {
1.68      ng       5092:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5093:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5094: 
1.385     albertel 5095:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5096: 	    my $parts = $curRes->parts();
1.68      ng       5097:             my $title = $curRes->compTitle();
1.71      ng       5098: 	    my $symbx = $curRes->symb();
1.484     albertel 5099: 	    $studentTable.=
                   5100: 		&Apache::loncommon::start_data_table_row().
                   5101: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5102: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5103:2): 		                        : '<br />('.&mt('[_1]parts',
                   5104:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5105: 		 ).
                   5106: 		 '</td>';
1.71      ng       5107: 	    $studentTable.='<td valign="top">';
1.382     albertel 5108: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5109: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5110: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5111: 					     undef,'both',\%form);
1.71      ng       5112: 	    } else {
1.382     albertel 5113: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5114: 		$companswer =~ s|<form(.*?)>||g;
                   5115: 		$companswer =~ s|</form>||g;
1.71      ng       5116: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5117: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5118: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5119: #		}
1.116     ng       5120: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5121: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5122: 	    }
                   5123: 
1.257     albertel 5124: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5125: 
1.257     albertel 5126: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5127: 		if ($record{'version'} eq '') {
1.485     albertel 5128: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5129: 		} else {
1.116     ng       5130: 		    my %responseType = ();
                   5131: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5132: 			my @responseIds =$curRes->responseIds($partid);
                   5133: 			my @responseType =$curRes->responseType($partid);
                   5134: 			my %responseIds;
                   5135: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5136: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5137: 			}
                   5138: 			$responseType{$partid} = \%responseIds;
1.116     ng       5139: 		    }
1.148     albertel 5140: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5141: 
1.71      ng       5142: 		}
1.257     albertel 5143: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5144: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5145:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5146: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5147: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5148:5): 									'','.submission',undef,
                   5149:5):                                                                         $usec,$identifier);
1.71      ng       5150:  
                   5151: 	    }
1.103     albertel 5152: 	    if (&canmodify($usec)) {
1.585     bisitz   5153:             $studentTable.=&gradeBox_start();
1.103     albertel 5154: 		foreach my $partid (@{$parts}) {
                   5155: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5156: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5157: 		    $question++;
                   5158: 		}
1.585     bisitz   5159:             $studentTable.=&gradeBox_end();
1.196     albertel 5160: 		$prob++;
1.71      ng       5161: 	    }
                   5162: 	    $studentTable.='</td></tr>';
1.68      ng       5163: 
1.103     albertel 5164: 	}
1.68      ng       5165:         $curRes = $iterator->next();
                   5166:     }
                   5167: 
1.589     bisitz   5168:     $studentTable.=
                   5169:         '</table>'."\n".
                   5170:         '<input type="button" value="'.&mt('Save').'" '.
                   5171:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5172:         '</form>'."\n";
1.324     albertel 5173:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       5174:     $request->print($studentTable);
                   5175: 
                   5176:     return '';
1.119     ng       5177: }
                   5178: 
                   5179: sub displaySubByDates {
1.148     albertel 5180:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5181:     my $isCODE=0;
1.335     albertel 5182:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5183:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5184:     my $studentTable=&Apache::loncommon::start_data_table().
                   5185: 	&Apache::loncommon::start_data_table_header_row().
                   5186: 	'<th>'.&mt('Date/Time').'</th>'.
                   5187: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5188:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5189: 	'<th>'.&mt('Submission').'</th>'.
                   5190: 	'<th>'.&mt('Status').'</th>'.
                   5191: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5192:     my ($version);
                   5193:     my %mark;
1.148     albertel 5194:     my %orders;
1.119     ng       5195:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5196:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5197: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5198:     }
1.335     albertel 5199: 
                   5200:     my $interaction;
1.525     raeburn  5201:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5202:5):     my (%lastrndseed,%lasttype);
1.119     ng       5203:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5204: 	my $timestamp = 
                   5205: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5206: 	if (exists($$record{$version.':resource.0.version'})) {
                   5207: 	    $interaction = $$record{$version.':resource.0.version'};
                   5208: 	}
1.596.2.12.2.  (raeburn 5209:):         if ($isTask && $env{'form.previousversion'}) {
                   5210:):             next unless ($interaction == $env{'form.previousversion'});
                   5211:):         }
1.335     albertel 5212: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5213: 		             : "$version:resource");
1.467     albertel 5214: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5215: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5216: 	if ($isCODE) {
                   5217: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5218: 	}
1.596.2.12.2.  (raeburn 5219:):         if ($isTask) {
                   5220:):             $studentTable.='<td>'.$interaction.'</td>';
                   5221:):         }
1.119     ng       5222: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5223: 	my @displaySub = ();
                   5224: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5225:             my ($hidden,$type);
                   5226:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5227:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5228:                 $hidden = 1;
                   5229:             }
1.335     albertel 5230: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   5231: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5232: 	    
1.122     ng       5233: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5234: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5235: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5236: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5237: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5238:                     
1.335     albertel 5239: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5240: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5241:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5242:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5243:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5244:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5245:                                    .'</span>'
                   5246:                                    .' <b>';
1.596     raeburn  5247:                     if ($hidden) {
                   5248:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5249:                     } else {
1.596.2.2  raeburn  5250:                         my ($trial,$rndseed,$newvariation);
                   5251:                         if ($type eq 'randomizetry') {
                   5252:                             $trial = $$record{"$where.$partid.tries"};
                   5253:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5254:                         }
1.596     raeburn  5255: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5256: 			    $displaySub[0].=&mt('Trial not counted');
                   5257: 		        } else {
                   5258: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5259: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5260:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5261:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5262:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5263:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5264:                                 }
                   5265:                             }
1.596.2.12.2.  4(raebur 5266:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5267:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5268: 		        }
                   5269: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5270:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5271: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5272: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5273: 			    $orders{$partid}->{$responseId}=
                   5274: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5275:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5276: 		        }
1.596.2.2  raeburn  5277: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5278: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5279: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5280:                     }
1.147     albertel 5281: 		}
                   5282: 	    }
1.335     albertel 5283: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5284: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5285: 				    $$record{"$where.$partid.checkedin"},
                   5286: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5287: 					'<br />';
1.335     albertel 5288: 	    }
                   5289: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5290: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5291: 		    lc($$record{"$where.$partid.award"}).' '.
                   5292: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5293: 		    '<br />';
                   5294: 	    }
1.335     albertel 5295: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5296: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5297: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5298: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5299: 		$displaySub[2].=
                   5300: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5301: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5302: 	    }
                   5303: 	}
                   5304: 	# needed because old essay regrader has not parts info
                   5305: 	if (exists $$record{"$version:resource.regrader"}) {
                   5306: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5307: 	}
                   5308: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5309: 	if ($displaySub[2]) {
1.467     albertel 5310: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5311: 	}
1.467     albertel 5312: 	$studentTable.='&nbsp;</td>'.
                   5313: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5314:     }
1.467     albertel 5315:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5316:     return $studentTable;
1.71      ng       5317: }
                   5318: 
                   5319: sub updateGradeByPage {
                   5320:     my ($request) = shift;
                   5321: 
1.257     albertel 5322:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5323:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5324:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5325:     my $pageTitle = $env{'form.page'};
1.103     albertel 5326:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5327:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5328:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5329:     if (!&canmodify($usec)) {
1.526     raeburn  5330: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 5331: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 5332: 	return;
                   5333:     }
1.398     albertel 5334:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5335:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5336: 	'</h3>'."\n";
1.70      ng       5337: 
1.68      ng       5338:     $request->print($result);
                   5339: 
1.582     raeburn  5340: 
1.132     bowersj2 5341:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5342:     unless (ref($navmap)) {
                   5343:         $request->print(&navmap_errormsg());
                   5344:         return;
                   5345:     }
1.257     albertel 5346:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5347:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5348:     if (!$map) {
1.527     raeburn  5349: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 5350: 	my ($symb)=&get_symb($request);
                   5351: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5352: 	return; 
                   5353:     }
1.71      ng       5354:     my $iterator = $navmap->getIterator($map->map_start(),
                   5355: 					$map->map_finish());
1.70      ng       5356: 
1.484     albertel 5357:     my $studentTable=
                   5358: 	&Apache::loncommon::start_data_table().
                   5359: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5360: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5361: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5362: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5363: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5364: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5365: 
                   5366:     $iterator->next(); # skip the first BEGIN_MAP
                   5367:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5368:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5369:     while ($depth > 0) {
1.71      ng       5370:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5371:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5372: 
1.385     albertel 5373:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5374: 	    my $parts = $curRes->parts();
1.71      ng       5375:             my $title = $curRes->compTitle();
                   5376: 	    my $symbx = $curRes->symb();
1.484     albertel 5377: 	    $studentTable.=
                   5378: 		&Apache::loncommon::start_data_table_row().
                   5379: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5380: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5381:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5382: 		.')').'</td>';
1.71      ng       5383: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5384: 
                   5385: 	    my %newrecord=();
                   5386: 	    my @displayPts=();
1.269     raeburn  5387:             my %aggregate = ();
                   5388:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5389:5):             if ($env{'form.HIDE'.$prob}) {
                   5390:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5391:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5392:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5393:5):                 $hideflag += $numchgs;
                   5394:5):             }
1.71      ng       5395: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5396: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5397: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5398: 
1.257     albertel 5399: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5400: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5401: 		my $partial = $newpts/$wgt;
                   5402: 		my $score;
                   5403: 		if ($partial > 0) {
                   5404: 		    $score = 'correct_by_override';
1.125     ng       5405: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5406: 		    $score = 'incorrect_by_override';
                   5407: 		}
1.257     albertel 5408: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5409: 		if ($dropMenu eq 'excused') {
1.71      ng       5410: 		    $partial = '';
                   5411: 		    $score = 'excused';
1.125     ng       5412: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5413: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5414: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5415: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5416: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5417: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5418: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5419: 		    $changeflag++;
                   5420: 		    $newpts = '';
1.269     raeburn  5421:                     
                   5422:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5423:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5424:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5425:                     if ($aggtries > 0) {
                   5426:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5427:                         $aggregateflag = 1;
                   5428:                     }
1.71      ng       5429: 		}
1.324     albertel 5430: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5431: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5432: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5433: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5434: 		    '&nbsp;<br />';
1.526     raeburn  5435: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5436: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5437: 		    '&nbsp;<br />';
1.71      ng       5438: 		$question++;
1.380     albertel 5439: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5440: 
1.71      ng       5441: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5442: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5443: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5444: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5445: 
                   5446: 		$changeflag++;
                   5447: 	    }
                   5448: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5449: 		my %record = 
                   5450: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5451: 					     $udom,$uname);
                   5452: 
                   5453: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5454: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5455: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5456: 		    $newrecord{'resource.CODE'} = '';
                   5457: 		}
1.257     albertel 5458: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5459: 					$udom,$uname);
1.382     albertel 5460: 		%record = &Apache::lonnet::restore($symbx,
                   5461: 						   $env{'request.course.id'},
                   5462: 						   $udom,$uname);
1.380     albertel 5463: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5464: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5465: 	    }
1.380     albertel 5466: 	    
1.269     raeburn  5467:             if ($aggregateflag) {
                   5468:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5469:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5470:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5471:             }
1.125     ng       5472: 
1.71      ng       5473: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5474: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5475: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5476: 
1.196     albertel 5477: 	    $prob++;
1.68      ng       5478: 	}
1.71      ng       5479:         $curRes = $iterator->next();
1.68      ng       5480:     }
1.98      albertel 5481: 
1.484     albertel 5482:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 5483:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  5484:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5485: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5486:5): 		  $changeflag).'<br />');
                   5487:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5488:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5489:5):                      $hideflag).'<br />');
                   5490:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5491: 
1.70      ng       5492:     return '';
                   5493: }
                   5494: 
1.72      ng       5495: #-------- end of section for handling grading by page/sequence ---------
                   5496: #
                   5497: #-------------------------------------------------------------------
                   5498: 
1.581     www      5499: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5500: #
                   5501: #------ start of section for handling grading by page/sequence ---------
                   5502: 
1.423     albertel 5503: =pod
                   5504: 
                   5505: =head1 Bubble sheet grading routines
                   5506: 
1.424     albertel 5507:   For this documentation:
                   5508: 
                   5509:    'scanline' refers to the full line of characters
                   5510:    from the file that we are parsing that represents one entire sheet
                   5511: 
                   5512:    'bubble line' refers to the data
1.596.2.6  raeburn  5513:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5514: 
                   5515: 
1.596.2.6  raeburn  5516: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5517: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5518: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5519: one of the predefined configurations for what each scanline looks
                   5520: like.
                   5521: 
                   5522: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5523: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5524: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5525:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5526: invalid student/employee ID
1.424     albertel 5527: 
                   5528: If the CODE option is used that determines the randomization of the
1.556     weissno  5529: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5530: username:domain.
                   5531: 
                   5532: During the validation phase the instructor can choose to skip scanlines. 
                   5533: 
1.596.2.6  raeburn  5534: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5535: 
                   5536:   scantron_original_filename (unmodified original file)
                   5537:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5538:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5539: 
                   5540: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5541: correction information that isn't representable in the bubblesheet
1.424     albertel 5542: file (see &scantron_getfile() for more information)
                   5543: 
                   5544: After all scanlines are either valid, marked as valid or skipped, then
                   5545: foreach line foreach problem in the picked sequence, an ssi request is
                   5546: made that simulates a user submitting their selected letter(s) against
                   5547: the homework problem.
1.423     albertel 5548: 
                   5549: =over 4
                   5550: 
                   5551: 
                   5552: 
                   5553: =item defaultFormData
                   5554: 
                   5555:   Returns html hidden inputs used to hold context/default values.
                   5556: 
                   5557:  Arguments:
                   5558:   $symb - $symb of the current resource 
                   5559: 
                   5560: =cut
1.422     foxr     5561: 
1.81      albertel 5562: sub defaultFormData {
1.324     albertel 5563:     my ($symb)=@_;
1.447     foxr     5564:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5565:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5566:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5567: }
                   5568: 
1.447     foxr     5569: 
1.423     albertel 5570: =pod 
                   5571: 
                   5572: =item getSequenceDropDown
                   5573: 
                   5574:    Return html dropdown of possible sequences to grade
                   5575:  
                   5576:  Arguments:
1.582     raeburn  5577:    $symb - $symb of the current resource
                   5578:    $map_error - ref to scalar which will container error if
                   5579:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5580: 
                   5581: =cut
1.422     foxr     5582: 
1.75      albertel 5583: sub getSequenceDropDown {
1.582     raeburn  5584:     my ($symb,$map_error)=@_;
1.75      albertel 5585:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5586:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5587:     if (ref($map_error)) {
                   5588:         return if ($$map_error);
                   5589:     }
1.137     albertel 5590:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5591:     my $ctr=0;
                   5592:     foreach (@$titles) {
                   5593: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5594: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5595: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5596: 	    '>'.$showtitle.'</option>'."\n";
                   5597: 	$ctr++;
                   5598:     }
                   5599:     $result.= '</select>';
                   5600:     return $result;
                   5601: }
                   5602: 
1.495     albertel 5603: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5604:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5605: 
                   5606: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5607: 
1.509     raeburn  5608: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5609:                                    # matchresponse or rankresponse, where 
                   5610:                                    # an individual response can have multiple 
                   5611:                                    # lines
1.503     raeburn  5612: 
                   5613: my %responsetype_per_response;     # responsetype for each response
                   5614: 
1.596.2.12.2.  6(raebur 5615:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5616:3):                                    # numbered response. Needed when randomorder
                   5617:3):                                    # or randompick are in use. Key is ID, value 
                   5618:3):                                    # is response number.
                   5619:3): 
1.495     albertel 5620: # Save and restore the bubble lines array to the form env.
                   5621: 
                   5622: 
                   5623: sub save_bubble_lines {
                   5624:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5625: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5626: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5627: 	    $first_bubble_line{$line};
1.503     raeburn  5628:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5629:             $subdivided_bubble_lines{$line};
                   5630:         $env{"form.scantron.responsetype.$line"} =
                   5631:             $responsetype_per_response{$line};
1.495     albertel 5632:     }
1.596.2.12.2.  6(raebur 5633:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5634:3):         my $line = $masterseq_id_responsenum{$resid};
                   5635:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5636:3):     }
1.495     albertel 5637: }
                   5638: 
                   5639: 
                   5640: sub restore_bubble_lines {
                   5641:     my $line = 0;
                   5642:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5643:3):     %masterseq_id_responsenum = ();
1.495     albertel 5644:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5645: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5646: 	$bubble_lines_per_response{$line} = $value;
                   5647: 	$first_bubble_line{$line}  =
                   5648: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5649:         $subdivided_bubble_lines{$line} =
                   5650:             $env{"form.scantron.sub_bubblelines.$line"};
                   5651:         $responsetype_per_response{$line} =
                   5652:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5653:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5654:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5655: 	$line++;
                   5656:     }
                   5657: }
                   5658: 
1.423     albertel 5659: =pod 
                   5660: 
                   5661: =item scantron_filenames
                   5662: 
                   5663:    Returns a list of the scantron files in the current course 
                   5664: 
                   5665: =cut
1.422     foxr     5666: 
1.202     albertel 5667: sub scantron_filenames {
1.257     albertel 5668:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5669:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5670:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5671:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5672:):                                                         $cname,$getpropath);
1.202     albertel 5673:     my @possiblenames;
1.596.2.12.2.  (raeburn 5674:):     if (ref($dirlist) eq 'ARRAY') {
                   5675:):         foreach my $filename (sort(@{$dirlist})) {
                   5676:): 	    ($filename)=split(/&/,$filename);
                   5677:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5678:): 	    $filename=~s/^scantron_orig_//;
                   5679:): 	    push(@possiblenames,$filename);
                   5680:):         }
1.202     albertel 5681:     }
                   5682:     return @possiblenames;
                   5683: }
                   5684: 
1.423     albertel 5685: =pod 
                   5686: 
                   5687: =item scantron_uploads
                   5688: 
                   5689:    Returns  html drop-down list of scantron files in current course.
                   5690: 
                   5691:  Arguments:
                   5692:    $file2grade - filename to set as selected in the dropdown
                   5693: 
                   5694: =cut
1.422     foxr     5695: 
1.202     albertel 5696: sub scantron_uploads {
1.209     ng       5697:     my ($file2grade) = @_;
1.202     albertel 5698:     my $result=	'<select name="scantron_selectfile">';
                   5699:     $result.="<option></option>";
                   5700:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5701: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5702:     }
                   5703:     $result.="</select>";
                   5704:     return $result;
                   5705: }
                   5706: 
1.423     albertel 5707: =pod 
                   5708: 
                   5709: =item scantron_scantab
                   5710: 
                   5711:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5712:   file.
                   5713: 
                   5714: =cut
1.422     foxr     5715: 
1.82      albertel 5716: sub scantron_scantab {
                   5717:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5718:     $result.='<option></option>'."\n";
1.596.2.12.2.  1.2.3(ra 5719:eb-19):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5720:     if (@lines > 0) {
                   5721:         foreach my $line (@lines) {
                   5722:             next if (($line =~ /^\#/) || ($line eq ''));
                   5723: 	    my ($name,$descrip)=split(/:/,$line);
                   5724: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5725:         }
1.82      albertel 5726:     }
                   5727:     $result.='</select>'."\n";
1.518     raeburn  5728:     return $result;
                   5729: }
                   5730: 
1.423     albertel 5731: =pod 
                   5732: 
                   5733: =item scantron_CODElist
                   5734: 
                   5735:   Returns html drop down of the saved CODE lists from current course,
                   5736:   generated from earlier printings.
                   5737: 
                   5738: =cut
1.422     foxr     5739: 
1.186     albertel 5740: sub scantron_CODElist {
1.257     albertel 5741:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5742:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5743:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5744:     my $namechoice='<option></option>';
1.225     albertel 5745:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5746: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5747: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5748: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5749:     }
                   5750:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5751:     return $namechoice;
                   5752: }
                   5753: 
1.423     albertel 5754: =pod 
                   5755: 
                   5756: =item scantron_CODEunique
                   5757: 
                   5758:   Returns the html for "Each CODE to be used once" radio.
                   5759: 
                   5760: =cut
1.422     foxr     5761: 
1.186     albertel 5762: sub scantron_CODEunique {
1.532     bisitz   5763:     my $result='<span class="LC_nobreak">
1.272     albertel 5764:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5765:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5766:                 </span>
1.532     bisitz   5767:                 <span class="LC_nobreak">
1.272     albertel 5768:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5769:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5770:                 </span>';
1.186     albertel 5771:     return $result;
                   5772: }
1.423     albertel 5773: 
                   5774: =pod 
                   5775: 
                   5776: =item scantron_selectphase
                   5777: 
1.596.2.6  raeburn  5778:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5779:   Allows for - starting a grading run.
1.424     albertel 5780:              - downloading existing scan data (original, corrected
1.423     albertel 5781:                                                 or skipped info)
                   5782: 
                   5783:              - uploading new scan data
                   5784: 
                   5785:  Arguments:
                   5786:   $r          - The Apache request object
                   5787:   $file2grade - name of the file that contain the scanned data to score
                   5788: 
                   5789: =cut
1.186     albertel 5790: 
1.75      albertel 5791: sub scantron_selectphase {
1.209     ng       5792:     my ($r,$file2grade) = @_;
1.324     albertel 5793:     my ($symb)=&get_symb($r);
1.75      albertel 5794:     if (!$symb) {return '';}
1.582     raeburn  5795:     my $map_error;
                   5796:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5797:     if ($map_error) {
                   5798:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5799:         return;
                   5800:     }
1.324     albertel 5801:     my $default_form_data=&defaultFormData($symb);
                   5802:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5803:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5804:     my $format_selector=&scantron_scantab();
1.186     albertel 5805:     my $CODE_selector=&scantron_CODElist();
                   5806:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5807:     my $result;
1.422     foxr     5808: 
1.513     foxr     5809:     $ssi_error = 0;
                   5810: 
1.596.2.4  raeburn  5811:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5812:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5813: 
                   5814:         # Chunk of form to prompt for a scantron file upload.
                   5815: 
                   5816:         $r->print('
1.596.2.12.2.  1.2.3(ra 5817:eb-19):     <br />');
                   5818:eb-19):     my $default_form_data=&defaultFormData($symb);
1.596.2.4  raeburn  5819:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5820:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  6(raebur 5821:6):     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5822:6):     &js_escape(\$alertmsg);
          1.2.3(ra 5823:eb-19):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   5824:eb-19):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  5825:     function checkUpload(formname) {
                   5826:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 5827:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  5828:             return false;
                   5829:         }
                   5830:         formname.submit();
1.596.2.12.2.  1.2.3(ra 5831:eb-19):     }'."\n".$formatjs));
                   5832:eb-19):     $r->print('
1.596.2.4  raeburn  5833:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5834:                 '.$default_form_data.'
                   5835:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5836:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5837:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  1.2.3(ra 5838:eb-19):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5839:eb-19):               '.&Apache::loncommon::start_data_table_header_row().'
                   5840:eb-19):                 <th>
                   5841:eb-19):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5842:eb-19):                 </th>
                   5843:eb-19):               '.&Apache::loncommon::end_data_table_header_row().'
                   5844:eb-19):               '.&Apache::loncommon::start_data_table_row().'
                   5845:eb-19):             <td>
                   5846:eb-19):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   5847:eb-19):     if ($formatoptions) {
                   5848:eb-19):         $r->print('</td>
                   5849:eb-19):                  '.&Apache::loncommon::end_data_table_row().'
                   5850:eb-19):                  '.&Apache::loncommon::start_data_table_row().'
                   5851:eb-19):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   5852:eb-19):                  </td>
                   5853:eb-19):                  '.&Apache::loncommon::end_data_table_row().'
                   5854:eb-19):                  '.&Apache::loncommon::start_data_table_row().'
                   5855:eb-19):                  <td>'
                   5856:eb-19):         );
                   5857:eb-19):     } else {
                   5858:eb-19):         $r->print(' <br />');
1.596.2.4  raeburn  5859:     }
1.596.2.12.2.  1.2.3(ra 5860:eb-19):     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5861:eb-19):               </td>
                   5862:eb-19):              '.&Apache::loncommon::end_data_table_row().'
                   5863:eb-19):              '.&Apache::loncommon::end_data_table().'
                   5864:eb-19):              </form>'
                   5865:eb-19):     );
1.596.2.4  raeburn  5866: 
1.596.2.12.2.  1.2.4(ra 5867:eb-19):     }
                   5868:eb-19): 
1.422     foxr     5869:     # Chunk of form to prompt for a file to grade and how:
                   5870: 
1.489     albertel 5871:     $result.= '
                   5872:     <br />
                   5873:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5874:     <input type="hidden" name="command" value="scantron_warning" />
                   5875:     '.$default_form_data.'
                   5876:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5877:        '.&Apache::loncommon::start_data_table_header_row().'
                   5878:             <th colspan="2">
1.492     albertel 5879:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5880:             </th>
                   5881:        '.&Apache::loncommon::end_data_table_header_row().'
                   5882:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5883:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5884:        '.&Apache::loncommon::end_data_table_row().'
                   5885:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5886:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5887:        '.&Apache::loncommon::end_data_table_row().'
                   5888:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5889:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5890:        '.&Apache::loncommon::end_data_table_row().'
                   5891:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5892:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5893:        '.&Apache::loncommon::end_data_table_row().'
                   5894:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5895:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5896:        '.&Apache::loncommon::end_data_table_row().'
                   5897:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5898: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5899:             <td>
1.492     albertel 5900: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5901:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5902:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5903: 	    </td>
1.489     albertel 5904:        '.&Apache::loncommon::end_data_table_row().'
                   5905:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5906:             <td colspan="2">
1.572     www      5907:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5908:             </td>
1.489     albertel 5909:        '.&Apache::loncommon::end_data_table_row().'
                   5910:     '.&Apache::loncommon::end_data_table().'
                   5911:     </form>
                   5912: ';
1.162     albertel 5913:    
                   5914:     $r->print($result);
                   5915: 
1.422     foxr     5916:     # Chunk of the form that prompts to view a scoring office file,
                   5917:     # corrected file, skipped records in a file.
                   5918: 
1.489     albertel 5919:     $r->print('
                   5920:    <br />
                   5921:    <form action="/adm/grades" name="scantron_download">
                   5922:      '.$default_form_data.'
                   5923:      <input type="hidden" name="command" value="scantron_download" />
                   5924:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5925:        '.&Apache::loncommon::start_data_table_header_row().'
                   5926:               <th>
1.492     albertel 5927:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5928:               </th>
                   5929:        '.&Apache::loncommon::end_data_table_header_row().'
                   5930:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5931:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5932:                 <br />
1.492     albertel 5933:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5934:        '.&Apache::loncommon::end_data_table_row().'
                   5935:      '.&Apache::loncommon::end_data_table().'
                   5936:    </form>
                   5937:    <br />
                   5938: ');
1.162     albertel 5939: 
1.457     banghart 5940:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5941: 
1.596.2.12.2.  8(raebur 5942:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5943:              $default_form_data."\n".
                   5944:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5945:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5946:              '<th colspan="2">
1.572     www      5947:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5948:              '</th>'."\n".
                   5949:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5950:               &Apache::loncommon::start_data_table_row()."\n".
                   5951:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5952:               '<td> '.$sequence_selector.' </td>'.
                   5953:               &Apache::loncommon::end_data_table_row()."\n".
                   5954:               &Apache::loncommon::start_data_table_row()."\n".
                   5955:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5956:               '<td> '.$file_selector.' </td>'."\n".
                   5957:               &Apache::loncommon::end_data_table_row()."\n".
                   5958:               &Apache::loncommon::start_data_table_row()."\n".
                   5959:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5960:               '<td> '.$format_selector.' </td>'."\n".
                   5961:               &Apache::loncommon::end_data_table_row()."\n".
                   5962:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5963:               '<td> '.&mt('Options').' </td>'."\n".
                   5964:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5965:               &Apache::loncommon::end_data_table_row()."\n".
                   5966:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5967:               '<td colspan="2">'."\n".
                   5968:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5969:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5970:               '</td>'."\n".
                   5971:               &Apache::loncommon::end_data_table_row()."\n".
                   5972:               &Apache::loncommon::end_data_table()."\n".
                   5973:               '</form><br />');
1.457     banghart 5974:     $r->print($grading_menu_button);
1.523     raeburn  5975:     return;
1.75      albertel 5976: }
                   5977: 
1.423     albertel 5978: =pod 
                   5979: 
                   5980: =item username_to_idmap
                   5981: 
1.556     weissno  5982:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5983:     student username:domain.
                   5984: 
                   5985:   Arguments:
                   5986: 
                   5987:     $classlist - reference to the class list hash. This is a hash
                   5988:                  keyed by student name:domain  whose elements are references
1.424     albertel 5989:                  to arrays containing various chunks of information
1.423     albertel 5990:                  about the student. (See loncoursedata for more info).
                   5991: 
                   5992:   Returns
                   5993:     %idmap - the constructed hash
                   5994: 
                   5995: =cut
                   5996: 
1.82      albertel 5997: sub username_to_idmap {
                   5998:     my ($classlist)= @_;
                   5999:     my %idmap;
                   6000:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6001:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6002:5):         unless ($id eq '') {
                   6003:5):             if (!exists($idmap{$id})) {
                   6004:5):                 $idmap{$id} = $student;
                   6005:5):             } else {
                   6006:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6007:5):                 if ($status eq 'Active') {
                   6008:5):                     $idmap{$id} = $student;
                   6009:5):                 }
                   6010:5):             }
                   6011:5):         }
1.82      albertel 6012:     }
                   6013:     return %idmap;
                   6014: }
1.423     albertel 6015: 
                   6016: =pod
                   6017: 
1.424     albertel 6018: =item scantron_fixup_scanline
1.423     albertel 6019: 
                   6020:    Process a requested correction to a scanline.
                   6021: 
                   6022:   Arguments:
1.596.2.12.2.  1.2.3(ra 6023:eb-19):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6024:     $scan_data         - hash of correction information 
                   6025:                           (see &scantron_getfile())
                   6026:     $line              - existing scanline
                   6027:     $whichline         - line number of the passed in scanline
                   6028:     $field             - type of change to process 
                   6029:                          (either 
1.573     bisitz   6030:                           'ID'     -> correct the student/employee ID
1.423     albertel 6031:                           'CODE'   -> correct the CODE
                   6032:                           'answer' -> fixup the submitted answers)
                   6033:     
                   6034:    $args               - hash of additional info,
                   6035:                           - 'ID' 
                   6036:                                'newid' -> studentID to use in replacement
1.424     albertel 6037:                                           of existing one
1.423     albertel 6038:                           - 'CODE' 
                   6039:                                'CODE_ignore_dup' - set to true if duplicates
                   6040:                                                    should be ignored.
                   6041: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6042:                                         if the existing unfound code should
1.423     albertel 6043:                                         be used as is
                   6044:                           - 'answer'
                   6045:                                'response' - new answer or 'none' if blank
                   6046:                                'question' - the bubble line to change
1.503     raeburn  6047:                                'questionnum' - the question identifier,
                   6048:                                                may include subquestion. 
1.423     albertel 6049: 
                   6050:   Returns:
                   6051:     $line - the modified scanline
                   6052: 
                   6053:   Side effects: 
                   6054:     $scan_data - may be updated
                   6055: 
                   6056: =cut
                   6057: 
1.82      albertel 6058: 
1.157     albertel 6059: sub scantron_fixup_scanline {
                   6060:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6061:     if ($field eq 'ID') {
                   6062: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6063: 	    return ($line,1,'New value too large');
1.157     albertel 6064: 	}
                   6065: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6066: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6067: 				     $args->{'newid'});
                   6068: 	}
                   6069: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6070: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6071: 	if ($args->{'newid'}=~/^\s*$/) {
                   6072: 	    &scan_data($scan_data,"$whichline.user",
                   6073: 		       $args->{'username'}.':'.$args->{'domain'});
                   6074: 	}
1.186     albertel 6075:     } elsif ($field eq 'CODE') {
1.192     albertel 6076: 	if ($args->{'CODE_ignore_dup'}) {
                   6077: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6078: 	}
                   6079: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6080: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6081: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6082: 		return ($line,1,'New CODE value too large');
                   6083: 	    }
                   6084: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6085: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6086: 	    }
                   6087: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6088: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6089: 	}
1.157     albertel 6090:     } elsif ($field eq 'answer') {
1.497     foxr     6091: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6092: 	my $off=$scantron_config->{'Qoff'};
                   6093: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6094: 	my $answer=${off}x$length;
                   6095: 	if ($args->{'response'} eq 'none') {
                   6096: 	    &scan_data($scan_data,
1.503     raeburn  6097: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6098: 	} else {
                   6099: 	    if ($on eq 'letter') {
                   6100: 		my @alphabet=('A'..'Z');
                   6101: 		$answer=$alphabet[$args->{'response'}];
                   6102: 	    } elsif ($on eq 'number') {
                   6103: 		$answer=$args->{'response'}+1;
                   6104: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6105: 	    } else {
1.497     foxr     6106: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6107: 	    }
1.497     foxr     6108: 	    &scan_data($scan_data,
1.503     raeburn  6109: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6110: 	}
1.497     foxr     6111: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6112: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6113:     }
                   6114:     return $line;
                   6115: }
1.423     albertel 6116: 
                   6117: =pod
                   6118: 
                   6119: =item scan_data
                   6120: 
                   6121:     Edit or look up  an item in the scan_data hash.
                   6122: 
                   6123:   Arguments:
                   6124:     $scan_data  - The hash (see scantron_getfile)
                   6125:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6126:                   scantronfilename_key).
1.423     albertel 6127:     $data        - New value of the hash entry.
                   6128:     $delete      - If true, the entry is removed from the hash.
                   6129: 
                   6130:   Returns:
                   6131:     The new value of the hash table field (undefined if deleted).
                   6132: 
                   6133: =cut
                   6134: 
                   6135: 
1.157     albertel 6136: sub scan_data {
                   6137:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6138:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6139:     if (defined($value)) {
                   6140: 	$scan_data->{$filename.'_'.$key} = $value;
                   6141:     }
                   6142:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6143:     return $scan_data->{$filename.'_'.$key};
                   6144: }
1.423     albertel 6145: 
1.495     albertel 6146: # ----- These first few routines are general use routines.----
                   6147: 
                   6148: # Return the number of occurences of a pattern in a string.
                   6149: 
                   6150: sub occurence_count {
                   6151:     my ($string, $pattern) = @_;
                   6152: 
                   6153:     my @matches = ($string =~ /$pattern/g);
                   6154: 
                   6155:     return scalar(@matches);
                   6156: }
                   6157: 
                   6158: 
                   6159: # Take a string known to have digits and convert all the
                   6160: # digits into letters in the range J,A..I.
                   6161: 
                   6162: sub digits_to_letters {
                   6163:     my ($input) = @_;
                   6164: 
                   6165:     my @alphabet = ('J', 'A'..'I');
                   6166: 
                   6167:     my @input    = split(//, $input);
                   6168:     my $output ='';
                   6169:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6170: 	if ($input[$i] =~ /\d/) {
                   6171: 	    $output .= $alphabet[$input[$i]];
                   6172: 	} else {
                   6173: 	    $output .= $input[$i];
                   6174: 	}
                   6175:     }
                   6176:     return $output;
                   6177: }
                   6178: 
1.423     albertel 6179: =pod 
                   6180: 
                   6181: =item scantron_parse_scanline
                   6182: 
                   6183:   Decodes a scanline from the selected scantron file
                   6184: 
                   6185:  Arguments:
                   6186:     line             - The text of the scantron file line to process
                   6187:     whichline        - Line number
                   6188:     scantron_config  - Hash describing the format of the scantron lines.
                   6189:     scan_data        - Hash of extra information about the scanline
                   6190:                        (see scantron_getfile for more information)
                   6191:     just_header      - True if should not process question answers but only
                   6192:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6193:3):     randomorder      - True if randomorder in use
                   6194:3):     randompick       - True if randompick in use
                   6195:3):     sequence         - Exam folder URL
                   6196:3):     master_seq       - Ref to array containing symbs in exam folder
                   6197:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6198:3):                        (corresponding values are resource objects)
                   6199:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6200:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6201:3):                        are refs to an array of resource objects, ordered
                   6202:3):                        according to order used for CODE, when randomorder
                   6203:3):                        and or randompick are in use.
                   6204:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6205:3):                        for current line to question number used for same question
                   6206:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6207:3):     startline        - Ref to hash where key is question number (0 is first)
                   6208:3):                        and value is number of first bubble line for current 
                   6209:3):                        student or code-based randompick and/or randomorder.
                   6210:3):     totalref         - Ref of scalar used to score total number of bubble
                   6211:3):                        lines needed for responses in a scan line (used when
                   6212:3):                        randompick in use. 
                   6213:3): 
1.423     albertel 6214:  Returns:
                   6215:    Hash containing the result of parsing the scanline
                   6216: 
                   6217:    Keys are all proceeded by the string 'scantron.'
                   6218: 
                   6219:        CODE    - the CODE in use for this scanline
                   6220:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6221:                  by the operator
                   6222:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6223:                             CODEs were selected, but the usage has been
                   6224:                             forced by the operator
1.556     weissno  6225:        ID  - student/employee ID
1.423     albertel 6226:        PaperID - if used, the ID number printed on the sheet when the 
                   6227:                  paper was scanned
                   6228:        FirstName - first name from the sheet
                   6229:        LastName  - last name from the sheet
                   6230: 
                   6231:      if just_header was not true these key may also exist
                   6232: 
1.447     foxr     6233:        missingerror - a list of bubble ranges that are considered to be answers
                   6234:                       to a single question that don't have any bubbles filled in.
                   6235:                       Of the form questionnumber:firstbubblenumber:count.
                   6236:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6237:                       to a single question that have more than one bubble filled in.
                   6238:                       Of the form questionnumber::firstbubblenumber:count
                   6239:    
                   6240:                 In the above, count is the number of bubble responses in the
                   6241:                 input line needed to represent the possible answers to the question.
                   6242:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6243:                 per line would have count = 2.
                   6244: 
1.423     albertel 6245:        maxquest     - the number of the last bubble line that was parsed
                   6246: 
                   6247:        (<number> starts at 1)
                   6248:        <number>.answer - zero or more letters representing the selected
                   6249:                          letters from the scanline for the bubble line 
                   6250:                          <number>.
                   6251:                          if blank there was either no bubble or there where
                   6252:                          multiple bubbles, (consult the keys missingerror and
                   6253:                          doubleerror if this is an error condition)
                   6254: 
                   6255: =cut
                   6256: 
1.82      albertel 6257: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6258:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6259:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6260:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6261: 
1.82      albertel 6262:     my %record;
1.596.2.12.2.  6(raebur 6263:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6264:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6265: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6266: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6267: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6268: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6269: 	    $record{'scantron.CODE'}=substr($data,
                   6270: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6271: 					    $$scantron_config{'CODElength'});
1.191     albertel 6272: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6273: 		$record{'scantron.useCODE'}=1;
                   6274: 	    }
1.192     albertel 6275: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6276: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6277: 	    }
1.82      albertel 6278: 	} else {
                   6279: 	    #FIXME interpret first N questions
                   6280: 	}
                   6281:     }
1.83      albertel 6282:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6283: 				  $$scantron_config{'IDlength'});
1.157     albertel 6284:     $record{'scantron.PaperID'}=
                   6285: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6286: 	       $$scantron_config{'PaperIDlength'});
                   6287:     $record{'scantron.FirstName'}=
                   6288: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6289: 	       $$scantron_config{'FirstNamelength'});
                   6290:     $record{'scantron.LastName'}=
                   6291: 	substr($data,$$scantron_config{'LastName'}-1,
                   6292: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6293:     if ($just_header) { return \%record; }
1.194     albertel 6294: 
1.82      albertel 6295:     my @alphabet=('A'..'Z');
                   6296:     my $questnum=0;
1.447     foxr     6297:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6298: 
1.596.2.12.2.  6(raebur 6299:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6300:3):     if ($randompick || $randomorder) {
                   6301:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6302:3):                                          $master_seq,$symb_to_resource,
                   6303:3):                                          $partids_by_symb,$orderedforcode,
                   6304:3):                                          $respnumlookup,$startline);
                   6305:3):         if ($total) {
                   6306:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6307:3):         }
                   6308:3):         if (ref($totalref)) {
                   6309:3):             $$totalref = $total;
                   6310:3):         }
                   6311:3):     }
                   6312:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6313:     chomp($questions);		# Get rid of any trailing \n.
                   6314:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6315:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6316:3):         my $answers_needed;
                   6317:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6318:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6319:3):         } else {
                   6320:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6321:3):         }
1.503     raeburn  6322:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6323:                              || 1;
                   6324:         $questnum++;
                   6325:         my $quest_id = $questnum;
                   6326:         my $currentquest = substr($questions,0,$answer_length);
                   6327:         $questions       = substr($questions,$answer_length);
                   6328:         if (length($currentquest) < $answer_length) { next; }
                   6329: 
1.596.2.12.2.  6(raebur 6330:3):         my $subdivided;
                   6331:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6332:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6333:3):         } else {
                   6334:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6335:3):         }
                   6336:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6337:             my $subquestnum = 1;
                   6338:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6339:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6340:             foreach my $subans (@subanswers_needed) {
                   6341:                 my $subans_length =
                   6342:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6343:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6344:                 $subquestions   = substr($subquestions,$subans_length);
                   6345:                 $quest_id = "$questnum.$subquestnum";
                   6346:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6347:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6348:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6349:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6350:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6351:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6352:                 } else {
                   6353:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6354:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6355:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6356:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6357:                 }
                   6358:                 $subquestnum ++;
                   6359:             }
                   6360:         } else {
                   6361:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6362:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6363:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6364:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6365:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6366:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6367:             } else {
                   6368:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6369:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6370:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6371:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6372:             }
                   6373:         }
                   6374:     }
                   6375:     $record{'scantron.maxquest'}=$questnum;
                   6376:     return \%record;
                   6377: }
1.447     foxr     6378: 
1.596.2.12.2.  6(raebur 6379:3): sub get_master_seq {
                   6380:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6381:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6382:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6383:3):     my $resource_error;
                   6384:3):     foreach my $resource (@{$resources}) {
                   6385:3):         my $ressymb;
                   6386:3):         if (ref($resource)) {
                   6387:3):             $ressymb = $resource->symb();
                   6388:3):             push(@{$master_seq},$ressymb);
                   6389:3):             $symb_to_resource->{$ressymb} = $resource;
                   6390:3):         } else {
                   6391:3):             $resource_error = 1;
                   6392:3):             last;
                   6393:3):         }
                   6394:3):     }
                   6395:3):     return $resource_error;
                   6396:3): }
                   6397:3): 
                   6398:3): sub get_respnum_lookups {
                   6399:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6400:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6401:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6402:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6403:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6404:3):                    (ref($startline) eq 'HASH'));
                   6405:3):     my ($user,$scancode);
                   6406:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6407:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6408:3):         $scancode = $record->{'scantron.CODE'};
                   6409:3):     } else {
                   6410:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6411:3):     }
                   6412:3):     my @mapresources =
                   6413:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6414:3):                      $orderedforcode);
                   6415:3):     my $total = 0;
                   6416:3):     my $count = 0;
                   6417:3):     foreach my $resource (@mapresources) {
                   6418:3):         my $id = $resource->id();
                   6419:3):         my $symb = $resource->symb();
                   6420:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6421:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6422:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6423:3):                 if ($respnum ne '') {
                   6424:3):                     $respnumlookup->{$count} = $respnum;
                   6425:3):                     $startline->{$count} = $total;
                   6426:3):                     $total += $bubble_lines_per_response{$respnum};
                   6427:3):                     $count ++;
                   6428:3):                 }
                   6429:3):             }
                   6430:3):         }
                   6431:3):     }
                   6432:3):     return $total;
                   6433:3): }
                   6434:3): 
1.503     raeburn  6435: sub scantron_validator_lettnum {
                   6436:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6437:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6438:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6439: 
                   6440:     # Qon 'letter' implies for each slot in currquest we have:
                   6441:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6442:     #    about anything else (esp. a value of Qoff) for missing
                   6443:     #    bubbles.
                   6444:     #
                   6445:     # Qon 'number' implies each slot gives a digit that indexes the
                   6446:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6447:     #    and * or ? for double bubbles on a single line.
                   6448:     #
1.447     foxr     6449: 
1.503     raeburn  6450:     my $matchon;
                   6451:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6452:         $matchon = '[A-Z]';
                   6453:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6454:         $matchon = '\d';
                   6455:     }
                   6456:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6457:3):     my $responsenum = $questnum-1;
                   6458:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6459:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6460:3):     }
                   6461:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6462:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6463:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6464:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6465:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6466:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6467:         my @singlelines = split('',$currquest);
                   6468:         foreach my $entry (@singlelines) {
                   6469:             $occurrences = &occurence_count($entry,$matchon);
                   6470:             if ($occurrences > 1) {
                   6471:                 last;
                   6472:             }
1.596.2.12.2.  6(raebur 6473:3):         }
1.503     raeburn  6474:     } else {
                   6475:         $occurrences = &occurence_count($currquest,$matchon); 
                   6476:     }
                   6477:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6478:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6479:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6480:             my $bubble = substr($currquest,$ans,1);
                   6481:             if ($bubble =~ /$matchon/ ) {
                   6482:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6483:                     if ($bubble == 0) {
                   6484:                         $bubble = 10; 
                   6485:                     }
                   6486:                     $record->{"scantron.$ansnum.answer"} = 
                   6487:                         $alphabet->[$bubble-1];
                   6488:                 } else {
                   6489:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6490:                 }
                   6491:             } else {
                   6492:                 $record->{"scantron.$ansnum.answer"}='';
                   6493:             }
                   6494:             $ansnum++;
                   6495:         }
                   6496:     } elsif (!defined($currquest)
                   6497:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6498:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6499:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6500:             $record->{"scantron.$ansnum.answer"}='';
                   6501:             $ansnum++;
                   6502:         }
                   6503:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6504:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6505:         }
                   6506:     } else {
                   6507:         if ($$scantron_config{'Qon'} eq 'number') {
                   6508:             $currquest = &digits_to_letters($currquest);            
                   6509:         }
                   6510:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6511:             my $bubble = substr($currquest,$ans,1);
                   6512:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6513:             $ansnum++;
                   6514:         }
                   6515:     }
                   6516:     return $ansnum;
                   6517: }
1.447     foxr     6518: 
1.503     raeburn  6519: sub scantron_validator_positional {
                   6520:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6521:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6522:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6523: 
1.503     raeburn  6524:     # Otherwise there's a positional notation;
                   6525:     # each bubble line requires Qlength items, and there are filled in
                   6526:     # bubbles for each case where there 'Qon' characters.
                   6527:     #
1.447     foxr     6528: 
1.503     raeburn  6529:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6530: 
1.503     raeburn  6531:     # If the split only gives us one element.. the full length of the
                   6532:     # answer string, no bubbles are filled in:
1.447     foxr     6533: 
1.507     raeburn  6534:     if ($answers_needed eq '') {
                   6535:         return;
                   6536:     }
                   6537: 
1.503     raeburn  6538:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6539:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6540:             $record->{"scantron.$ansnum.answer"}='';
                   6541:             $ansnum++;
                   6542:         }
                   6543:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6544:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6545:         }
                   6546:     } elsif (scalar(@array) == 2) {
                   6547:         my $location = length($array[0]);
                   6548:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6549:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6550:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6551:             if ($ans eq $line_num) {
                   6552:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6553:             } else {
                   6554:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6555:             }
                   6556:             $ansnum++;
                   6557:          }
                   6558:     } else {
                   6559:         #  If there's more than one instance of a bubble character
                   6560:         #  That's a double bubble; with positional notation we can
                   6561:         #  record all the bubbles filled in as well as the
                   6562:         #  fact this response consists of multiple bubbles.
                   6563:         #
1.596.2.12.2.  6(raebur 6564:3):         my $responsenum = $questnum-1;
                   6565:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6566:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6567:3):         }
                   6568:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6569:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6570:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6571:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6572:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6573:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6574:             my $doubleerror = 0;
                   6575:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6576:                    (!$doubleerror)) {
                   6577:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6578:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6579:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6580:                if (length(@currarray) > 2) {
                   6581:                    $doubleerror = 1;
                   6582:                } 
                   6583:             }
                   6584:             if ($doubleerror) {
                   6585:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6586:             }
                   6587:         } else {
                   6588:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6589:         }
                   6590:         my $item = $ansnum;
                   6591:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6592:             $record->{"scantron.$item.answer"} = '';
                   6593:             $item ++;
                   6594:         }
1.447     foxr     6595: 
1.503     raeburn  6596:         my @ans=@array;
                   6597:         my $i=0;
                   6598:         my $increment = 0;
                   6599:         while ($#ans) {
                   6600:             $i+=length($ans[0]) + $increment;
                   6601:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6602:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6603:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6604:             shift(@ans);
                   6605:             $increment = 1;
                   6606:         }
                   6607:         $ansnum += $answers_needed;
1.82      albertel 6608:     }
1.503     raeburn  6609:     return $ansnum;
1.82      albertel 6610: }
                   6611: 
1.423     albertel 6612: =pod
                   6613: 
                   6614: =item scantron_add_delay
                   6615: 
                   6616:    Adds an error message that occurred during the grading phase to a
                   6617:    queue of messages to be shown after grading pass is complete
                   6618: 
                   6619:  Arguments:
1.424     albertel 6620:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6621:    $scanline    - the scanline that caused the error
                   6622:    $errormesage - the error message
                   6623:    $errorcode   - a numeric code for the error
                   6624: 
                   6625:  Side Effects:
1.424     albertel 6626:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6627: 
                   6628: =cut
                   6629: 
1.82      albertel 6630: sub scantron_add_delay {
1.140     albertel 6631:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6632:     push(@$delayqueue,
                   6633: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6634: 	  'ecode' => $errorcode }
                   6635: 	 );
1.82      albertel 6636: }
                   6637: 
1.423     albertel 6638: =pod
                   6639: 
                   6640: =item scantron_find_student
                   6641: 
1.424     albertel 6642:    Finds the username for the current scanline
                   6643: 
                   6644:   Arguments:
                   6645:    $scantron_record - hash result from scantron_parse_scanline
                   6646:    $scan_data       - hash of correction information 
                   6647:                       (see &scantron_getfile() form more information)
                   6648:    $idmap           - hash from &username_to_idmap()
                   6649:    $line            - number of current scanline
                   6650:  
                   6651:   Returns:
                   6652:    Either 'username:domain' or undef if unknown
                   6653: 
1.423     albertel 6654: =cut
                   6655: 
1.82      albertel 6656: sub scantron_find_student {
1.157     albertel 6657:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6658:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6659:     if ($scanID =~ /^\s*$/) {
                   6660:  	return &scan_data($scan_data,"$line.user");
                   6661:     }
1.83      albertel 6662:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6663:  	if (lc($id) eq lc($scanID)) {
                   6664:  	    return $$idmap{$id};
                   6665:  	}
1.83      albertel 6666:     }
                   6667:     return undef;
                   6668: }
                   6669: 
1.423     albertel 6670: =pod
                   6671: 
                   6672: =item scantron_filter
                   6673: 
1.424     albertel 6674:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6675:    hidden resources was selected
                   6676: 
1.423     albertel 6677: =cut
                   6678: 
1.83      albertel 6679: sub scantron_filter {
                   6680:     my ($curres)=@_;
1.331     albertel 6681: 
                   6682:     if (ref($curres) && $curres->is_problem()) {
                   6683: 	# if the user has asked to not have either hidden
                   6684: 	# or 'randomout' controlled resources to be graded
                   6685: 	# don't include them
                   6686: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6687: 	    && $curres->randomout) {
                   6688: 	    return 0;
                   6689: 	}
1.83      albertel 6690: 	return 1;
                   6691:     }
                   6692:     return 0;
1.82      albertel 6693: }
                   6694: 
1.423     albertel 6695: =pod
                   6696: 
                   6697: =item scantron_process_corrections
                   6698: 
1.424     albertel 6699:    Gets correction information out of submitted form data and corrects
                   6700:    the scanline
                   6701: 
1.423     albertel 6702: =cut
                   6703: 
1.157     albertel 6704: sub scantron_process_corrections {
                   6705:     my ($r) = @_;
1.596.2.12.2.  1.2.3(ra 6706:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6707:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6708:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6709:     my $which=$env{'form.scantron_line'};
1.200     albertel 6710:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6711:     my ($skip,$err,$errmsg);
1.257     albertel 6712:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6713: 	$skip=1;
1.257     albertel 6714:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6715: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6716: 	    $env{'form.scantron_domain'};
1.157     albertel 6717: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6718: 	($line,$err,$errmsg)=
                   6719: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6720: 				     'ID',{'newid'=>$newid,
1.257     albertel 6721: 				    'username'=>$env{'form.scantron_username'},
                   6722: 				    'domain'=>$env{'form.scantron_domain'}});
                   6723:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6724: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6725: 	my $newCODE;
1.192     albertel 6726: 	my %args;
1.190     albertel 6727: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6728: 	    $newCODE='use_unfound';
1.190     albertel 6729: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6730: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6731: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6732: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6733: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6734: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6735: 	}
1.257     albertel 6736: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6737: 	    $args{'CODE_ignore_dup'}=1;
                   6738: 	}
                   6739: 	$args{'CODE'}=$newCODE;
1.186     albertel 6740: 	($line,$err,$errmsg)=
                   6741: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6742: 				     'CODE',\%args);
1.257     albertel 6743:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6744: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6745: 	    ($line,$err,$errmsg)=
                   6746: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6747: 					 $which,'answer',
                   6748: 					 { 'question'=>$question,
1.503     raeburn  6749: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6750:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6751: 	    if ($err) { last; }
                   6752: 	}
                   6753:     }
                   6754:     if ($err) {
1.596.2.12.2.  0(raebur 6755:3): 	$r->print(
                   6756:3):             '<p class="LC_error">'
                   6757:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6758:3):                 $errmsg)
          1(raebur 6759:3):            .'</p>');
1.157     albertel 6760:     } else {
1.200     albertel 6761: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6762: 	&scantron_putfile($scanlines,$scan_data);
                   6763:     }
                   6764: }
                   6765: 
1.423     albertel 6766: =pod
                   6767: 
                   6768: =item reset_skipping_status
                   6769: 
1.424     albertel 6770:    Forgets the current set of remember skipped scanlines (and thus
                   6771:    reverts back to considering all lines in the
                   6772:    scantron_skipped_<filename> file)
                   6773: 
1.423     albertel 6774: =cut
                   6775: 
1.200     albertel 6776: sub reset_skipping_status {
                   6777:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6778:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6779:     &scantron_putfile(undef,$scan_data);
                   6780: }
                   6781: 
1.423     albertel 6782: =pod
                   6783: 
                   6784: =item start_skipping
                   6785: 
1.424     albertel 6786:    Marks a scanline to be skipped. 
                   6787: 
1.423     albertel 6788: =cut
                   6789: 
1.376     albertel 6790: sub start_skipping {
1.200     albertel 6791:     my ($scan_data,$i)=@_;
                   6792:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6793:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6794: 	$remembered{$i}=2;
                   6795:     } else {
                   6796: 	$remembered{$i}=1;
                   6797:     }
1.200     albertel 6798:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6799: }
                   6800: 
1.423     albertel 6801: =pod
                   6802: 
                   6803: =item should_be_skipped
                   6804: 
1.424     albertel 6805:    Checks whether a scanline should be skipped.
                   6806: 
1.423     albertel 6807: =cut
                   6808: 
1.200     albertel 6809: sub should_be_skipped {
1.376     albertel 6810:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6811:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6812: 	# not redoing old skips
1.376     albertel 6813: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6814: 	return 0;
                   6815:     }
                   6816:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6817: 
                   6818:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6819: 	return 0;
                   6820:     }
1.200     albertel 6821:     return 1;
                   6822: }
                   6823: 
1.423     albertel 6824: =pod
                   6825: 
                   6826: =item remember_current_skipped
                   6827: 
1.424     albertel 6828:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6829:    file and remembers them into scan_data for later use.
                   6830: 
1.423     albertel 6831: =cut
                   6832: 
1.200     albertel 6833: sub remember_current_skipped {
                   6834:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6835:     my %to_remember;
                   6836:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6837: 	if ($scanlines->{'skipped'}[$i]) {
                   6838: 	    $to_remember{$i}=1;
                   6839: 	}
                   6840:     }
1.376     albertel 6841: 
1.200     albertel 6842:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6843:     &scantron_putfile(undef,$scan_data);
                   6844: }
                   6845: 
1.423     albertel 6846: =pod
                   6847: 
                   6848: =item check_for_error
                   6849: 
1.424     albertel 6850:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  6851:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6852:     something went wrong.
                   6853: 
1.423     albertel 6854: =cut
                   6855: 
1.200     albertel 6856: sub check_for_error {
                   6857:     my ($r,$result)=@_;
                   6858:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6859: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6860:     }
                   6861: }
1.157     albertel 6862: 
1.423     albertel 6863: =pod
                   6864: 
                   6865: =item scantron_warning_screen
                   6866: 
1.424     albertel 6867:    Interstitial screen to make sure the operator has selected the
                   6868:    correct options before we start the validation phase.
                   6869: 
1.423     albertel 6870: =cut
                   6871: 
1.203     albertel 6872: sub scantron_warning_screen {
                   6873:     my ($button_text)=@_;
1.257     albertel 6874:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  1.2.3(ra 6875:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6876:     my $CODElist;
1.284     albertel 6877:     if ($scantron_config{'CODElocation'} &&
                   6878: 	$scantron_config{'CODEstart'} &&
                   6879: 	$scantron_config{'CODElength'}) {
                   6880: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 6881:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6882: 	$CODElist=
1.492     albertel 6883: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6884: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6885:     }
1.596.2.12.2.  (raeburn 6886:):     my $lastbubblepoints;
                   6887:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6888:):         $lastbubblepoints =
                   6889:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6890:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6891:):     }
1.492     albertel 6892:     return ('
1.203     albertel 6893: <p>
1.492     albertel 6894: <span class="LC_warning">
1.596.2.12.2.  6(raebur 6895:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6896: </p>
                   6897: <table>
1.492     albertel 6898: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6899: <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 6900:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 6901: </table>
                   6902: <br />
1.596.2.12.2.  2(raebur 6903:2): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
                   6904:2): <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
1.203     albertel 6905: 
                   6906: <br />
1.492     albertel 6907: ');
1.203     albertel 6908: }
                   6909: 
1.423     albertel 6910: =pod
                   6911: 
                   6912: =item scantron_do_warning
                   6913: 
1.424     albertel 6914:    Check if the operator has picked something for all required
                   6915:    fields. Error out if something is missing.
                   6916: 
1.423     albertel 6917: =cut
                   6918: 
1.203     albertel 6919: sub scantron_do_warning {
                   6920:     my ($r)=@_;
1.324     albertel 6921:     my ($symb)=&get_symb($r);
1.203     albertel 6922:     if (!$symb) {return '';}
1.324     albertel 6923:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6924:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6925:     if ( $env{'form.selectpage'} eq '' ||
                   6926: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6927: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  6928: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6929: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6930: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6931: 	} 
1.257     albertel 6932: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  6933: 	    $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 6934: 	} 
1.257     albertel 6935: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  6936: 	    $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 6937: 	} 
                   6938:     } else {
1.265     www      6939: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.596.2.12.2.  (raeburn 6940:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6941: 	$r->print('
1.596.2.12.2.  (raeburn 6942:): '.$warning.$bubbledbyhand.'
1.492     albertel 6943: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6944: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6945: ');
1.237     albertel 6946:     }
1.352     albertel 6947:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6948:     return '';
                   6949: }
                   6950: 
1.423     albertel 6951: =pod
                   6952: 
                   6953: =item scantron_form_start
                   6954: 
1.424     albertel 6955:     html hidden input for remembering all selected grading options
                   6956: 
1.423     albertel 6957: =cut
                   6958: 
1.203     albertel 6959: sub scantron_form_start {
                   6960:     my ($max_bubble)=@_;
                   6961:     my $result= <<SCANTRONFORM;
                   6962: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6963:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6964:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6965:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6966:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6967:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6968:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6969:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6970:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6971:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6972: SCANTRONFORM
1.447     foxr     6973: 
                   6974:   my $line = 0;
                   6975:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6976:        my $chunk =
                   6977: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6978:        $chunk .=
                   6979: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6980:        $chunk .= 
                   6981:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6982:        $chunk .=
                   6983:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 6984:3):        $chunk .=
                   6985:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6986:        $result .= $chunk;
                   6987:        $line++;
1.596.2.12.2.  6(raebur 6988:3):     }
1.203     albertel 6989:     return $result;
                   6990: }
                   6991: 
1.423     albertel 6992: =pod
                   6993: 
                   6994: =item scantron_validate_file
                   6995: 
1.596.2.6  raeburn  6996:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6997: 
                   6998:     Also processes any necessary information resets that need to
                   6999:     occur before validation begins (ignore previous corrections,
                   7000:     restarting the skipped records processing)
                   7001: 
1.423     albertel 7002: =cut
                   7003: 
1.157     albertel 7004: sub scantron_validate_file {
                   7005:     my ($r) = @_;
1.324     albertel 7006:     my ($symb)=&get_symb($r);
1.157     albertel 7007:     if (!$symb) {return '';}
1.324     albertel 7008:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7009:     
1.596.2.12.2.  0(raebur 7010:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7011:     # them when doing the corrections reset
1.257     albertel 7012:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7013: 	&reset_skipping_status();
                   7014:     }
1.257     albertel 7015:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7016: 	&remember_current_skipped();
1.257     albertel 7017: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7018:     }
                   7019: 
1.257     albertel 7020:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7021: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7022: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7023: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7024: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7025:     }
1.200     albertel 7026: 
1.257     albertel 7027:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7028: 	&scantron_process_corrections($r);
                   7029:     }
1.503     raeburn  7030:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7031:     #get the student pick code ready
                   7032:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7033:     my $nav_error;
1.596.2.12.2.  1.2.3(ra 7034:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7035:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7036:     if ($nav_error) {
                   7037:         $r->print(&navmap_errormsg());
                   7038:         return '';
                   7039:     }
1.203     albertel 7040:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7041:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7042:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7043:):     }
1.157     albertel 7044:     $r->print($result);
                   7045:     
1.334     albertel 7046:     my @validate_phases=( 'sequence',
                   7047: 			  'ID',
1.157     albertel 7048: 			  'CODE',
                   7049: 			  'doublebubble',
                   7050: 			  'missingbubbles');
1.257     albertel 7051:     if (!$env{'form.validatepass'}) {
                   7052: 	$env{'form.validatepass'} = 0;
1.157     albertel 7053:     }
1.257     albertel 7054:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7055: 
1.448     foxr     7056: 
1.157     albertel 7057:     my $stop=0;
                   7058:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7059: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7060: 	$r->rflush();
1.596.2.12.2.  6(raebur 7061:3): 
1.157     albertel 7062: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7063: 	{
                   7064: 	    no strict 'refs';
                   7065: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7066: 	}
                   7067:     }
                   7068:     if (!$stop) {
1.203     albertel 7069: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  7070: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7071:                   $warning.
                   7072:                   &mt('Perform verification for each student after storage of submissions?').
                   7073:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7074:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7075:                   ('&nbsp;'x3).'<label>'.
                   7076:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7077:                   '</label></span><br />'.
                   7078:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      7079:                   &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  7080:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7081:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7082:     } else {
                   7083: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7084: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7085:     }
                   7086:     if ($stop) {
1.334     albertel 7087: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7088: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7089: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7090: 
1.492     albertel 7091: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 7092: 	} else {
1.503     raeburn  7093:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7094: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7095:             } else {
1.539     riegler  7096:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7097:             }
1.492     albertel 7098: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7099: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7100: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7101: 	}
1.157     albertel 7102:     }
1.352     albertel 7103:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 7104:     return '';
                   7105: }
                   7106: 
1.423     albertel 7107: 
                   7108: =pod
                   7109: 
                   7110: =item scantron_remove_file
                   7111: 
1.596.2.6  raeburn  7112:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7113:    scantron_original_<filename> is never removed
                   7114: 
                   7115: 
1.423     albertel 7116: =cut
                   7117: 
1.200     albertel 7118: sub scantron_remove_file {
1.192     albertel 7119:     my ($which)=@_;
1.257     albertel 7120:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7122:     my $file='scantron_';
1.200     albertel 7123:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7124: 	$file.=$which.'_';
1.192     albertel 7125:     } else {
                   7126: 	return 'refused';
                   7127:     }
1.257     albertel 7128:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7129:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7130: }
                   7131: 
1.423     albertel 7132: 
                   7133: =pod
                   7134: 
                   7135: =item scantron_remove_scan_data
                   7136: 
1.596.2.6  raeburn  7137:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7138:    data file.  (In the case that both the are doing skipped records we need
                   7139:    to remember the old skipped lines for the time being so that element
                   7140:    persists for a while.)
                   7141: 
1.423     albertel 7142: =cut
                   7143: 
1.200     albertel 7144: sub scantron_remove_scan_data {
1.257     albertel 7145:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7146:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7147:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7148:     my @todelete;
1.257     albertel 7149:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7150:     foreach my $key (@keys) {
                   7151: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7152: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7153: 		$key=~/remember_skipping/) {
                   7154: 		next;
                   7155: 	    }
1.192     albertel 7156: 	    push(@todelete,$key);
                   7157: 	}
                   7158:     }
1.200     albertel 7159:     my $result;
1.192     albertel 7160:     if (@todelete) {
1.491     albertel 7161: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7162: 				       \@todelete,$cdom,$cname);
                   7163:     } else {
                   7164: 	$result = 'ok';
1.192     albertel 7165:     }
                   7166:     return $result;
                   7167: }
                   7168: 
1.423     albertel 7169: 
                   7170: =pod
                   7171: 
                   7172: =item scantron_getfile
                   7173: 
1.596.2.6  raeburn  7174:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7175:     the scan_data hash
                   7176:   
                   7177:   Arguments:
                   7178:     None
                   7179: 
                   7180:   Returns:
                   7181:     2 hash references
                   7182: 
                   7183:      - first one has 
                   7184:          orig      -
                   7185:          corrected -
                   7186:          skipped   -  each of which points to an array ref of the specified
                   7187:                       file broken up into individual lines
                   7188:          count     - number of scanlines
                   7189:  
                   7190:      - second is the scan_data hash possible keys are
1.425     albertel 7191:        ($number refers to scanline numbered $number and thus the key affects
                   7192:         only that scanline
                   7193:         $bubline refers to the specific bubble line element and the aspects
                   7194:         refers to that specific bubble line element)
                   7195: 
                   7196:        $number.user - username:domain to use
                   7197:        $number.CODE_ignore_dup 
                   7198:                     - ignore the duplicate CODE error 
                   7199:        $number.useCODE
                   7200:                     - use the CODE in the scanline as is
                   7201:        $number.no_bubble.$bubline
                   7202:                     - it is valid that there is no bubbled in bubble
                   7203:                       at $number $bubline
                   7204:        remember_skipping
                   7205:                     - a frozen hash containing keys of $number and values
                   7206:                       of either 
                   7207:                         1 - we are on a 'do skipped records pass' and plan
                   7208:                             on processing this line
                   7209:                         2 - we are on a 'do skipped records pass' and this
                   7210:                             scanline has been marked to skip yet again
1.424     albertel 7211: 
1.423     albertel 7212: =cut
                   7213: 
1.157     albertel 7214: sub scantron_getfile {
1.200     albertel 7215:     #FIXME really would prefer a scantron directory
1.257     albertel 7216:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7217:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7218:     my $lines;
                   7219:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7220: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7221:     my %scanlines;
                   7222:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7223:     my $temp=$scanlines{'orig'};
                   7224:     $scanlines{'count'}=$#$temp;
                   7225: 
                   7226:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7227: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7228:     if ($lines eq '-1') {
                   7229: 	$scanlines{'corrected'}=[];
                   7230:     } else {
                   7231: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7232:     }
                   7233:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7234: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7235:     if ($lines eq '-1') {
                   7236: 	$scanlines{'skipped'}=[];
                   7237:     } else {
                   7238: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7239:     }
1.175     albertel 7240:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7241:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7242:     my %scan_data = @tmp;
                   7243:     return (\%scanlines,\%scan_data);
                   7244: }
                   7245: 
1.423     albertel 7246: =pod
                   7247: 
                   7248: =item lonnet_putfile
                   7249: 
1.424     albertel 7250:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7251: 
                   7252:  Arguments:
                   7253:    $contents - data to store
                   7254:    $filename - filename to store $contents into
                   7255: 
                   7256:  Returns:
                   7257:    result value from &Apache::lonnet::finishuserfileupload
                   7258: 
1.423     albertel 7259: =cut
                   7260: 
1.157     albertel 7261: sub lonnet_putfile {
                   7262:     my ($contents,$filename)=@_;
1.257     albertel 7263:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7264:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7265:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7266:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7267: 
                   7268: }
                   7269: 
1.423     albertel 7270: =pod
                   7271: 
                   7272: =item scantron_putfile
                   7273: 
1.596.2.6  raeburn  7274:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7275:     scan_data hash. (Does not modify the original version only the
                   7276:     corrected and skipped versions.
                   7277: 
                   7278:  Arguments:
                   7279:     $scanlines - hash ref that looks like the first return value from
                   7280:                  &scantron_getfile()
                   7281:     $scan_data - hash ref that looks like the second return value from
                   7282:                  &scantron_getfile()
                   7283: 
1.423     albertel 7284: =cut
                   7285: 
1.157     albertel 7286: sub scantron_putfile {
                   7287:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7288:     #FIXME really would prefer a scantron directory
1.257     albertel 7289:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7290:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7291:     if ($scanlines) {
                   7292: 	my $prefix='scantron_';
1.157     albertel 7293: # no need to update orig, shouldn't change
                   7294: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7295: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7296: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7297: 			$prefix.'corrected_'.
1.257     albertel 7298: 			$env{'form.scantron_selectfile'});
1.200     albertel 7299: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7300: 			$prefix.'skipped_'.
1.257     albertel 7301: 			$env{'form.scantron_selectfile'});
1.200     albertel 7302:     }
1.175     albertel 7303:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7304: }
                   7305: 
1.423     albertel 7306: =pod
                   7307: 
                   7308: =item scantron_get_line
                   7309: 
1.424     albertel 7310:    Returns the correct version of the scanline
                   7311: 
                   7312:  Arguments:
                   7313:     $scanlines - hash ref that looks like the first return value from
                   7314:                  &scantron_getfile()
                   7315:     $scan_data - hash ref that looks like the second return value from
                   7316:                  &scantron_getfile()
                   7317:     $i         - number of the requested line (starts at 0)
                   7318: 
                   7319:  Returns:
                   7320:    A scanline, (either the original or the corrected one if it
                   7321:    exists), or undef if the requested scanline should be
                   7322:    skipped. (Either because it's an skipped scanline, or it's an
                   7323:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7324:    pass.
                   7325: 
1.423     albertel 7326: =cut
                   7327: 
1.157     albertel 7328: sub scantron_get_line {
1.200     albertel 7329:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7330:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7331:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7332:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7333:     return $scanlines->{'orig'}[$i]; 
                   7334: }
                   7335: 
1.423     albertel 7336: =pod
                   7337: 
                   7338: =item scantron_todo_count
                   7339: 
1.424     albertel 7340:     Counts the number of scanlines that need processing.
                   7341: 
                   7342:  Arguments:
                   7343:     $scanlines - hash ref that looks like the first return value from
                   7344:                  &scantron_getfile()
                   7345:     $scan_data - hash ref that looks like the second return value from
                   7346:                  &scantron_getfile()
                   7347: 
                   7348:  Returns:
                   7349:     $count - number of scanlines to process
                   7350: 
1.423     albertel 7351: =cut
                   7352: 
1.200     albertel 7353: sub get_todo_count {
                   7354:     my ($scanlines,$scan_data)=@_;
                   7355:     my $count=0;
                   7356:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7357: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7358: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7359: 	$count++;
                   7360:     }
                   7361:     return $count;
                   7362: }
                   7363: 
1.423     albertel 7364: =pod
                   7365: 
                   7366: =item scantron_put_line
                   7367: 
1.596.2.6  raeburn  7368:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7369:     data file.
                   7370: 
                   7371:  Arguments:
                   7372:     $scanlines - hash ref that looks like the first return value from
                   7373:                  &scantron_getfile()
                   7374:     $scan_data - hash ref that looks like the second return value from
                   7375:                  &scantron_getfile()
                   7376:     $i         - line number to update
                   7377:     $newline   - contents of the updated scanline
                   7378:     $skip      - if true make the line for skipping and update the
                   7379:                  'skipped' file
                   7380: 
1.423     albertel 7381: =cut
                   7382: 
1.157     albertel 7383: sub scantron_put_line {
1.200     albertel 7384:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7385:     if ($skip) {
                   7386: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7387: 	&start_skipping($scan_data,$i);
1.157     albertel 7388: 	return;
                   7389:     }
                   7390:     $scanlines->{'corrected'}[$i]=$newline;
                   7391: }
                   7392: 
1.423     albertel 7393: =pod
                   7394: 
                   7395: =item scantron_clear_skip
                   7396: 
1.424     albertel 7397:    Remove a line from the 'skipped' file
                   7398: 
                   7399:  Arguments:
                   7400:     $scanlines - hash ref that looks like the first return value from
                   7401:                  &scantron_getfile()
                   7402:     $scan_data - hash ref that looks like the second return value from
                   7403:                  &scantron_getfile()
                   7404:     $i         - line number to update
                   7405: 
1.423     albertel 7406: =cut
                   7407: 
1.376     albertel 7408: sub scantron_clear_skip {
                   7409:     my ($scanlines,$scan_data,$i)=@_;
                   7410:     if (exists($scanlines->{'skipped'}[$i])) {
                   7411: 	undef($scanlines->{'skipped'}[$i]);
                   7412: 	return 1;
                   7413:     }
                   7414:     return 0;
                   7415: }
                   7416: 
1.423     albertel 7417: =pod
                   7418: 
                   7419: =item scantron_filter_not_exam
                   7420: 
1.424     albertel 7421:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7422:    filter out resources that are not marked as 'exam' mode
                   7423: 
1.423     albertel 7424: =cut
                   7425: 
1.334     albertel 7426: sub scantron_filter_not_exam {
                   7427:     my ($curres)=@_;
                   7428:     
                   7429:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7430: 	# if the user has asked to not have either hidden
                   7431: 	# or 'randomout' controlled resources to be graded
                   7432: 	# don't include them
                   7433: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7434: 	    && $curres->randomout) {
                   7435: 	    return 0;
                   7436: 	}
                   7437: 	return 1;
                   7438:     }
                   7439:     return 0;
                   7440: }
                   7441: 
1.423     albertel 7442: =pod
                   7443: 
                   7444: =item scantron_validate_sequence
                   7445: 
1.424     albertel 7446:     Validates the selected sequence, checking for resource that are
                   7447:     not set to exam mode.
                   7448: 
1.423     albertel 7449: =cut
                   7450: 
1.334     albertel 7451: sub scantron_validate_sequence {
                   7452:     my ($r,$currentphase) = @_;
                   7453: 
                   7454:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7455:     unless (ref($navmap)) {
                   7456:         $r->print(&navmap_errormsg());
                   7457:         return (1,$currentphase);
                   7458:     }
1.334     albertel 7459:     my (undef,undef,$sequence)=
                   7460: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7461: 
                   7462:     my $map=$navmap->getResourceByUrl($sequence);
                   7463: 
                   7464:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7465:                                     value="ignore" />');
                   7466:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7467: 	my @resources=
                   7468: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7469: 	if (@resources) {
1.596.2.12.2.  0(raebur 7470:2): 	    $r->print('<p class="LC_warning">'
                   7471:2):                .&mt('Some resources in the sequence currently are not set to'
                   7472:2):                    .' exam mode. Grading these resources currently may not'
                   7473:2):                    .' work correctly.')
                   7474:2):                .'</p>'
                   7475:2):             );
1.334     albertel 7476: 	    return (1,$currentphase);
                   7477: 	}
                   7478:     }
                   7479: 
                   7480:     return (0,$currentphase+1);
                   7481: }
                   7482: 
1.423     albertel 7483: 
                   7484: 
1.157     albertel 7485: sub scantron_validate_ID {
                   7486:     my ($r,$currentphase) = @_;
                   7487:     
                   7488:     #get student info
                   7489:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7490:     my %idmap=&username_to_idmap($classlist);
                   7491: 
                   7492:     #get scantron line setup
1.596.2.12.2.  1.2.3(ra 7493:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7494:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7495: 
                   7496:     my $nav_error;
1.596.2.12.2.  (raeburn 7497:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7498:     if ($nav_error) {
                   7499:         $r->print(&navmap_errormsg());
                   7500:         return(1,$currentphase);
                   7501:     }
1.157     albertel 7502: 
                   7503:     my %found=('ids'=>{},'usernames'=>{});
                   7504:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7505: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7506: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7507: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7508: 						 $scan_data);
                   7509: 	my $id=$$scan_record{'scantron.ID'};
                   7510: 	my $found;
                   7511: 	foreach my $checkid (keys(%idmap)) {
                   7512: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7513: 	}
                   7514: 	if ($found) {
                   7515: 	    my $username=$idmap{$found};
                   7516: 	    if ($found{'ids'}{$found}) {
                   7517: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7518: 					 $line,'duplicateID',$found);
1.194     albertel 7519: 		return(1,$currentphase);
1.157     albertel 7520: 	    } elsif ($found{'usernames'}{$username}) {
                   7521: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7522: 					 $line,'duplicateID',$username);
1.194     albertel 7523: 		return(1,$currentphase);
1.157     albertel 7524: 	    }
1.186     albertel 7525: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7526: 	    $found{'ids'}{$found}++;
                   7527: 	    $found{'usernames'}{$username}++;
                   7528: 	} else {
                   7529: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7530: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7531: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7532: 		    &scantron_get_correction($r,$i,$scan_record,
                   7533: 					     \%scantron_config,
                   7534: 					     $line,'duplicateID',$username);
1.194     albertel 7535: 		    return(1,$currentphase);
1.157     albertel 7536: 		} elsif (!defined($username)) {
                   7537: 		    &scantron_get_correction($r,$i,$scan_record,
                   7538: 					     \%scantron_config,
                   7539: 					     $line,'incorrectID');
1.194     albertel 7540: 		    return(1,$currentphase);
1.157     albertel 7541: 		}
                   7542: 		$found{'usernames'}{$username}++;
                   7543: 	    } else {
                   7544: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7545: 					 $line,'incorrectID');
1.194     albertel 7546: 		return(1,$currentphase);
1.157     albertel 7547: 	    }
                   7548: 	}
                   7549:     }
                   7550: 
                   7551:     return (0,$currentphase+1);
                   7552: }
                   7553: 
1.423     albertel 7554: 
1.157     albertel 7555: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7556:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7557:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7558: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7559: #to show both the current line and the previous one and allow skipping
                   7560: #the previous one or the current one
                   7561: 
1.333     albertel 7562:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7563:         $r->print(
                   7564:             '<p class="LC_warning">'
                   7565:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7566:                 "<b>$error</b>",
                   7567:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7568:            ."</p> \n");
1.157     albertel 7569:     } else {
1.596.2.6  raeburn  7570:         $r->print(
                   7571:             '<p class="LC_warning">'
                   7572:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7573:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7574:            ."</p> \n");
                   7575:     }
                   7576:     my $message =
                   7577:         '<p>'
                   7578:        .&mt('The ID on the form is [_1]',
                   7579:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7580:        .'<br />'
1.596.2.12  raeburn  7581:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7582:             $$scan_record{'scantron.LastName'},
                   7583:             $$scan_record{'scantron.FirstName'})
                   7584:        .'</p>';
1.242     albertel 7585: 
1.157     albertel 7586:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7587:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7588:                            # Array populated for doublebubble or
                   7589:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7590:                            # to validate radio button checking   
                   7591: 
1.157     albertel 7592:     if ($error =~ /ID$/) {
1.186     albertel 7593: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7594: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7595: 		      "</p>\n");
1.157     albertel 7596: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7597: 	    $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 7598: 	}
1.242     albertel 7599: 	$r->print($message);
1.492     albertel 7600: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7601: 	$r->print("\n<ul><li> ");
                   7602: 	#FIXME it would be nice if this sent back the user ID and
                   7603: 	#could do partial userID matches
                   7604: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7605: 				       'scantron_username','scantron_domain'));
                   7606: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7607:3): 	$r->print("\n:\n".
1.257     albertel 7608: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7609: 
                   7610: 	$r->print('</li>');
1.186     albertel 7611:     } elsif ($error =~ /CODE$/) {
                   7612: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7613: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7614: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7615: 	    $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 7616: 	}
1.596.2.6  raeburn  7617:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7618:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7619:                  ."</p>\n");
1.242     albertel 7620: 	$r->print($message);
1.596.2.6  raeburn  7621: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7622: 	$r->print("\n<br /> ");
1.194     albertel 7623: 	my $i=0;
1.273     albertel 7624: 	if ($error eq 'incorrectCODE' 
                   7625: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7626: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7627: 	    if ($closest > 0) {
                   7628: 		foreach my $testcode (@{$closest}) {
                   7629: 		    my $checked='';
1.569     bisitz   7630: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7631: 		    $r->print("
                   7632:    <label>
1.569     bisitz   7633:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7634:        ".&mt("Use the similar CODE [_1] instead.",
                   7635: 	    "<b><tt>".$testcode."</tt></b>")."
                   7636:     </label>
                   7637:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7638: 		    $r->print("\n<br />");
                   7639: 		    $i++;
                   7640: 		}
1.194     albertel 7641: 	    }
                   7642: 	}
1.273     albertel 7643: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7644: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7645: 	    $r->print("
                   7646:     <label>
1.569     bisitz   7647:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7648:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7649: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7650:     </label>");
1.273     albertel 7651: 	    $r->print("\n<br />");
                   7652: 	}
1.194     albertel 7653: 
1.188     albertel 7654: 	$r->print(<<ENDSCRIPT);
                   7655: <script type="text/javascript">
                   7656: function change_radio(field) {
1.190     albertel 7657:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7658:     var i;
                   7659:     for (i=0;i<slct.length;i++) {
                   7660:         if (slct[i].value==field) { slct[i].checked=true; }
                   7661:     }
                   7662: }
                   7663: </script>
                   7664: ENDSCRIPT
1.187     albertel 7665: 	my $href="/adm/pickcode?".
1.359     www      7666: 	   "form=".&escape("scantronupload").
                   7667: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7668: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7669: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7670: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7671: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7672: 	    $r->print("
                   7673:     <label>
                   7674:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7675:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7676: 	     "<a target='_blank' href='$href'>","</a>")."
                   7677:     </label> 
1.558     bisitz   7678:     ".&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 7679: 	    $r->print("\n<br />");
                   7680: 	}
1.492     albertel 7681: 	$r->print("
                   7682:     <label>
                   7683:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7684:        ".&mt("Use [_1] as the CODE.",
                   7685: 	     "</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 7686: 	$r->print("\n<br /><br />");
1.157     albertel 7687:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7688: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7689: 
                   7690: 	# The form field scantron_questions is acutally a list of line numbers.
                   7691: 	# represented by this form so:
                   7692: 
1.596.2.12.2.  6(raebur 7693:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7694:3):                                                 $respnumlookup,$startline);
1.497     foxr     7695: 
1.157     albertel 7696: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7697: 		  $line_list.'" />');
1.242     albertel 7698: 	$r->print($message);
1.492     albertel 7699: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7700: 	foreach my $question (@{$arg}) {
1.503     raeburn  7701: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7702:3):                                                    $scan_record, $error,
                   7703:3):                                                    $randomorder,$randompick,
                   7704:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7705:             push(@lines_to_correct,@linenums);
1.157     albertel 7706: 	}
1.503     raeburn  7707:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7708:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7709: 	$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 7710: 	$r->print($message);
1.492     albertel 7711: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7712: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7713: 
1.503     raeburn  7714: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7715: 	# a list of question numbers. Therefore:
                   7716: 	#
                   7717: 	
1.596.2.12.2.  6(raebur 7718:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7719:3):                                                 $respnumlookup,$startline);
1.497     foxr     7720: 
1.157     albertel 7721: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7722: 		  $line_list.'" />');
1.157     albertel 7723: 	foreach my $question (@{$arg}) {
1.503     raeburn  7724: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7725:3):                                                    $scan_record, $error,
                   7726:3):                                                    $randomorder,$randompick,
                   7727:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7728:             push(@lines_to_correct,@linenums);
1.157     albertel 7729: 	}
1.503     raeburn  7730:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7731:     } else {
                   7732: 	$r->print("\n<ul>");
                   7733:     }
                   7734:     $r->print("\n</li></ul>");
1.497     foxr     7735: }
                   7736: 
1.503     raeburn  7737: sub verify_bubbles_checked {
                   7738:     my (@ansnums) = @_;
                   7739:     my $ansnumstr = join('","',@ansnums);
                   7740:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.596.2.12.2.  6(raebur 7741:6):     &js_escape(\$warning);
1.503     raeburn  7742:     my $output = (<<ENDSCRIPT);
                   7743: <script type="text/javascript">
                   7744: function verify_bubble_radio(form) {
                   7745:     var ansnumArray = new Array ("$ansnumstr");
                   7746:     var need_bubble_count = 0;
                   7747:     for (var i=0; i<ansnumArray.length; i++) {
                   7748:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7749:             var bubble_picked = 0; 
                   7750:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7751:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7752:                     bubble_picked = 1;
                   7753:                 }
                   7754:             }
                   7755:             if (bubble_picked == 0) {
                   7756:                 need_bubble_count ++;
                   7757:             }
                   7758:         }
                   7759:     }
                   7760:     if (need_bubble_count) {
                   7761:         alert("$warning");
                   7762:         return;
                   7763:     }
                   7764:     form.submit(); 
                   7765: }
                   7766: </script>
                   7767: ENDSCRIPT
                   7768:     return $output;
                   7769: }
                   7770: 
1.497     foxr     7771: =pod
                   7772: 
                   7773: =item  questions_to_line_list
1.157     albertel 7774: 
1.497     foxr     7775: Converts a list of questions into a string of comma separated
                   7776: line numbers in the answer sheet used by the questions.  This is
                   7777: used to fill in the scantron_questions form field.
                   7778: 
                   7779:   Arguments:
                   7780:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7781:3):      randomorder  - True if randomorder in use.
                   7782:3):      randompick   - True if randompick in use.
                   7783:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7784:3):                      for current line to question number used for same question
                   7785:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7786:3):      startline    - Reference to hash where key is question number (0 is first)
                   7787:3):                     and key is number of first bubble line for current student
                   7788:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7789: 
                   7790: =cut
                   7791: 
                   7792: 
                   7793: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7794:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7795:     my @lines;
                   7796: 
1.503     raeburn  7797:     foreach my $item (@{$questions}) {
                   7798:         my $question = $item;
                   7799:         my ($first,$count,$last);
                   7800:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7801:             $question = $1;
                   7802:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7803:3):             my $responsenum = $question-1;
                   7804:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7805:3):                 $responsenum = $respnumlookup->{$question-1};
                   7806:3):                 if (ref($startline) eq 'HASH') {
                   7807:3):                     $first = $startline->{$question-1} + 1;
                   7808:3):                 }
                   7809:3):             } else {
                   7810:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7811:3):             }
          7(raebur 7812:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7813:             my $subcount = 1;
                   7814:             while ($subcount<$subquestion) {
                   7815:                 $first += $subans[$subcount-1];
                   7816:                 $subcount ++;
                   7817:             }
                   7818:             $count = $subans[$subquestion-1];
                   7819:         } else {
1.596.2.12.2.  7(raebur 7820:3):             my $responsenum = $question-1;
                   7821:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7822:3):                 $responsenum = $respnumlookup->{$question-1};
                   7823:3):                 if (ref($startline) eq 'HASH') {
                   7824:3):                     $first = $startline->{$question-1} + 1;
                   7825:3):                 }
                   7826:3):             } else {
                   7827:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7828:3):             }
                   7829:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7830:         }
1.506     raeburn  7831:         $last = $first+$count-1;
1.503     raeburn  7832:         push(@lines, ($first..$last));
1.497     foxr     7833:     }
                   7834:     return join(',', @lines);
                   7835: }
                   7836: 
                   7837: =pod 
                   7838: 
                   7839: =item prompt_for_corrections
                   7840: 
                   7841: Prompts for a potentially multiline correction to the
                   7842: user's bubbling (factors out common code from scantron_get_correction
                   7843: for multi and missing bubble cases).
                   7844: 
                   7845:  Arguments:
                   7846:    $r           - Apache request object.
                   7847:    $question    - The question number to prompt for.
                   7848:    $scan_config - The scantron file configuration hash.
                   7849:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7850:    $error       - Type of error
1.596.2.12.2.  7(raebur 7851:3):    $randomorder - True if randomorder in use.
                   7852:3):    $randompick  - True if randompick in use.
                   7853:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7854:3):                     for current line to question number used for same question
                   7855:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   7856:3):    $startline   - Reference to hash where key is question number (0 is first)
                   7857:3):                   and value is number of first bubble line for current student
                   7858:3):                   or code-based randompick and/or randomorder.
1.497     foxr     7859: 
                   7860:  Implicit inputs:
                   7861:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7862:                                   Numbered from 0 (but question numbers are from
                   7863:                                   1.
                   7864:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7865:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7866:                                   type problems render as separate sub-questions, 
1.503     raeburn  7867:                                   in exam mode. This hash contains a 
                   7868:                                   comma-separated list of the lines per 
                   7869:                                   sub-question.
1.510     raeburn  7870:    %responsetype_per_response   - essayresponse, formularesponse,
                   7871:                                   stringresponse, imageresponse, reactionresponse,
                   7872:                                   and organicresponse type problem parts can have
1.503     raeburn  7873:                                   multiple lines per response if the weight
                   7874:                                   assigned exceeds 10.  In this case, only
                   7875:                                   one bubble per line is permitted, but more 
                   7876:                                   than one line might contain bubbles, e.g.
                   7877:                                   bubbling of: line 1 - J, line 2 - J, 
                   7878:                                   line 3 - B would assign 22 points.  
1.497     foxr     7879: 
                   7880: =cut
                   7881: 
                   7882: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 7883:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7884:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7885:     my ($current_line,$lines);
                   7886:     my @linenums;
                   7887:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 7888:3):     my ($first,$responsenum);
1.503     raeburn  7889:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7890:         $question = $1;
                   7891:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 7892:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7893:3):             $responsenum = $respnumlookup->{$question-1};
                   7894:3):             if (ref($startline) eq 'HASH') {
                   7895:3):                 $first = $startline->{$question-1};
                   7896:3):             }
                   7897:3):         } else {
                   7898:3):             $responsenum = $question-1;
          7(raebur 7899:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 7900:3):         }
                   7901:3):         $current_line = $first + 1 ;
                   7902:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7903:         my $subcount = 1;
                   7904:         while ($subcount<$subquestion) {
                   7905:             $current_line += $subans[$subcount-1];
                   7906:             $subcount ++;
                   7907:         }
                   7908:         $lines = $subans[$subquestion-1];
                   7909:     } else {
1.596.2.12.2.  6(raebur 7910:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7911:3):             $responsenum = $respnumlookup->{$question-1};
                   7912:3):             if (ref($startline) eq 'HASH') {
                   7913:3):                 $first = $startline->{$question-1};
                   7914:3):             }
                   7915:3):         } else {
                   7916:3):             $responsenum = $question-1;
                   7917:3):             $first = $first_bubble_line{$responsenum};
                   7918:3):         }
                   7919:3):         $current_line = $first + 1;
                   7920:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7921:     }
1.497     foxr     7922:     if ($lines > 1) {
1.503     raeburn  7923:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 7924:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7925:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7926:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7927:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7928:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7929:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 7930: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  7931:         } else {
                   7932:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7933:         }
1.497     foxr     7934:     }
                   7935:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7936:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 7937:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7938: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7939:         push(@linenums,$current_line);
1.497     foxr     7940: 	$current_line++;
                   7941:     }
                   7942:     if ($lines > 1) {
                   7943: 	$r->print("<hr /><br />");
                   7944:     }
1.503     raeburn  7945:     return @linenums;
1.157     albertel 7946: }
1.423     albertel 7947: 
                   7948: =pod
                   7949: 
                   7950: =item scantron_bubble_selector
                   7951:   
                   7952:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7953:    possibly showing the existing the selected bubbles if known
1.423     albertel 7954: 
                   7955:  Arguments:
                   7956:     $r           - Apache request object
1.596.2.12.2.  1.2.3(ra 7957:eb-19):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     7958:     $line        - Number of the line being displayed.
1.503     raeburn  7959:     $questionnum - Question number (may include subquestion)
                   7960:     $error       - Type of error.
1.497     foxr     7961:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7962: 
                   7963: =cut
                   7964: 
1.157     albertel 7965: sub scantron_bubble_selector {
1.503     raeburn  7966:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7967:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7968: 
                   7969:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 7970:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   7971:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7972:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7973:):             $max=$$scan_config{'BubblesPerRow'};
                   7974:):             if (($scmode eq 'number') && ($max > 10)) {
                   7975:):                 $max = 10;
                   7976:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   7977:):                 $max = 26;
                   7978:):             }
                   7979:):         } else {
                   7980:):             $max = 10;
                   7981:):         }
                   7982:):     }
1.274     albertel 7983: 
1.157     albertel 7984:     my @alphabet=('A'..'Z');
1.503     raeburn  7985:     $r->print(&Apache::loncommon::start_data_table().
                   7986:               &Apache::loncommon::start_data_table_row());
                   7987:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7988:     for (my $i=0;$i<$max+1;$i++) {
                   7989: 	$r->print("\n".'<td align="center">');
                   7990: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7991: 	else { $r->print('&nbsp;'); }
                   7992: 	$r->print('</td>');
                   7993:     }
1.503     raeburn  7994:     $r->print(&Apache::loncommon::end_data_table_row().
                   7995:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7996:     for (my $i=0;$i<$max;$i++) {
                   7997: 	$r->print("\n".
                   7998: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7999: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8000:     }
1.503     raeburn  8001:     my $nobub_checked = ' ';
                   8002:     if ($error eq 'missingbubble') {
                   8003:         $nobub_checked = ' checked = "checked" ';
                   8004:     }
                   8005:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8006: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8007:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8008:               $line.'" value="'.$questionnum.'" /></td>');
                   8009:     $r->print(&Apache::loncommon::end_data_table_row().
                   8010:               &Apache::loncommon::end_data_table());
1.157     albertel 8011: }
                   8012: 
1.423     albertel 8013: =pod
                   8014: 
                   8015: =item num_matches
                   8016: 
1.424     albertel 8017:    Counts the number of characters that are the same between the two arguments.
                   8018: 
                   8019:  Arguments:
                   8020:    $orig - CODE from the scanline
                   8021:    $code - CODE to match against
                   8022: 
                   8023:  Returns:
                   8024:    $count - integer count of the number of same characters between the
                   8025:             two arguments
                   8026: 
1.423     albertel 8027: =cut
                   8028: 
1.194     albertel 8029: sub num_matches {
                   8030:     my ($orig,$code) = @_;
                   8031:     my @code=split(//,$code);
                   8032:     my @orig=split(//,$orig);
                   8033:     my $same=0;
                   8034:     for (my $i=0;$i<scalar(@code);$i++) {
                   8035: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8036:     }
                   8037:     return $same;
                   8038: }
                   8039: 
1.423     albertel 8040: =pod
                   8041: 
                   8042: =item scantron_get_closely_matching_CODEs
                   8043: 
1.424     albertel 8044:    Cycles through all CODEs and finds the set that has the greatest
                   8045:    number of same characters as the provided CODE
                   8046: 
                   8047:  Arguments:
                   8048:    $allcodes - hash ref returned by &get_codes()
                   8049:    $CODE     - CODE from the current scanline
                   8050: 
                   8051:  Returns:
                   8052:    2 element list
                   8053:     - first elements is number of how closely matching the best fit is 
                   8054:       (5 means best set has 5 matching characters)
                   8055:     - second element is an arrary ref containing the set of valid CODEs
                   8056:       that best fit the passed in CODE
                   8057: 
1.423     albertel 8058: =cut
                   8059: 
1.194     albertel 8060: sub scantron_get_closely_matching_CODEs {
                   8061:     my ($allcodes,$CODE)=@_;
                   8062:     my @CODEs;
                   8063:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8064: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8065:     }
                   8066: 
                   8067:     return ($#CODEs,$CODEs[-1]);
                   8068: }
                   8069: 
1.423     albertel 8070: =pod
                   8071: 
                   8072: =item get_codes
                   8073: 
1.424     albertel 8074:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8075:    set of remembered CODEs.
                   8076: 
                   8077:  Arguments:
                   8078:   $old_name - name of the set of remembered CODEs
                   8079:   $cdom     - domain of the course
                   8080:   $cnum     - internal course name
                   8081: 
                   8082:  Returns:
                   8083:   %allcodes - keys are the valid CODEs, values are all 1
                   8084: 
1.423     albertel 8085: =cut
                   8086: 
1.194     albertel 8087: sub get_codes {
1.280     foxr     8088:     my ($old_name, $cdom, $cnum) = @_;
                   8089:     if (!$old_name) {
                   8090: 	$old_name=$env{'form.scantron_CODElist'};
                   8091:     }
                   8092:     if (!$cdom) {
                   8093: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8094:     }
                   8095:     if (!$cnum) {
                   8096: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8097:     }
1.278     albertel 8098:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8099: 				    $cdom,$cnum);
                   8100:     my %allcodes;
                   8101:     if ($result{"type\0$old_name"} eq 'number') {
                   8102: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8103:     } else {
                   8104: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8105:     }
1.194     albertel 8106:     return %allcodes;
                   8107: }
                   8108: 
1.423     albertel 8109: =pod
                   8110: 
                   8111: =item scantron_validate_CODE
                   8112: 
1.424     albertel 8113:    Validates all scanlines in the selected file to not have any
                   8114:    invalid or underspecified CODEs and that none of the codes are
                   8115:    duplicated if this was requested.
                   8116: 
1.423     albertel 8117: =cut
                   8118: 
1.157     albertel 8119: sub scantron_validate_CODE {
                   8120:     my ($r,$currentphase) = @_;
1.596.2.12.2.  1.2.3(ra 8121:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8122:     if ($scantron_config{'CODElocation'} &&
                   8123: 	$scantron_config{'CODEstart'} &&
                   8124: 	$scantron_config{'CODElength'}) {
1.257     albertel 8125: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8126: 	    &FIXME_blow_up()
                   8127: 	}
                   8128:     } else {
                   8129: 	return (0,$currentphase+1);
                   8130:     }
                   8131:     
                   8132:     my %usedCODEs;
                   8133: 
1.194     albertel 8134:     my %allcodes=&get_codes();
1.186     albertel 8135: 
1.582     raeburn  8136:     my $nav_error;
1.596.2.12.2.  (raeburn 8137:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8138:     if ($nav_error) {
                   8139:         $r->print(&navmap_errormsg());
                   8140:         return(1,$currentphase);
                   8141:     }
1.447     foxr     8142: 
1.186     albertel 8143:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8144:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8145: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8146: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8147: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8148: 						 $scan_data);
                   8149: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8150: 	my $error=0;
1.224     albertel 8151: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8152: 	    &scantron_get_correction($r,$i,$scan_record,
                   8153: 				     \%scantron_config,
                   8154: 				     $line,'incorrectCODE',\%allcodes);
                   8155: 	    return(1,$currentphase);
                   8156: 	}
1.221     albertel 8157: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8158: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8159: 	    &scantron_get_correction($r,$i,$scan_record,
                   8160: 				     \%scantron_config,
1.194     albertel 8161: 				     $line,'incorrectCODE',\%allcodes);
                   8162: 	    return(1,$currentphase);
1.186     albertel 8163: 	}
1.214     albertel 8164: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8165: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8166: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8167: 	    &scantron_get_correction($r,$i,$scan_record,
                   8168: 				     \%scantron_config,
1.194     albertel 8169: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8170: 	    return(1,$currentphase);
1.186     albertel 8171: 	}
1.524     raeburn  8172: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8173:     }
1.157     albertel 8174:     return (0,$currentphase+1);
                   8175: }
                   8176: 
1.423     albertel 8177: =pod
                   8178: 
                   8179: =item scantron_validate_doublebubble
                   8180: 
1.424     albertel 8181:    Validates all scanlines in the selected file to not have any
                   8182:    bubble lines with multiple bubbles marked.
                   8183: 
1.423     albertel 8184: =cut
                   8185: 
1.157     albertel 8186: sub scantron_validate_doublebubble {
                   8187:     my ($r,$currentphase) = @_;
                   8188:     #get student info
                   8189:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8190:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8191:3):     my (undef,undef,$sequence)=
                   8192:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8193: 
                   8194:     #get scantron line setup
1.596.2.12.2.  1.2.3(ra 8195:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8196:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8197:3): 
                   8198:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8199:3):     unless (ref($navmap)) {
                   8200:3):         $r->print(&navmap_errormsg());
                   8201:3):         return(1,$currentphase);
                   8202:3):     }
                   8203:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8204:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8205:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8206:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8207:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8208:3): 
1.583     raeburn  8209:     my $nav_error;
1.596.2.12.2.  6(raebur 8210:3):     if (ref($map)) {
                   8211:3):         $randomorder = $map->randomorder();
                   8212:3):         $randompick = $map->randompick();
                   8213:3):         if ($randomorder || $randompick) {
                   8214:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8215:3):             if ($nav_error) {
                   8216:3):                 $r->print(&navmap_errormsg());
                   8217:3):                 return(1,$currentphase);
                   8218:3):             }
                   8219:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8220:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8221:3):         }
                   8222:3):     } else {
                   8223:3):         $r->print(&navmap_errormsg());
                   8224:3):         return(1,$currentphase);
                   8225:3):     }
                   8226:3): 
          (raeburn 8227:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8228:     if ($nav_error) {
                   8229:         $r->print(&navmap_errormsg());
                   8230:         return(1,$currentphase);
                   8231:     }
1.447     foxr     8232: 
1.157     albertel 8233:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8234: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8235: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8236: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8237:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8238:3):                                                  $randompick,$sequence,\@master_seq,
                   8239:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8240:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8241: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8242: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8243: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8244:3): 				 $$scan_record{'scantron.doubleerror'},
                   8245:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8246:     	return (1,$currentphase);
                   8247:     }
                   8248:     return (0,$currentphase+1);
                   8249: }
                   8250: 
1.423     albertel 8251: 
1.503     raeburn  8252: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8253:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8254:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8255: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8256: 	&restore_bubble_lines();
1.257     albertel 8257: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8258:     }
1.330     albertel 8259: 
1.447     foxr     8260:     my (undef, undef, $sequence) =
1.257     albertel 8261: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8262: 
1.447     foxr     8263:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8264:     unless (ref($navmap)) {
                   8265:         if (ref($nav_error)) {
                   8266:             $$nav_error = 1;
                   8267:         }
1.591     raeburn  8268:         return;
1.582     raeburn  8269:     }
1.191     albertel 8270:     my $map=$navmap->getResourceByUrl($sequence);
                   8271:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8272:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8273: 
                   8274:     &Apache::lonxml::clear_problem_counter();
                   8275: 
1.557     raeburn  8276:     my $uname       = $env{'user.name'};
                   8277:     my $udom        = $env{'user.domain'};
1.435     foxr     8278:     my $cid         = $env{'request.course.id'};
                   8279:     my $total_lines = 0;
                   8280:     %bubble_lines_per_response = ();
1.447     foxr     8281:     %first_bubble_line         = ();
1.503     raeburn  8282:     %subdivided_bubble_lines   = ();
                   8283:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8284:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8285: 
1.447     foxr     8286:     my $response_number = 0;
                   8287:     my $bubble_line     = 0;
1.191     albertel 8288:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8289:3):         my $resid = $resource->id();
          (raeburn 8290:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8291:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8292:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8293: 	    foreach my $part_id (@{$parts}) {
                   8294:                 my $lines;
                   8295: 
                   8296: 	        # TODO - make this a persistent hash not an array.
                   8297: 
                   8298:                 # optionresponse, matchresponse and rankresponse type items 
                   8299:                 # render as separate sub-questions in exam mode.
                   8300:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8301:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8302:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8303:                     my ($numbub,$numshown);
                   8304:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8305:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8306:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8307:                         }
                   8308:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8309:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8310:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8311:                         }
                   8312:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8313:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8314:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8315:                         }
                   8316:                     }
                   8317:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8318:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8319:                     }
1.596.2.12.2.  (raeburn 8320:):                     my $bubbles_per_row =
                   8321:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8322:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8323:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8324:                         $inner_bubble_lines++;
                   8325:                     }
                   8326:                     for (my $i=0; $i<$numshown; $i++) {
                   8327:                         $subdivided_bubble_lines{$response_number} .= 
                   8328:                             $inner_bubble_lines.',';
                   8329:                     }
                   8330:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8331:                     $lines = $numshown * $inner_bubble_lines;
                   8332:                 } else {
                   8333:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8334:):                 }
1.542     raeburn  8335: 
                   8336:                 $first_bubble_line{$response_number} = $bubble_line;
                   8337: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8338:                 $responsetype_per_response{$response_number} = 
                   8339:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8340:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8341: 	        $response_number++;
                   8342: 
                   8343: 	        $bubble_line +=  $lines;
                   8344: 	        $total_lines +=  $lines;
                   8345: 	    }
                   8346:         }
                   8347:     }
1.552     raeburn  8348:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8349: 
                   8350:     &save_bubble_lines();
                   8351:     $env{'form.scantron_maxbubble'} =
                   8352: 	$total_lines;
                   8353:     return $env{'form.scantron_maxbubble'};
                   8354: }
1.523     raeburn  8355: 
1.596.2.12.2.  (raeburn 8356:): sub bubblesheet_bubbles_per_row {
                   8357:):     my ($scantron_config) = @_;
                   8358:):     my $bubbles_per_row;
                   8359:):     if (ref($scantron_config) eq 'HASH') {
                   8360:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8361:):     }
                   8362:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8363:):         $bubbles_per_row = 10;
                   8364:):     }
                   8365:):     return $bubbles_per_row;
                   8366:): }
                   8367:): 
1.157     albertel 8368: sub scantron_validate_missingbubbles {
                   8369:     my ($r,$currentphase) = @_;
                   8370:     #get student info
                   8371:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8372:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8373:3):     my (undef,undef,$sequence)=
                   8374:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8375: 
                   8376:     #get scantron line setup
1.596.2.12.2.  1.2.3(ra 8377:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8378:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8379:3): 
                   8380:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8381:3):     unless (ref($navmap)) {
                   8382:3):         $r->print(&navmap_errormsg());
                   8383:3):         return(1,$currentphase);
                   8384:3):     }
                   8385:3): 
                   8386:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8387:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8388:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8389:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8390:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8391:3): 
1.582     raeburn  8392:     my $nav_error;
1.596.2.12.2.  6(raebur 8393:3):     if (ref($map)) {
                   8394:3):         $randomorder = $map->randomorder();
                   8395:3):         $randompick = $map->randompick();
          7(raebur 8396:3):         if ($randomorder || $randompick) {
                   8397:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8398:3):             if ($nav_error) {
                   8399:3):                 $r->print(&navmap_errormsg());
                   8400:3):                 return(1,$currentphase);
                   8401:3):             }
                   8402:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8403:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8404:3):         }
          6(raebur 8405:3):     } else {
                   8406:3):         $r->print(&navmap_errormsg());
          7(raebur 8407:3):         return(1,$currentphase);
          6(raebur 8408:3):     }
                   8409:3): 
                   8410:3): 
          (raeburn 8411:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8412:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8413:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8414:         return(1,$currentphase);
                   8415:     }
1.596.2.12.2.  6(raebur 8416:3): 
1.157     albertel 8417:     if (!$max_bubble) { $max_bubble=2**31; }
                   8418:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8419: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8420: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8421:3):         my $scan_record =
                   8422:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8423:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8424:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8425:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8426: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8427: 	my @to_correct;
1.470     foxr     8428: 	
                   8429: 	# Probably here's where the error is...
                   8430: 
1.157     albertel 8431: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8432:             my $lastbubble;
                   8433:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8434:3):                 my $question = $1;
                   8435:3):                 my $subquestion = $2;
                   8436:3):                 my ($first,$responsenum);
                   8437:3):                 if ($randomorder || $randompick) {
                   8438:3):                     $responsenum = $respnumlookup{$question-1};
                   8439:3):                     $first = $startline{$question-1};
                   8440:3):                 } else {
                   8441:3):                     $responsenum = $question-1;
                   8442:3):                     $first = $first_bubble_line{$responsenum};
                   8443:3):                 }
                   8444:3):                 if (!defined($first)) { next; }
          7(raebur 8445:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8446:3):                 my $subcount = 1;
                   8447:3):                 while ($subcount<$subquestion) {
                   8448:3):                     $first += $subans[$subcount-1];
                   8449:3):                     $subcount ++;
                   8450:3):                 }
                   8451:3):                 my $count = $subans[$subquestion-1];
                   8452:3):                 $lastbubble = $first + $count;
1.505     raeburn  8453:             } else {
1.596.2.12.2.  6(raebur 8454:3):                 my ($first,$responsenum);
                   8455:3):                 if ($randomorder || $randompick) {
                   8456:3):                     $responsenum = $respnumlookup{$missing-1};
                   8457:3):                     $first = $startline{$missing-1};
                   8458:3):                 } else {
                   8459:3):                     $responsenum = $missing-1;
                   8460:3):                     $first = $first_bubble_line{$responsenum};
                   8461:3):                 }
                   8462:3):                 if (!defined($first)) { next; }
                   8463:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8464:             }
                   8465:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8466: 	    push(@to_correct,$missing);
                   8467: 	}
                   8468: 	if (@to_correct) {
                   8469: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8470:3): 				     $line,'missingbubble',\@to_correct,
                   8471:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8472:3):                                      \%startline);
1.157     albertel 8473: 	    return (1,$currentphase);
                   8474: 	}
                   8475: 
                   8476:     }
                   8477:     return (0,$currentphase+1);
                   8478: }
                   8479: 
1.596.2.12.2.  (raeburn 8480:): sub hand_bubble_option {
                   8481:):     my (undef, undef, $sequence) =
                   8482:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8483:):     return if ($sequence eq '');
                   8484:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8485:):     unless (ref($navmap)) {
                   8486:):         return;
                   8487:):     }
                   8488:):     my $needs_hand_bubbles;
                   8489:):     my $map=$navmap->getResourceByUrl($sequence);
                   8490:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8491:):     foreach my $res (@resources) {
                   8492:):         if (ref($res)) {
                   8493:):             if ($res->is_problem()) {
                   8494:):                 my $partlist = $res->parts();
                   8495:):                 foreach my $part (@{ $partlist }) {
                   8496:):                     my @types = $res->responseType($part);
                   8497:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8498:):                         $needs_hand_bubbles = 1;
                   8499:):                         last;
                   8500:):                     }
                   8501:):                 }
                   8502:):             }
                   8503:):         }
                   8504:):     }
                   8505:):     if ($needs_hand_bubbles) {
          1.2.3(ra 8506:eb-19):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8507:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8508:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8509:):                &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 />').
                   8510:):                '<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 8511:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8512:):     }
                   8513:):     return;
                   8514:): }
1.423     albertel 8515: 
1.82      albertel 8516: sub scantron_process_students {
1.75      albertel 8517:     my ($r) = @_;
1.513     foxr     8518: 
1.257     albertel 8519:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 8520:     my ($symb)=&get_symb($r);
1.513     foxr     8521:     if (!$symb) {
                   8522: 	return '';
                   8523:     }
1.324     albertel 8524:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8525: 
1.596.2.12.2.  1.2.3(ra 8526:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8527:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8528:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8529:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8530:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8531:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8532:     unless (ref($navmap)) {
                   8533:         $r->print(&navmap_errormsg());
                   8534:         return '';
1.596.2.12.2.  6(raebur 8535:3):     }
1.83      albertel 8536:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8537:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8538:3):         %grader_randomlists_by_symb);
          1(raebur 8539:2):     if (ref($map)) {
                   8540:2):         $randomorder = $map->randomorder();
          6(raebur 8541:3):         $randompick = $map->randompick();
                   8542:3):     } else {
                   8543:3):         $r->print(&navmap_errormsg());
                   8544:3):         return '';
          1(raebur 8545:2):     }
          6(raebur 8546:3):     my $nav_error;
1.83      albertel 8547:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8548:3):     if ($randomorder || $randompick) {
                   8549:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8550:3):         if ($nav_error) {
                   8551:3):             $r->print(&navmap_errormsg());
                   8552:3):             return '';
1.586     raeburn  8553:         }
                   8554:     }
1.596.2.12.2.  6(raebur 8555:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8556:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8557: 
1.554     raeburn  8558:     my ($uname,$udom);
1.82      albertel 8559:     my $result= <<SCANTRONFORM;
1.81      albertel 8560: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8561:   <input type="hidden" name="command" value="scantron_configphase" />
                   8562:   $default_form_data
                   8563: SCANTRONFORM
1.82      albertel 8564:     $r->print($result);
                   8565: 
                   8566:     my @delayqueue;
1.542     raeburn  8567:     my (%completedstudents,%scandata);
1.140     albertel 8568:     
1.520     www      8569:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8570:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8571:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.140     albertel 8572:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8573: 					  'Processing first student');
1.542     raeburn  8574:     $r->print('<br />');
1.140     albertel 8575:     my $start=&Time::HiRes::time();
1.158     albertel 8576:     my $i=-1;
1.542     raeburn  8577:     my $started;
1.447     foxr     8578: 
1.596.2.12.2.  (raeburn 8579:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8580:     if ($nav_error) {
                   8581:         $r->print(&navmap_errormsg());
                   8582:         return '';
                   8583:     }
                   8584: 
1.513     foxr     8585:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8586:     # the user and return.
                   8587: 
                   8588:     if ($ssi_error) {
                   8589: 	$r->print("</form>");
                   8590: 	&ssi_print_error($r);
                   8591: 	$r->print(&show_grading_menu_form($symb));
1.520     www      8592:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8593: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8594:     }
1.447     foxr     8595: 
1.596.2.12.2.  1.2.3(ra 8596:eb-19):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8597:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8598:3):     my %orderedforcode;
1.542     raeburn  8599: 
1.157     albertel 8600:     while ($i<$scanlines->{'count'}) {
                   8601:  	($uname,$udom)=('','');
                   8602:  	$i++;
1.200     albertel 8603:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8604:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8605: 	if ($started) {
                   8606: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8607: 						     'last student');
                   8608: 	}
                   8609: 	$started=1;
1.596.2.12.2.  6(raebur 8610:3):         my %respnumlookup = ();
                   8611:3):         my %startline = ();
                   8612:3):         my $total;
1.157     albertel 8613:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8614:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8615:3):                                                  $randompick,$sequence,\@master_seq,
                   8616:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8617:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8618:3):                                                  \$total);
1.157     albertel 8619:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8620:  					      \%idmap,$i)) {
                   8621:   	    &scantron_add_delay(\@delayqueue,$line,
                   8622:  				'Unable to find a student that matches',1);
                   8623:  	    next;
                   8624:   	}
                   8625:  	if (exists $completedstudents{$uname}) {
                   8626:  	    &scantron_add_delay(\@delayqueue,$line,
                   8627:  				'Student '.$uname.' has multiple sheets',2);
                   8628:  	    next;
                   8629:  	}
1.596.2.12.2.  1(raebur 8630:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8631:2):         my $user = $uname.':'.$usec;
1.157     albertel 8632:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8633: 
1.596.2.12.2.  1(raebur 8634:2):         my $scancode;
                   8635:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8636:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8637:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8638:2):         } else {
                   8639:2):             $scancode = '';
                   8640:2):         }
                   8641:2): 
                   8642:2):         my @mapresources = @resources;
          6(raebur 8643:3):         if ($randomorder || $randompick) {
          1(raebur 8644:2):             @mapresources =
          6(raebur 8645:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8646:3):                              \%orderedforcode);
          1(raebur 8647:2):         }
1.586     raeburn  8648:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8649:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8650:             my $ressymb;
                   8651:             if (ref($resource)) {
                   8652:                 $ressymb = $resource->symb();
                   8653:             } else {
                   8654:                 $res_error = 1;
                   8655:                 last;
                   8656:             }
1.557     raeburn  8657:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8658:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 8659:7):                 my $currcode;
                   8660:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8661:7):                     $currcode = $scancode;
                   8662:7):                 }
1.557     raeburn  8663:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8664:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 8665:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   8666:7):                                               $currcode);
1.557     raeburn  8667:                 $partids_by_symb{$ressymb} = $parts;
                   8668:             } else {
                   8669:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8670:             }
1.554     raeburn  8671:         }
                   8672: 
1.586     raeburn  8673:         if ($res_error) {
                   8674:             &scantron_add_delay(\@delayqueue,$line,
                   8675:                                 'An error occurred while grading student '.$uname,2);
                   8676:             next;
                   8677:         }
                   8678: 
1.330     albertel 8679: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8680:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8681: 
                   8682: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8683: 	    &scantron_putfile($scanlines,$scan_data);
                   8684: 	}
1.161     albertel 8685: 	
1.542     raeburn  8686:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8687:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8688:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8689:3):                                    \%respnumlookup,\%startline) 
                   8690:3):             eq 'ssi_error') {
1.542     raeburn  8691:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8692:             $r->print("</form>");
                   8693:             &ssi_print_error($r);
                   8694:             $r->print(&show_grading_menu_form($symb));
                   8695:             &Apache::lonnet::remove_lock($lock);
                   8696:             return '';      # Why return ''?  Beats me.
                   8697:         }
1.513     foxr     8698: 
1.596.2.12.2.  6(raebur 8699:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8700:3):             my $parmresult =
                   8701:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8702:3):                                                        '0_examcode',2,$scancode,
                   8703:3):                                                        'string_examcode',$uname,
                   8704:3):                                                        $udom);
                   8705:3):         }
1.140     albertel 8706: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8707:         if ($env{'form.verifyrecord'}) {
                   8708:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8709:3):             if ($randompick) {
                   8710:3):                 if ($total) {
                   8711:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8712:3):                 }
                   8713:3):             }
                   8714:3): 
1.542     raeburn  8715:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8716:             chomp($studentdata);
                   8717:             $studentdata =~ s/\r$//;
                   8718:             my $studentrecord = '';
                   8719:             my $counter = -1;
1.596.2.12.2.  1(raebur 8720:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8721:                 my $ressymb = $resource->symb();
1.542     raeburn  8722:                 ($counter,my $recording) =
                   8723:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8724:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8725:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8726:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8727:                 $studentrecord .= $recording;
                   8728:             }
                   8729:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8730:                 &Apache::lonxml::clear_problem_counter();
                   8731:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8732:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8733:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8734:3):                                            \%respnumlookup,\%startline)
                   8735:3):                     eq 'ssi_error') {
1.554     raeburn  8736:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8737:                     $r->print("</form>");
                   8738:                     &ssi_print_error($r);
                   8739:                     $r->print(&show_grading_menu_form($symb));
                   8740:                     &Apache::lonnet::remove_lock($lock);
                   8741:                     delete($completedstudents{$uname});
                   8742:                     return '';
                   8743:                 }
1.542     raeburn  8744:                 $counter = -1;
                   8745:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8746:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8747:                     my $ressymb = $resource->symb();
1.542     raeburn  8748:                     ($counter,my $recording) =
                   8749:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8750:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8751:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8752:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8753:3):                                                  \%startline);
1.542     raeburn  8754:                     $studentrecord .= $recording;
                   8755:                 }
                   8756:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8757:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8758:                     if ($scancode eq '') {
1.596.2.6  raeburn  8759:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8760:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8761:                     } else {
1.596.2.6  raeburn  8762:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8763:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8764:                     }
                   8765:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8766:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8767:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8768:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8769:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8770:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8771:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8772:                               &Apache::loncommon::end_data_table_row().
                   8773:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8774:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8775:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8776:                               &Apache::loncommon::end_data_table_row().
                   8777:                               &Apache::loncommon::end_data_table().'</p>');
                   8778:                 } else {
                   8779:                     $r->print('<br /><span class="LC_warning">'.
                   8780:                              &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 />'.
                   8781:                              &mt("As a consequence, this user's submission history records two tries.").
                   8782:                                  '</span><br />');
                   8783:                 }
                   8784:             }
                   8785:         }
1.543     raeburn  8786:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8787:     } continue {
1.330     albertel 8788: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8789: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8790:     }
1.140     albertel 8791:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8792:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8793: #    my $lasttime = &Time::HiRes::time()-$start;
                   8794: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8795: 
1.200     albertel 8796:     $r->print("</form>");
1.324     albertel 8797:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8798:     return '';
1.75      albertel 8799: }
1.157     albertel 8800: 
1.557     raeburn  8801: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8802:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8803:):         $bubbles_per_row) = @_;
1.557     raeburn  8804:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8805:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8806:         foreach my $resource (@{$resources}) {
                   8807:             my $ressymb = $resource->symb();
                   8808:             my ($analysis,$parts) =
                   8809:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8810:):                                           $env{'user.name'},$env{'user.domain'},
                   8811:):                                           1,$bubbles_per_row);
1.557     raeburn  8812:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8813:             if (ref($analysis) eq 'HASH') {
                   8814:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8815:                     $grader_randomlists_by_symb->{$ressymb} =
                   8816:                         $analysis->{'parts_withrandomlist'};
                   8817:                 }
                   8818:             }
                   8819:         }
                   8820:     }
                   8821:     return;
                   8822: }
                   8823: 
1.596.2.12.2.  1(raebur 8824:2): =pod
                   8825:2): 
                   8826:2): =item users_order
                   8827:2): 
                   8828:2):   Returns array of resources in current map, ordered based on either CODE,
                   8829:2):   if this is a CODEd exam, or based on student's identity if this is a
                   8830:2):   "NAMEd" exam.
                   8831:2): 
          6(raebur 8832:3):   Should be used when randomorder and/or randompick applied when the 
                   8833:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   8834:3):   for the version of the exam the student received.
          1(raebur 8835:2): 
                   8836:2): =cut
                   8837:2): 
                   8838:2): sub users_order  {
          6(raebur 8839:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 8840:2):     my @mapresources;
          6(raebur 8841:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 8842:2):         return @mapresources;
                   8843:2):     }
          6(raebur 8844:3):     if ($scancode) {
                   8845:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8846:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   8847:3):         } else {
                   8848:3):             $env{'form.CODE'} = $scancode;
                   8849:3):             my $actual_seq =
                   8850:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8851:3):                                                                $master_seq,
                   8852:3):                                                                $user,$scancode,1);
                   8853:3):             if (ref($actual_seq) eq 'ARRAY') {
                   8854:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8855:3):                 if (ref($orderedforcode) eq 'HASH') {
                   8856:3):                     if (@mapresources > 0) {
                   8857:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   8858:3):                     }
                   8859:3):                 }
                   8860:3):             }
                   8861:3):             delete($env{'form.CODE'});
          1(raebur 8862:2):         }
                   8863:2):     } else {
                   8864:2):         my $actual_seq =
                   8865:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8866:2):                                                            $master_seq,
          5(raebur 8867:3):                                                            $user,undef,1);
          1(raebur 8868:2):         if (ref($actual_seq) eq 'ARRAY') {
                   8869:2):             @mapresources =
                   8870:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8871:2):         }
          6(raebur 8872:3):     }
                   8873:3):     return @mapresources;
          1(raebur 8874:2): }
                   8875:2): 
1.542     raeburn  8876: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 8877:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8878:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8879:3):     my $uselookup = 0;
                   8880:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8881:3):         (ref($startline) eq 'HASH')) {
                   8882:3):         $uselookup = 1;
                   8883:3):     }
                   8884:3): 
1.554     raeburn  8885:     if (ref($resources) eq 'ARRAY') {
                   8886:         my $count = 0;
                   8887:         foreach my $resource (@{$resources}) {
                   8888:             my $ressymb = $resource->symb();
                   8889:             my %form = ('submitted'      => 'scantron',
                   8890:                         'grade_target'   => 'grade',
                   8891:                         'grade_username' => $uname,
                   8892:                         'grade_domain'   => $udom,
                   8893:                         'grade_courseid' => $env{'request.course.id'},
                   8894:                         'grade_symb'     => $ressymb,
                   8895:                         'CODE'           => $scancode
                   8896:                        );
1.596.2.12.2.  (raeburn 8897:):             if ($bubbles_per_row ne '') {
                   8898:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8899:):             }
                   8900:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8901:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8902:):             }
1.554     raeburn  8903:             if (ref($parts) eq 'HASH') {
                   8904:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8905:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 8906:3):                         if ($uselookup) {
                   8907:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8908:3):                         } else {
                   8909:3):                             $form{'scantron_questnum_start.'.$part} =
                   8910:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8911:3):                         }
1.554     raeburn  8912:                         $count++;
                   8913:                     }
                   8914:                 }
                   8915:             }
                   8916:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8917:             return 'ssi_error' if ($ssi_error);
                   8918:             last if (&Apache::loncommon::connection_aborted($r));
                   8919:         }
1.542     raeburn  8920:     }
                   8921:     return;
                   8922: }
                   8923: 
1.157     albertel 8924: sub scantron_upload_scantron_data {
                   8925:     my ($r)=@_;
1.565     raeburn  8926:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  1.2.3(ra 8927:eb-19):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  8928:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8929:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8930:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8931: 							  'domainid',
1.565     raeburn  8932: 							  'coursename',$dom);
                   8933:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 8934:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   8935:):     my ($symb) = &get_symb($r,1);
                   8936:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8937:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 8938:6):     &js_escape(\$nofile_alert);
1.579     raeburn  8939:     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.596.2.12.2.  6(raebur 8940:6):     &js_escape(\$nocourseid_alert);
          1.2.3(ra 8941:eb-19):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8942:     function checkUpload(formname) {
                   8943: 	if (formname.upfile.value == "") {
1.579     raeburn  8944: 	    alert("'.$nofile_alert.'");
1.157     albertel 8945: 	    return false;
                   8946: 	}
1.565     raeburn  8947:         if (formname.courseid.value == "") {
1.579     raeburn  8948:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8949:             return false;
                   8950:         }
1.157     albertel 8951: 	formname.submit();
                   8952:     }
1.565     raeburn  8953: 
                   8954:     function ToSyllabus() {
                   8955:         var cdom = '."'$dom'".';
                   8956:         var cnum = document.rules.courseid.value;
                   8957:         if (cdom == "" || cdom == null) {
                   8958:             return;
                   8959:         }
                   8960:         if (cnum == "" || cnum == null) {
                   8961:            return;
                   8962:         }
                   8963:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8964:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8965:         return;
                   8966:     }
                   8967: 
1.596.2.12.2.  1.2.3(ra 8968:eb-19):     '.$formatjs.'
                   8969:eb-19): '));
                   8970:eb-19):     $r->print('
1.596.2.4  raeburn  8971: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8972: 
1.492     albertel 8973: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8974: '.$default_form_data.
                   8975:   &Apache::lonhtmlcommon::start_pick_box().
                   8976:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8977:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8978:   &Apache::lonhtmlcommon::row_closure().
                   8979:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8980:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8981:   &Apache::lonhtmlcommon::row_closure().
                   8982:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8983:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  1.2.3(ra 8984:eb-19):   &Apache::lonhtmlcommon::row_closure());
                   8985:eb-19):     if ($formatoptions) {
                   8986:eb-19):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   8987:eb-19):                   &Apache::lonhtmlcommon::row_closure());
                   8988:eb-19):     }
                   8989:eb-19):     $r->print(
1.565     raeburn  8990:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8991:   '<input type="file" name="upfile" size="50" />'.
                   8992:   &Apache::lonhtmlcommon::row_closure(1).
                   8993:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8994: 
1.492     albertel 8995: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8996: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8997: </form>
1.492     albertel 8998: ');
1.157     albertel 8999:     return '';
                   9000: }
                   9001: 
1.596.2.12.2.  1.2.3(ra 9002:eb-19): sub scantron_upload_dataformat {
                   9003:eb-19):     my ($dom) = @_;
                   9004:eb-19):     my ($formatoptions,$formattitle,$formatjs);
                   9005:eb-19):     $formatjs = <<'END';
                   9006:eb-19): function toggleScantab(form) {
                   9007:eb-19):    return;
                   9008:eb-19): }
                   9009:eb-19): END
                   9010:eb-19):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9011:eb-19):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9012:eb-19):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9013:eb-19):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9014:eb-19):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9015:eb-19):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9016:eb-19):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9017:eb-19):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9018:eb-19):                             my ($onclick,$formatextra,$singleline);
                   9019:eb-19):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9020:eb-19):                             my $count = 0;
                   9021:eb-19):                             foreach my $line (@lines) {
                   9022:eb-19):                                 next if ($line =~ /^#/);
                   9023:eb-19):                                 $singleline = $line;
                   9024:eb-19):                                 $count ++;
                   9025:eb-19):                             }
                   9026:eb-19):                             if ($count > 1) {
                   9027:eb-19):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9028:eb-19):                                                '<span class="LC_nobreak">'.
                   9029:eb-19):                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9030:eb-19):                                                &scantron_scantab().'</span></div>';
                   9031:eb-19):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9032:eb-19):                                 $formatjs = <<"END";
                   9033:eb-19): function toggleScantab(form) {
                   9034:eb-19):     var divid = 'bubbletype';
                   9035:eb-19):     if (document.getElementById(divid)) {
                   9036:eb-19):         var radioname = 'fileformat';
                   9037:eb-19):         var num = form.elements[radioname].length;
                   9038:eb-19):         if (num) {
                   9039:eb-19):             for (var i=0; i<num; i++) {
                   9040:eb-19):                 if (form.elements[radioname][i].checked) {
                   9041:eb-19):                     var chosen = form.elements[radioname][i].value;
                   9042:eb-19):                     if (chosen == 'dat') {
                   9043:eb-19):                         document.getElementById(divid).style.display = 'none';
                   9044:eb-19):                     } else if (chosen == 'csv') {
                   9045:eb-19):                         document.getElementById(divid).style.display = 'block';
                   9046:eb-19):                     }
                   9047:eb-19):                 }
                   9048:eb-19):             }
                   9049:eb-19):         }
                   9050:eb-19):     }
                   9051:eb-19):     return;
                   9052:eb-19): }
                   9053:eb-19): 
                   9054:eb-19): END
                   9055:eb-19):                             } elsif ($count == 1) {
                   9056:eb-19):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9057:eb-19):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9058:eb-19):                             }
                   9059:eb-19):                             $formattitle = &mt('File format');
                   9060:eb-19):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9061:eb-19):                                              &mt('Plain Text (no delimiters)').
                   9062:eb-19):                                              '</label>'.('&nbsp;'x2).
                   9063:eb-19):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9064:eb-19):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9065:eb-19):                         }
                   9066:eb-19):                     }
                   9067:eb-19):                 }
                   9068:eb-19):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9069:eb-19):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9070:eb-19):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9071:eb-19):                         $formattitle = &mt('Bubblesheet type');
                   9072:eb-19):                         $formatoptions = &scantron_scantab();
                   9073:eb-19):                     }
                   9074:eb-19):                 }
                   9075:eb-19):             }
                   9076:eb-19):         }
                   9077:eb-19):     }
                   9078:eb-19):     return ($formatoptions,$formattitle,$formatjs);
                   9079:eb-19): }
1.423     albertel 9080: 
1.157     albertel 9081: sub scantron_upload_scantron_data_save {
                   9082:     my($r)=@_;
1.324     albertel 9083:     my ($symb)=&get_symb($r,1);
1.182     albertel 9084:     my $doanotherupload=
                   9085: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9086: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9087: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9088: 	'</form>'."\n";
1.257     albertel 9089:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9090: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9091: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9092: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 9093: 	if ($symb) {
1.324     albertel 9094: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 9095: 	} else {
                   9096: 	    $r->print($doanotherupload);
                   9097: 	}
1.162     albertel 9098: 	return '';
                   9099:     }
1.257     albertel 9100:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9101:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9102:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9103:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9104:3):         $r->print(
                   9105:3):             &Apache::lonhtmlcommon::confirm_success(
                   9106:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9107:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9108:     } else {
1.596.2.12.2.  1.2.3(ra 9109:eb-19):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9110:eb-19):         my $parser;
                   9111:eb-19):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9112:eb-19):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9113:eb-19):                 my $is_csv;
                   9114:eb-19):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9115:eb-19):                 if (@possibles > 1) {
                   9116:eb-19):                     if ($env{'form.fileformat'} eq 'csv') {
                   9117:eb-19):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9118:eb-19):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9119:eb-19):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9120:eb-19):                                     $is_csv = 1;
                   9121:eb-19):                                 }
                   9122:eb-19):                             }
                   9123:eb-19):                         }
                   9124:eb-19):                     }
                   9125:eb-19):                 } elsif (@possibles == 1) {
                   9126:eb-19):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9127:eb-19):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9128:eb-19):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9129:eb-19):                                 $is_csv = 1;
                   9130:eb-19):                             }
                   9131:eb-19):                         }
                   9132:eb-19):                     }
                   9133:eb-19):                 }
                   9134:eb-19):                 if ($is_csv) {
                   9135:eb-19):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9136:eb-19):                 }
                   9137:eb-19):             }
                   9138:eb-19):         }
                   9139:eb-19):         my $result =
                   9140:eb-19):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9141:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9142: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9143:3):             $r->print(
                   9144:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9145:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9146:3):                         (length($env{'form.upfile'})-1),
                   9147:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9148:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9149:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9150:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9151: 	} else {
1.596.2.12.2.  5(raebur 9152:3):             $r->print(
                   9153:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9154:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9155:3):                           $result,
1.568     raeburn  9156: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9157: 	}
                   9158:     }
1.174     albertel 9159:     if ($symb) {
1.209     ng       9160: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 9161:     } else {
1.182     albertel 9162: 	$r->print($doanotherupload);
1.174     albertel 9163:     }
1.157     albertel 9164:     return '';
                   9165: }
                   9166: 
1.567     raeburn  9167: sub validate_uploaded_scantron_file {
                   9168:     my ($cdom,$cname,$fname) = @_;
                   9169:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9170:     my @lines;
                   9171:     if ($scanlines ne '-1') {
                   9172:         @lines=split("\n",$scanlines,-1);
                   9173:     }
                   9174:     my $output;
                   9175:     if (@lines) {
                   9176:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9177:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9178:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9179:         my %idmap = &username_to_idmap($classlist);
                   9180:         foreach my $key (keys(%idmap)) {
                   9181:             my $lckey = lc($key);
                   9182:             $idmap{$lckey} = $idmap{$key};
                   9183:         }
                   9184:         my %unique_formats;
1.596.2.12.2.  1.2.4(ra 9185:eb-19):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9186:         foreach my $line (@formatlines) {
                   9187:             chomp($line);
                   9188:             my @config = split(/:/,$line);
                   9189:             my $idstart = $config[5];
                   9190:             my $idlength = $config[6];
                   9191:             if (($idstart ne '') && ($idlength > 0)) {
                   9192:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9193:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9194:                 } else {
                   9195:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9196:                 }
                   9197:             }
                   9198:         }
                   9199:         foreach my $key (keys(%unique_formats)) {
                   9200:             my ($idstart,$idlength) = split(':',$key);
                   9201:             %{$counts{$key}} = (
                   9202:                                'found'   => 0,
                   9203:                                'total'   => 0,
                   9204:                               );
                   9205:             foreach my $line (@lines) {
                   9206:                 next if ($line =~ /^#/);
                   9207:                 next if ($line =~ /^[\s\cz]*$/);
                   9208:                 my $id = substr($line,$idstart-1,$idlength);
                   9209:                 $id = lc($id);
                   9210:                 if (exists($idmap{$id})) {
                   9211:                     $counts{$key}{'found'} ++;
                   9212:                 }
                   9213:                 $counts{$key}{'total'} ++;
                   9214:             }
                   9215:             if ($counts{$key}{'total'}) {
                   9216:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9217:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9218:                     $max_match_pct = $percent_match;
                   9219:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9220:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9221:                     $max_match_count = $counts{$key}{'total'};
                   9222:                 }
                   9223:             }
                   9224:         }
                   9225:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9226:             my $format_descs;
                   9227:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9228:             for (my $i=0; $i<$numwithformat; $i++) {
                   9229:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9230:                 if ($i<$numwithformat-2) {
                   9231:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9232:                 } elsif ($i==$numwithformat-2) {
                   9233:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9234:                 } elsif ($i==$numwithformat-1) {
                   9235:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9236:                 }
                   9237:             }
                   9238:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9239:3):             $output .= '<br />';
                   9240:3):             if ($found_match_count == $max_match_count) {
                   9241:3):                 # 100% matching entries
                   9242:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9243:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9244:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9245:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9246:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9247:3):                     ' in the file (for the format defined for [_3]).',
                   9248:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9249:3):             } else {
                   9250:3):                 # Not all entries matching? -> Show warning and additional info
                   9251:3):                 $output .=
                   9252:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9253:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9254:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9255:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9256:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9257:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9258:3):                         ' in the file (for the format defined for [_3]).',
                   9259:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9260:3):                     '<p class="LC_info">'.
                   9261:3):                     &mt('A low percentage of matches results from one of the following:').
                   9262:3):                     '</p><ul>'.
                   9263:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9264:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9265:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9266:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9267:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9268:3):                     '</ul>';
                   9269:3):             }
1.567     raeburn  9270:         }
                   9271:     } else {
1.596.2.12.2.  5(raebur 9272:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9273:     }
                   9274:     return $output;
                   9275: }
                   9276: 
1.202     albertel 9277: sub valid_file {
                   9278:     my ($requested_file)=@_;
                   9279:     foreach my $filename (sort(&scantron_filenames())) {
                   9280: 	if ($requested_file eq $filename) { return 1; }
                   9281:     }
                   9282:     return 0;
                   9283: }
                   9284: 
                   9285: sub scantron_download_scantron_data {
                   9286:     my ($r)=@_;
1.596.2.12.2.  (raeburn 9287:):     my ($symb) = &get_symb($r,1);
                   9288:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9289:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9290:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9291:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9292:     if (! &valid_file($file)) {
1.492     albertel 9293: 	$r->print('
1.202     albertel 9294: 	<p>
1.596.2.12.2.  3(raebur 9295:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9296:         </p>
1.492     albertel 9297: ');
1.596.2.12.2.  (raeburn 9298:): 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 9299: 	return;
                   9300:     }
                   9301:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9302:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9303:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9304:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9305:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9306:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9307:     $r->print('
1.202     albertel 9308:     <p>
1.596.2.12.2.  8(raebur 9309:4): 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
1.492     albertel 9310: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9311:     </p>
                   9312:     <p>
1.492     albertel 9313: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9314: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9315:     </p>
                   9316:     <p>
1.492     albertel 9317: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9318: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9319:     </p>
1.492     albertel 9320: ');
1.596.2.12.2.  (raeburn 9321:):     $r->print(&show_grading_menu_form($symb));
1.202     albertel 9322:     return '';
                   9323: }
1.157     albertel 9324: 
1.523     raeburn  9325: sub checkscantron_results {
                   9326:     my ($r) = @_;
                   9327:     my ($symb)=&get_symb($r);
                   9328:     if (!$symb) {return '';}
                   9329:     my $grading_menu_button=&show_grading_menu_form($symb);
                   9330:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  1.2.3(ra 9331:eb-19):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9332:     my $numletts = scalar(keys(%lettdig));
                   9333:     my $cnum = $env{'course.'.$cid.'.num'};
                   9334:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9335:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9336:     my %record;
                   9337:     my %scantron_config =
1.596.2.12.2.  1.2.3(ra 9338:eb-19):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9339:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9340:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9341:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9342:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9343:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9344:     unless (ref($navmap)) {
                   9345:         $r->print(&navmap_errormsg());
                   9346:         return '';
                   9347:     }
1.523     raeburn  9348:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9349:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9350:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9351:2):     if (ref($map)) {
                   9352:2):         $randomorder=$map->randomorder();
          7(raebur 9353:3):         $randompick=$map->randompick();
          1(raebur 9354:2):     }
1.557     raeburn  9355:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9356:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9357:3):     if ($nav_error) {
                   9358:3):         $r->print(&navmap_errormsg());
                   9359:3):         return '';
          1(raebur 9360:2):     }
          (raeburn 9361:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9362:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9363:     my ($uname,$udom);
1.523     raeburn  9364:     my (%scandata,%lastname,%bylast);
                   9365:     $r->print('
                   9366: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9367: 
                   9368:     my @delayqueue;
                   9369:     my %completedstudents;
                   9370: 
1.596.2.12.2.  6(raebur 9371:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9372:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9373:3):     my ($username,$domain,$started);
          (raeburn 9374:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9375:     if ($nav_error) {
                   9376:         $r->print(&navmap_errormsg());
                   9377:         return '';
                   9378:     }
1.523     raeburn  9379: 
                   9380:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9381:                                           'Processing first student');
                   9382:     my $start=&Time::HiRes::time();
                   9383:     my $i=-1;
                   9384: 
                   9385:     while ($i<$scanlines->{'count'}) {
                   9386:         ($username,$domain,$uname)=('','','');
                   9387:         $i++;
                   9388:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9389:         if ($line=~/^[\s\cz]*$/) { next; }
                   9390:         if ($started) {
                   9391:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9392:                                                      'last student');
                   9393:         }
                   9394:         $started=1;
                   9395:         my $scan_record=
                   9396:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9397:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9398:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9399:3):                                               \%idmap,$i)) {
1.523     raeburn  9400:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9401:                                 'Unable to find a student that matches',1);
                   9402:             next;
                   9403:         }
                   9404:         if (exists $completedstudents{$uname}) {
                   9405:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9406:                                 'Student '.$uname.' has multiple sheets',2);
                   9407:             next;
                   9408:         }
                   9409:         my $pid = $scan_record->{'scantron.ID'};
                   9410:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9411:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9412:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9413:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9414:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9415:2): 
                   9416:2):         my $scancode;
                   9417:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9418:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9419:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9420:2):         } else {
                   9421:2):             $scancode = '';
                   9422:2):         }
                   9423:2): 
                   9424:2):         my @mapresources = @resources;
          6(raebur 9425:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9426:3):         my %respnumlookup=();
                   9427:3):         my %startline=();
                   9428:3):         if ($randomorder || $randompick) {
          1(raebur 9429:2):             @mapresources =
          6(raebur 9430:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9431:3):                              \%orderedforcode);
                   9432:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9433:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9434:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9435:3):                                              \%respnumlookup,\%startline);
                   9436:3):             if ($randompick && $total) {
                   9437:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9438:3):             }
          1(raebur 9439:2):         }
          6(raebur 9440:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9441:3):         chomp($scandata{$pid});
                   9442:3):         $scandata{$pid} =~ s/\r$//;
                   9443:3): 
1.523     raeburn  9444:         my $counter = -1;
1.596.2.12.2.  1(raebur 9445:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9446:             my $parts;
1.554     raeburn  9447:             my $ressymb = $resource->symb();
1.557     raeburn  9448:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9449:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9450:7):                 my $currcode;
                   9451:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9452:7):                     $currcode = $scancode;
                   9453:7):                 }
1.557     raeburn  9454:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9455:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9456:):                                               $username,$domain,undef,
          1(raebur 9457:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9458:             } else {
                   9459:                 $parts = $grader_partids_by_symb{$ressymb};
                   9460:             }
1.542     raeburn  9461:             ($counter,my $recording) =
                   9462:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9463:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9464:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9465:3):                                          $randomorder,$randompick,
                   9466:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9467:             $record{$pid} .= $recording;
1.523     raeburn  9468:         }
                   9469:     }
                   9470:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9471:     $r->print('<br />');
                   9472:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9473:     $passed = 0;
                   9474:     $failed = 0;
                   9475:     $numstudents = 0;
                   9476:     foreach my $last (sort(keys(%bylast))) {
                   9477:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9478:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9479:                 my $showscandata = $scandata{$pid};
                   9480:                 my $showrecord = $record{$pid};
                   9481:                 $showscandata =~ s/\s/&nbsp;/g;
                   9482:                 $showrecord =~ s/\s/&nbsp;/g;
                   9483:                 if ($scandata{$pid} eq $record{$pid}) {
                   9484:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9485:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9486: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9487: '</tr>'."\n".
                   9488: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9489:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9490:                     $passed ++;
                   9491:                 } else {
                   9492:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9493:                     $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  9494: '</tr>'."\n".
                   9495: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9496:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9497: '</tr>'."\n";
                   9498:                     $failed ++;
                   9499:                 }
                   9500:                 $numstudents ++;
                   9501:             }
                   9502:         }
                   9503:     }
1.596.2.4  raeburn  9504:     $r->print('<p>'.
1.596.2.8  raeburn  9505:               &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  9506:                   '<b>',
                   9507:                   $numstudents,
                   9508:                   '</b>',
                   9509:                   $env{'form.scantron_maxbubble'}).
                   9510:               '</p>'
                   9511:     );
1.596.2.12.2.  2(raebur 9512:2):     $r->print('<p>'
                   9513:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9514:2):              .'<br />'
                   9515:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9516:2):              .'</p>');
1.523     raeburn  9517:     if ($passed) {
1.572     www      9518:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9519:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9520:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9521:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9522:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9523:                  $okstudents."\n".
                   9524:                  &Apache::loncommon::end_data_table().'<br />');
                   9525:     }
                   9526:     if ($failed) {
1.572     www      9527:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9528:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9529:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9530:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9531:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9532:                  $badstudents."\n".
                   9533:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9534:                  &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  9535:     }
                   9536:     $r->print('</form><br />'.$grading_menu_button);
                   9537:     return;
                   9538: }
                   9539: 
1.542     raeburn  9540: sub verify_scantron_grading {
1.554     raeburn  9541:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9542:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9543:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9544:     my ($record,%expected,%startpos);
                   9545:     return ($counter,$record) if (!ref($resource));
                   9546:     return ($counter,$record) if (!$resource->is_problem());
                   9547:     my $symb = $resource->symb();
1.554     raeburn  9548:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9549:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9550:         $counter ++;
                   9551:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9552:3):         my $respnum = $counter;
                   9553:3):         if ($randomorder || $randompick) {
                   9554:3):             $respnum = $respnumlookup->{$counter};
                   9555:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9556:3):         } else {
                   9557:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9558:3):         }
                   9559:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9560:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9561:             foreach my $item (@sub_lines) {
                   9562:                 $expected{$part_id} += $item;
                   9563:             }
                   9564:         } else {
1.596.2.12.2.  6(raebur 9565:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9566:         }
                   9567:     }
                   9568:     if ($symb) {
                   9569:         my %recorded;
                   9570:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9571:         if ($returnhash{'version'}) {
                   9572:             my %lasthash=();
                   9573:             my $version;
                   9574:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9575:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9576:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9577:                 }
                   9578:             }
                   9579:             foreach my $key (keys(%lasthash)) {
                   9580:                 if ($key =~ /\.scantron$/) {
                   9581:                     my $value = &unescape($lasthash{$key});
                   9582:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9583:                     if ($value eq '') {
                   9584:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9585:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9586:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9587:                             }
                   9588:                         }
                   9589:                     } else {
                   9590:                         my @tocheck;
                   9591:                         my @items = split(//,$value);
                   9592:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9593:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9594:                             if (@items < $expected{$part_id}) {
                   9595:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9596:                                 my @singles = split(//,$fragment);
                   9597:                                 foreach my $pos (@singles) {
                   9598:                                     if ($pos eq ' ') {
                   9599:                                         push(@tocheck,$pos);
                   9600:                                     } else {
                   9601:                                         my $next = shift(@items);
                   9602:                                         push(@tocheck,$next);
                   9603:                                     }
                   9604:                                 }
                   9605:                             } else {
                   9606:                                 @tocheck = @items;
                   9607:                             }
                   9608:                             foreach my $letter (@tocheck) {
                   9609:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9610:                                     if ($letter !~ /^[A-J]$/) {
                   9611:                                         $letter = $scantron_config->{'Qoff'};
                   9612:                                     }
                   9613:                                     $recorded{$part_id} .= $letter;
                   9614:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9615:                                     my $digit;
                   9616:                                     if ($letter !~ /^[A-J]$/) {
                   9617:                                         $digit = $scantron_config->{'Qoff'};
                   9618:                                     } else {
                   9619:                                         $digit = $lettdig->{$letter};
                   9620:                                     }
                   9621:                                     $recorded{$part_id} .= $digit;
                   9622:                                 }
                   9623:                             }
                   9624:                         } else {
                   9625:                             @tocheck = @items;
                   9626:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9627:                                 my $curr_sub = shift(@tocheck);
                   9628:                                 my $digit;
                   9629:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9630:                                     $digit = $lettdig->{$curr_sub}-1;
                   9631:                                 }
                   9632:                                 if ($curr_sub eq 'J') {
                   9633:                                     $digit += scalar($numletts);
                   9634:                                 }
                   9635:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9636:                                     if ($j == $digit) {
                   9637:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9638:                                     } else {
                   9639:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9640:                                     }
                   9641:                                 }
                   9642:                             }
                   9643:                         }
                   9644:                     }
                   9645:                 }
                   9646:             }
                   9647:         }
1.554     raeburn  9648:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9649:             if ($recorded{$part_id} eq '') {
                   9650:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9651:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9652:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9653:                     }
                   9654:                 }
                   9655:             }
                   9656:             $record .= $recorded{$part_id};
                   9657:         }
                   9658:     }
                   9659:     return ($counter,$record);
                   9660: }
                   9661: 
1.75      albertel 9662: #-------- end of section for handling grading scantron forms -------
                   9663: #
                   9664: #-------------------------------------------------------------------
                   9665: 
1.72      ng       9666: #-------------------------- Menu interface -------------------------
                   9667: #
                   9668: #--- Show a Grading Menu button - Calls the next routine ---
                   9669: sub show_grading_menu_form {
1.324     albertel 9670:     my ($symb)=@_;
1.125     ng       9671:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 9672: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 9673: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       9674: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 9675: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       9676: 	'</form>'."\n";
                   9677:     return $result;
                   9678: }
                   9679: 
1.77      ng       9680: # -- Retrieve choices for grading form
                   9681: sub savedState {
                   9682:     my %savedState = ();
1.257     albertel 9683:     if ($env{'form.saveState'}) {
                   9684: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       9685: 	    my ($key,$value) = split(/=/,$_,2);
                   9686: 	    $savedState{$key} = $value;
                   9687: 	}
                   9688:     }
                   9689:     return \%savedState;
                   9690: }
1.76      ng       9691: 
1.596.2.12.2.  (raeburn 9692:): #--- Href with symb and command ---
                   9693:): 
                   9694:): sub href_symb_cmd {
                   9695:):     my ($symb,$cmd)=@_;
                   9696:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9697:): }
                   9698:): 
1.443     banghart 9699: sub grading_menu {
                   9700:     my ($request) = @_;
                   9701:     my ($symb)=&get_symb($request);
                   9702:     if (!$symb) {return '';}
                   9703:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   9704:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   9705: 
1.444     banghart 9706:     $request->print($table);
1.443     banghart 9707:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   9708:                   'handgrade'=>$hdgrade,
                   9709:                   'probTitle'=>$probTitle,
                   9710:                   'command'=>'submit_options',
                   9711:                   'saveState'=>"",
                   9712:                   'gradingMenu'=>1,
                   9713:                   'showgrading'=>"yes");
1.538     schulted 9714:     
                   9715:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9716:     
1.443     banghart 9717:     $fields{'command'} = 'csvform';
1.538     schulted 9718:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9719:     
1.443     banghart 9720:     $fields{'command'} = 'processclicker';
1.538     schulted 9721:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9722:     
1.443     banghart 9723:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9724:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9725:     
                   9726:     my @menu = ({	categorytitle=>'Course Grading',
                   9727:             items =>[
                   9728:                         {	linktext => 'Manual Grading/View Submissions',
                   9729:                     		url => $url1,
                   9730:                     		permission => 'F',
                   9731:                     		icon => 'edit-find-replace.png',
                   9732:                     		linktitle => 'Start the process of hand grading submissions.'
                   9733:                         },
                   9734:                 	    {	linktext => 'Upload Scores',
                   9735:                     		url => $url2,
                   9736:                     		permission => 'F',
                   9737:                     		icon => 'uploadscores.png',
                   9738:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9739:                 	    },
                   9740:                 	    {	linktext => 'Process Clicker',
                   9741:                     		url => $url3,
                   9742:                     		permission => 'F',
                   9743:                     		icon => 'addClickerInfoFile.png',
                   9744:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9745:                 	    },
1.587     raeburn  9746:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9747:                     		url => $url4,
                   9748:                     		permission => 'F',
                   9749:                     		icon => 'stat.png',
1.596.2.4  raeburn  9750:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 9751:                 	    }
                   9752:                     ]
                   9753:             });
                   9754: 
                   9755:     #$fields{'command'} = 'verify';
                   9756:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 9757:     #
                   9758:     # Create the menu
                   9759:     my $Str;
1.444     banghart 9760:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 9761:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9762:     $Str .= '<input type="hidden" name="command" value="" />'.
                   9763:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   9764: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 9765: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 9766: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   9767: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   9768: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9769: 
1.538     schulted 9770:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   9771:     #$menudata->{'jscript'}
1.584     bisitz   9772:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   9773:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 9774:         ' /> '.
                   9775:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   9776:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 9777: 
1.444     banghart 9778:     $Str .="</form>\n";
1.539     riegler  9779:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 9780:     $request->print(<<GRADINGMENUJS);
                   9781: <script type="text/javascript" language="javascript">
                   9782:     function checkChoice(formname,val,cmdx) {
                   9783: 	if (val <= 2) {
                   9784: 	    var cmd = radioSelection(formname.radioChoice);
                   9785: 	    var cmdsave = cmd;
                   9786: 	} else {
                   9787: 	    cmd = cmdx;
                   9788: 	    cmdsave = 'submission';
                   9789: 	}
                   9790: 	formname.command.value = cmd;
                   9791: 	if (val < 5) formname.submit();
                   9792: 	if (val == 5) {
1.458     banghart 9793: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   9794: 	        return false;
                   9795: 	    } else {
                   9796: 	        formname.submit();
                   9797: 	    }
1.445     banghart 9798: 	}
                   9799:     }
1.443     banghart 9800: 
                   9801:     function checkReceiptNo(formname,nospace) {
                   9802: 	var receiptNo = formname.receipt.value;
                   9803: 	var checkOpt = false;
                   9804: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9805: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9806: 	if (checkOpt) {
1.539     riegler  9807: 	    alert("$receiptalert");
1.443     banghart 9808: 	    formname.receipt.value = "";
                   9809: 	    formname.receipt.focus();
                   9810: 	    return false;
                   9811: 	}
                   9812: 	return true;
                   9813:     }
                   9814: </script>
                   9815: GRADINGMENUJS
                   9816:     &commonJSfunctions($request);
                   9817:     return $Str;    
                   9818: }
                   9819: 
                   9820: 
                   9821: #--- Displays the submissions first page -------
                   9822: sub submit_options {
1.72      ng       9823:     my ($request) = @_;
1.324     albertel 9824:     my ($symb)=&get_symb($request);
1.72      ng       9825:     if (!$symb) {return '';}
1.76      ng       9826:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       9827: 
1.539     riegler  9828:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       9829:     $request->print(<<GRADINGMENUJS);
                   9830: <script type="text/javascript" language="javascript">
1.116     ng       9831:     function checkChoice(formname,val,cmdx) {
                   9832: 	if (val <= 2) {
                   9833: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       9834: 	    var cmdsave = cmd;
1.116     ng       9835: 	} else {
                   9836: 	    cmd = cmdx;
1.118     ng       9837: 	    cmdsave = 'submission';
1.116     ng       9838: 	}
                   9839: 	formname.command.value = cmd;
1.118     ng       9840: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 9841: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       9842: 	if (val < 5) formname.submit();
                   9843: 	if (val == 5) {
1.72      ng       9844: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   9845: 	    formname.submit();
                   9846: 	}
1.238     albertel 9847: 	if (val < 7) formname.submit();
1.72      ng       9848:     }
                   9849: 
                   9850:     function checkReceiptNo(formname,nospace) {
                   9851: 	var receiptNo = formname.receipt.value;
                   9852: 	var checkOpt = false;
                   9853: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9854: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9855: 	if (checkOpt) {
1.539     riegler  9856: 	    alert("$receiptalert");
1.72      ng       9857: 	    formname.receipt.value = "";
                   9858: 	    formname.receipt.focus();
                   9859: 	    return false;
                   9860: 	}
                   9861: 	return true;
                   9862:     }
                   9863: </script>
                   9864: GRADINGMENUJS
1.118     ng       9865:     &commonJSfunctions($request);
1.324     albertel 9866:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 9867:     my $result;
1.76      ng       9868:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       9869:     my $savedState = &savedState();
1.118     ng       9870:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       9871:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       9872:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       9873:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       9874: 
1.533     bisitz   9875:     # Preselect sections
                   9876:     my $selsec="";
                   9877:     if (ref($sections)) {
                   9878:         foreach my $section (sort(@$sections)) {
                   9879:             $selsec.='<option value="'.$section.'" '.
                   9880:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   9881:         }
                   9882:     }
                   9883: 
1.72      ng       9884:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 9885: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       9886: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   9887: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       9888: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       9889: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       9890: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       9891: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9892: 
1.472     albertel 9893:     $result.='
1.533     bisitz   9894: <h2>
                   9895:   '.&mt('Grade Current Resource').'
                   9896: </h2>
                   9897: <div>
                   9898:   '.$table.'
                   9899: </div>
                   9900: 
1.537     harmsja  9901: <div class="LC_columnSection">
                   9902:   
1.533     bisitz   9903:     <fieldset>
                   9904:       <legend>
                   9905:        '.&mt('Sections').'
                   9906:       </legend>
                   9907:       <select name="section" multiple="multiple" size="5">'."\n";
                   9908:     $result.= $selsec;
1.401     albertel 9909:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 9910:     $result.='
1.533     bisitz   9911:     </fieldset>
1.537     harmsja  9912:   
1.533     bisitz   9913:     <fieldset>
                   9914:       <legend>
                   9915:         '.&mt('Groups').'
                   9916:       </legend>
                   9917:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9918:     </fieldset>
1.537     harmsja  9919:   
1.533     bisitz   9920:     <fieldset>
                   9921:       <legend>
                   9922:         '.&mt('Access Status').'
                   9923:       </legend>
                   9924:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   9925:     </fieldset>
1.537     harmsja  9926:   
1.533     bisitz   9927:     <fieldset>
                   9928:       <legend>
                   9929:         '.&mt('Submission Status').'
                   9930:       </legend>
                   9931:       <select name="submitonly" size="5">
1.473     albertel 9932: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   9933: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   9934: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   9935: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   9936:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   9937:       </select>
                   9938:     </fieldset>
1.537     harmsja  9939:   
1.533     bisitz   9940: </div>
                   9941: 
                   9942: <br />
                   9943:           <div>
                   9944:             <div>
1.473     albertel 9945:               <label>
                   9946:                 <input type="radio" name="radioChoice" value="submission" '.
                   9947:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   9948:              &mt('Select individual students to grade and view submissions.').'
                   9949: 	      </label> 
                   9950:             </div>
1.533     bisitz   9951:             <div>
1.473     albertel 9952: 	      <label>
                   9953:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   9954:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   9955:                     &mt('Grade all selected students in a grading table.').'
                   9956:               </label>
                   9957:             </div>
1.533     bisitz   9958:             <div>
1.589     bisitz   9959: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9960:             </div>
1.472     albertel 9961:           </div>
1.533     bisitz   9962: 
                   9963: 
1.473     albertel 9964:         <h2>
                   9965:          '.&mt('Grade Complete Folder for One Student').'
                   9966:         </h2>
1.533     bisitz   9967:         <div>
                   9968:             <div>
1.473     albertel 9969:               <label>
                   9970:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   9971: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   9972:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   9973:               </label>
                   9974:             </div>
1.533     bisitz   9975:             <div>
1.589     bisitz   9976: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9977:             </div>
1.472     albertel 9978:         </div>
                   9979:   </form>';
1.499     albertel 9980:     $result .= &show_grading_menu_form($symb);
1.44      ng       9981:     return $result;
1.2       albertel 9982: }
                   9983: 
1.596.2.12.2.  7(raebur 9984:6): sub substatus_options {
                   9985:6):     return &Apache::lonlocal::texthash(
                   9986:6):                                       'yes'       => 'with submissions',
                   9987:6):                                       'queued'    => 'in grading queue',
                   9988:6):                                       'graded'    => 'with ungraded submissions',
                   9989:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 9990:7):                                       'all'       => 'with any status',
                   9991:7):                                       );
          7(raebur 9992:6): }
                   9993:6): 
1.285     albertel 9994: sub reset_perm {
                   9995:     undef(%perm);
                   9996: }
                   9997: 
                   9998: sub init_perm {
                   9999:     &reset_perm();
1.300     albertel 10000:     foreach my $test_perm ('vgr','mgr','opa') {
                   10001: 
                   10002: 	my $scope = $env{'request.course.id'};
                   10003: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10004: 
                   10005: 	    $scope .= '/'.$env{'request.course.sec'};
                   10006: 	    if ( $perm{$test_perm}=
                   10007: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10008: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10009: 	    } else {
                   10010: 		delete($perm{$test_perm});
                   10011: 	    }
1.285     albertel 10012: 	}
                   10013:     }
                   10014: }
                   10015: 
1.596.2.12.2.  (raeburn 10016:): sub init_old_essays {
                   10017:):     my ($symb,$apath,$adom,$aname) = @_;
                   10018:):     if ($symb ne '') {
                   10019:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10020:):         if (keys(%essays) > 0) {
                   10021:):             $old_essays{$symb} = \%essays;
                   10022:):         }
                   10023:):     }
                   10024:):     return;
                   10025:): }
                   10026:): 
                   10027:): sub reset_old_essays {
                   10028:):     undef(%old_essays);
                   10029:): }
                   10030:): 
1.400     www      10031: sub gather_clicker_ids {
1.408     albertel 10032:     my %clicker_ids;
1.400     www      10033: 
                   10034:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10035: 
                   10036:     # Set up a couple variables.
1.407     albertel 10037:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10038:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10039:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10040: 
1.407     albertel 10041:     foreach my $student (keys(%$classlist)) {
1.438     www      10042:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10043:         my $username = $classlist->{$student}->[$username_idx];
                   10044:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10045:         my $clickers =
1.408     albertel 10046: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10047:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10048:             $id=~s/^[\#0]+//;
1.421     www      10049:             $id=~s/[\-\:]//g;
1.407     albertel 10050:             if (exists($clicker_ids{$id})) {
1.408     albertel 10051: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10052:             } else {
1.408     albertel 10053: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10054:             }
                   10055:         }
                   10056:     }
1.407     albertel 10057:     return %clicker_ids;
1.400     www      10058: }
                   10059: 
1.402     www      10060: sub gather_adv_clicker_ids {
1.408     albertel 10061:     my %clicker_ids;
1.402     www      10062:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10064:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10065:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10066:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10067:             my ($puname,$pudom)=split(/\:/,$person);
                   10068:             my $clickers =
1.408     albertel 10069: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10070:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10071: 		$id=~s/^[\#0]+//;
1.421     www      10072:                 $id=~s/[\-\:]//g;
1.408     albertel 10073: 		if (exists($clicker_ids{$id})) {
                   10074: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10075: 		} else {
                   10076: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10077: 		}
1.405     www      10078:             }
1.402     www      10079:         }
                   10080:     }
1.407     albertel 10081:     return %clicker_ids;
1.402     www      10082: }
                   10083: 
1.413     www      10084: sub clicker_grading_parameters {
                   10085:     return ('gradingmechanism' => 'scalar',
                   10086:             'upfiletype' => 'scalar',
                   10087:             'specificid' => 'scalar',
                   10088:             'pcorrect' => 'scalar',
                   10089:             'pincorrect' => 'scalar');
                   10090: }
                   10091: 
1.400     www      10092: sub process_clicker {
                   10093:     my ($r)=@_;
                   10094:     my ($symb)=&get_symb($r);
                   10095:     if (!$symb) {return '';}
                   10096:     my $result=&checkforfile_js();
                   10097:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   10098:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   10099:     $result.=$table;
                   10100:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   10101:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 10102:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   10103:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  10104:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      10105: # Attempt to restore parameters from last session, set defaults if not present
                   10106:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10107:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10108:                                                  \%Saveable_Parameters);
                   10109:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10110:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10111:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10112:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10113: 
                   10114:     my %checked;
1.521     www      10115:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10116:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10117:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10118:        }
                   10119:     }
                   10120: 
1.400     www      10121:     my $upload=&mt("Upload File");
                   10122:     my $type=&mt("Type");
1.402     www      10123:     my $attendance=&mt("Award points just for participation");
                   10124:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10125:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10126:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10127:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10128:     my $pcorrect=&mt("Percentage points for correct solution");
                   10129:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10130:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10131:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10132:):                                                     'interwrite' => 'interwrite PRS',
                   10133:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10134:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      10135:     $result.=<<ENDUPFORM;
1.402     www      10136: <script type="text/javascript">
                   10137: function sanitycheck() {
                   10138: // Accept only integer percentages
                   10139:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10140:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10141: // Find out grading choice
                   10142:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10143:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10144:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10145:       }
                   10146:    }
                   10147: // By default, new choice equals user selection
                   10148:    newgradingchoice=gradingchoice;
                   10149: // Not good to give more points for false answers than correct ones
                   10150:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10151:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10152:    }
                   10153: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10154:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10155:       document.forms.gradesupload.pcorrect.value=100;
                   10156:       document.forms.gradesupload.pincorrect.value=100;
                   10157:    }
                   10158: // If the values are different, cannot be attendance only
                   10159:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10160:        (gradingchoice=='attendance')) {
                   10161:        newgradingchoice='personnel';
                   10162:    }
                   10163: // Change grading choice to new one
                   10164:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10165:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10166:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10167:       } else {
                   10168:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10169:       }
                   10170:    }
                   10171: // Remember the old state
                   10172:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10173: }
                   10174: </script>
1.400     www      10175: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10176: <input type="hidden" name="symb" value="$symb" />
                   10177: <input type="hidden" name="command" value="processclickerfile" />
                   10178: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10179: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   10180: <input type="file" name="upfile" size="50" />
                   10181: <br /><label>$type: $selectform</label>
1.589     bisitz   10182: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   10183: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10184: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10185: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10186: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10187: <br />&nbsp;&nbsp;&nbsp;
                   10188: <input type="text" name="givenanswer" size="50" />
1.413     www      10189: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   10190: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   10191: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10192: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10193: </form>
                   10194: ENDUPFORM
                   10195:     $result.='</td></tr></table>'."\n".
                   10196:              '</td></tr></table><br /><br />'."\n";
                   10197:     $result.=&show_grading_menu_form($symb);
                   10198:     return $result;
                   10199: }
                   10200: 
                   10201: sub process_clicker_file {
                   10202:     my ($r)=@_;
                   10203:     my ($symb)=&get_symb($r);
                   10204:     if (!$symb) {return '';}
1.413     www      10205: 
                   10206:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10207:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10208:                                               \%Saveable_Parameters);
                   10209: 
1.400     www      10210:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      10211:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10212: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   10213: 	return $result.&show_grading_menu_form($symb);
1.404     www      10214:     }
1.522     www      10215:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10216:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   10217:         return $result.&show_grading_menu_form($symb);
                   10218:     }
1.522     www      10219:     my $foundgiven=0;
1.521     www      10220:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10221:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10222:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10223:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10224:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10225:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10226:         $foundgiven=$#answers+1;
1.521     www      10227:     }
1.407     albertel 10228:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10229:     my %correct_ids;
1.404     www      10230:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10231: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10232:     }
                   10233:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10234: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10235: 	   $correct_id=~tr/a-z/A-Z/;
                   10236: 	   $correct_id=~s/\s//gs;
                   10237: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10238:            $correct_id=~s/[\-\:]//g;
1.414     www      10239:            if ($correct_id) {
                   10240: 	      $correct_ids{$correct_id}='specified';
                   10241:            }
                   10242:         }
1.400     www      10243:     }
1.404     www      10244:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10245: 	$result.=&mt('Score based on attendance only');
1.521     www      10246:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10247:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10248:     } else {
1.408     albertel 10249: 	my $number=0;
1.411     www      10250: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10251: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10252: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10253: 	    if ($correct_ids{$id} eq 'specified') {
                   10254: 		$result.=&mt('specified');
                   10255: 	    } else {
                   10256: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10257: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10258: 	    }
                   10259: 	    $number++;
                   10260: 	}
1.411     www      10261:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10262:3):         if ($number==0) {
                   10263:3):             $result .=
                   10264:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10265:3):                      &mt('No IDs found to determine correct answer'),1);
                   10266:3):             return $result,.&show_grading_menu_form($symb);
                   10267:3):         }
1.404     www      10268:     }
1.405     www      10269:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10270:3):         $result .=
                   10271:3):             &Apache::lonhtmlcommon::confirm_success(
                   10272:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10273:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.405     www      10274:         return $result.&show_grading_menu_form($symb);
                   10275:     }
1.410     www      10276: 
                   10277: # Were able to get all the info needed, now analyze the file
                   10278: 
1.411     www      10279:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10280:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      10281:     my $heading=&mt('Scanning clicker file');
                   10282:     $result.=(<<ENDHEADER);
                   10283: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   10284: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  10285: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      10286: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10287: <input type="hidden" name="symb" value="$symb" />
                   10288: <input type="hidden" name="command" value="assignclickergrades" />
                   10289: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10290: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      10291: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10292: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10293: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10294: ENDHEADER
1.522     www      10295:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10296:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10297:     } 
1.408     albertel 10298:     my %responses;
                   10299:     my @questiontitles;
1.405     www      10300:     my $errormsg='';
                   10301:     my $number=0;
                   10302:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10303: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10304:     }
1.419     www      10305:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10306:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10307:     }
1.596.2.12.2.  (raeburn 10308:):     if ($env{'form.upfiletype'} eq 'turning') {
                   10309:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10310:):     }
1.411     www      10311:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10312:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10313:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10314:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10315:              '<br />';
1.522     www      10316:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10317:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   10318:        return $result.&show_grading_menu_form($symb);
                   10319:     } 
1.414     www      10320: # Remember Question Titles
                   10321: # FIXME: Possibly need delimiter other than ":"
                   10322:     for (my $i=0;$i<$number;$i++) {
                   10323:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10324:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10325:     }
1.411     www      10326:     my $correct_count=0;
                   10327:     my $student_count=0;
                   10328:     my $unknown_count=0;
1.414     www      10329: # Match answers with usernames
                   10330: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10331:     foreach my $id (keys(%responses)) {
1.410     www      10332:        if ($correct_ids{$id}) {
1.414     www      10333:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10334:           $correct_count++;
1.410     www      10335:        } elsif ($clicker_ids{$id}) {
1.437     www      10336:           if ($clicker_ids{$id}=~/\,/) {
                   10337: # More than one user with the same clicker!
                   10338:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   10339:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10340:                            "<select name='multi".$id."'>";
                   10341:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10342:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10343:              }
                   10344:              $result.='</select>';
                   10345:              $unknown_count++;
                   10346:           } else {
                   10347: # Good: found one and only one user with the right clicker
                   10348:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10349:              $student_count++;
                   10350:           }
1.410     www      10351:        } else {
1.411     www      10352:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   10353:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10354:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10355:                    "\n".&mt("Domain").": ".
                   10356:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  10357:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10358:           $unknown_count++;
1.410     www      10359:        }
1.405     www      10360:     }
1.412     www      10361:     $result.='<hr />'.
                   10362:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10363:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10364:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10365:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10366:        } elsif ($correct_count>1) {
1.414     www      10367:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10368:        }
                   10369:     }
1.428     www      10370:     if ($number<1) {
                   10371:        $errormsg.="Found no questions.";
                   10372:     }
1.412     www      10373:     if ($errormsg) {
                   10374:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10375:     } else {
                   10376:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10377:     }
                   10378:     $result.='</form></td></tr></table>'."\n".
1.410     www      10379:              '</td></tr></table><br /><br />'."\n";
1.404     www      10380:     return $result.&show_grading_menu_form($symb);
1.400     www      10381: }
                   10382: 
1.405     www      10383: sub iclicker_eval {
1.406     www      10384:     my ($questiontitles,$responses)=@_;
1.405     www      10385:     my $number=0;
                   10386:     my $errormsg='';
                   10387:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10388:         my %components=&Apache::loncommon::record_sep($line);
                   10389:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10390: 	if ($entries[0] eq 'Question') {
                   10391: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10392: 		$$questiontitles[$number]=$entries[$i];
                   10393: 		$number++;
                   10394: 	    }
                   10395: 	}
                   10396: 	if ($entries[0]=~/^\#/) {
                   10397: 	    my $id=$entries[0];
                   10398: 	    my @idresponses;
                   10399: 	    $id=~s/^[\#0]+//;
                   10400: 	    for (my $i=0;$i<$number;$i++) {
                   10401: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10402:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10403: 		push(@idresponses,$entries[$idx]);
                   10404: 	    }
                   10405: 	    $$responses{$id}=join(',',@idresponses);
                   10406: 	}
1.405     www      10407:     }
                   10408:     return ($errormsg,$number);
                   10409: }
                   10410: 
1.419     www      10411: sub interwrite_eval {
                   10412:     my ($questiontitles,$responses)=@_;
                   10413:     my $number=0;
                   10414:     my $errormsg='';
1.420     www      10415:     my $skipline=1;
                   10416:     my $questionnumber=0;
                   10417:     my %idresponses=();
1.419     www      10418:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10419:         my %components=&Apache::loncommon::record_sep($line);
                   10420:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10421:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10422:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10423:         next if $skipline;
                   10424:         if ($entries[0]!=$questionnumber) {
                   10425:            $questionnumber=$entries[0];
                   10426:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10427:            $number++;
1.419     www      10428:         }
1.420     www      10429:         my $id=$entries[4];
                   10430:         $id=~s/^[\#0]+//;
1.421     www      10431:         $id=~s/^v\d*\://i;
                   10432:         $id=~s/[\-\:]//g;
1.420     www      10433:         $idresponses{$id}[$number]=$entries[6];
                   10434:     }
1.524     raeburn  10435:     foreach my $id (keys(%idresponses)) {
1.420     www      10436:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10437:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10438:     }
                   10439:     return ($errormsg,$number);
                   10440: }
                   10441: 
1.596.2.12.2.  (raeburn 10442:): sub turning_eval {
                   10443:):     my ($questiontitles,$responses)=@_;
                   10444:):     my $number=0;
                   10445:):     my $errormsg='';
                   10446:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10447:):         my %components=&Apache::loncommon::record_sep($line);
                   10448:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10449:):         if ($#entries>$number) { $number=$#entries; }
                   10450:):         my $id=$entries[0];
                   10451:):         my @idresponses;
                   10452:):         $id=~s/^[\#0]+//;
                   10453:):         unless ($id) { next; }
                   10454:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10455:):             $entries[$idx]=~s/\,/\;/g;
                   10456:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10457:):             push(@idresponses,$entries[$idx]);
                   10458:):         }
                   10459:):         $$responses{$id}=join(',',@idresponses);
                   10460:):     }
                   10461:):     for (my $i=1; $i<=$number; $i++) {
                   10462:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10463:):     }
                   10464:):     return ($errormsg,$number);
                   10465:): }
                   10466:): 
1.414     www      10467: sub assign_clicker_grades {
                   10468:     my ($r)=@_;
                   10469:     my ($symb)=&get_symb($r);
                   10470:     if (!$symb) {return '';}
1.416     www      10471: # See which part we are saving to
1.582     raeburn  10472:     my $res_error;
                   10473:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10474:     if ($res_error) {
                   10475:         return &navmap_errormsg();
                   10476:     }
1.416     www      10477: # FIXME: This should probably look for the first handgradeable part
                   10478:     my $part=$$partlist[0];
                   10479: # Start screen output
1.596.2.10  raeburn  10480:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  10481: 
1.596.2.10  raeburn  10482:     $result .= '<br />'.
                   10483:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  10484:                &Apache::loncommon::start_data_table_header_row().
                   10485:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10486:                &Apache::loncommon::end_data_table_header_row().
                   10487:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      10488: 
1.414     www      10489: # Get correct result
                   10490: # FIXME: Possibly need delimiter other than ":"
                   10491:     my @correct=();
1.415     www      10492:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10493:     my $number=$env{'form.number'};
                   10494:     if ($gradingmechanism ne 'attendance') {
1.414     www      10495:        foreach my $key (keys(%env)) {
                   10496:           if ($key=~/^form\.correct\:/) {
                   10497:              my @input=split(/\,/,$env{$key});
                   10498:              for (my $i=0;$i<=$#input;$i++) {
                   10499:                  if (($correct[$i]) && ($input[$i]) &&
                   10500:                      ($correct[$i] ne $input[$i])) {
                   10501:                     $result.='<br /><span class="LC_warning">'.
                   10502:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10503:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10504:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10505:                     $correct[$i]=$input[$i];
                   10506:                  }
                   10507:              }
                   10508:           }
                   10509:        }
1.415     www      10510:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10511:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10512:              $result.='<br /><span class="LC_error">'.
                   10513:                       &mt('No correct result given for question "[_1]"!',
                   10514:                           $env{'form.question:'.$i}).'</span>';
                   10515:           }
                   10516:        }
1.596.2.4  raeburn  10517:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10518:     }
                   10519: # Start grading
1.415     www      10520:     my $pcorrect=$env{'form.pcorrect'};
                   10521:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10522:     my $storecount=0;
1.596.2.4  raeburn  10523:     my %users=();
1.415     www      10524:     foreach my $key (keys(%env)) {
1.420     www      10525:        my $user='';
1.415     www      10526:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10527:           $user=$1;
                   10528:        }
                   10529:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10530:           my $id=$1;
                   10531:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10532:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10533:           } elsif ($env{'form.multi'.$id}) {
                   10534:              $user=$env{'form.multi'.$id};
1.420     www      10535:           }
                   10536:        }
1.596.2.4  raeburn  10537:        if ($user) {
                   10538:           if ($users{$user}) {
                   10539:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10540:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10541:                       '</span><br />';
                   10542:           }
                   10543:           $users{$user}=1;
1.415     www      10544:           my @answer=split(/\,/,$env{$key});
                   10545:           my $sum=0;
1.522     www      10546:           my $realnumber=$number;
1.415     www      10547:           for (my $i=0;$i<$number;$i++) {
1.576     www      10548:              if  ($correct[$i] eq '-') {
                   10549:                 $realnumber--;
                   10550:              } elsif ($answer[$i]) {
1.415     www      10551:                 if ($gradingmechanism eq 'attendance') {
                   10552:                    $sum+=$pcorrect;
1.576     www      10553:                 } elsif ($correct[$i] eq '*') {
1.522     www      10554:                    $sum+=$pcorrect;
1.415     www      10555:                 } else {
1.596.2.4  raeburn  10556: # We actually grade if correct or not
                   10557:                    my $increment=$pincorrect;
                   10558: # Special case: numerical answer "0"
                   10559:                    if ($correct[$i] eq '0') {
                   10560:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10561:                          $increment=$pcorrect;
                   10562:                       }
                   10563: # General numerical answer, both evaluate to something non-zero
                   10564:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10565:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10566:                          $increment=$pcorrect;
                   10567:                       }
                   10568: # Must be just alphanumeric
                   10569:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10570:                       $increment=$pcorrect;
1.415     www      10571:                    }
1.596.2.4  raeburn  10572:                    $sum+=$increment;
1.415     www      10573:                 }
                   10574:              }
                   10575:           }
1.522     www      10576:           my $ave=$sum/(100*$realnumber);
1.416     www      10577: # Store
                   10578:           my ($username,$domain)=split(/\:/,$user);
                   10579:           my %grades=();
                   10580:           $grades{"resource.$part.solved"}='correct_by_override';
                   10581:           $grades{"resource.$part.awarded"}=$ave;
                   10582:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10583:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10584:                                                  $env{'request.course.id'},
                   10585:                                                  $domain,$username);
                   10586:           if ($returncode ne 'ok') {
                   10587:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10588:           } else {
                   10589:              $storecount++;
                   10590:           }
1.415     www      10591:        }
                   10592:     }
                   10593: # We are done
1.549     hauer    10594:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10595:              '</td>'.
                   10596:              &Apache::loncommon::end_data_table_row().
                   10597:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      10598:     return $result.&show_grading_menu_form($symb);
                   10599: }
                   10600: 
1.582     raeburn  10601: sub navmap_errormsg {
                   10602:     return '<div class="LC_error">'.
                   10603:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10604:            &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  10605:            '</div>';
                   10606: }
                   10607: 
1.596.2.12.2.  (raeburn 10608:): sub startpage {
          1.2.3(ra 10609:eb-19):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
                   10610:eb-19):     my %args;
                   10611:eb-19):     if ($onload) {
                   10612:eb-19):          my %loaditems = (
                   10613:eb-19):                         'onload' => $onload,
                   10614:eb-19):                       );
                   10615:eb-19):          $args{'add_entries'} = \%loaditems;
                   10616:eb-19):     }
          (raeburn 10617:):     if ($nomenu) {
          1.2.3(ra 10618:eb-19):         $args{'only_body'} = 1;
                   10619:eb-19):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
          (raeburn 10620:):     } else {
          1.2.3(ra 10621:eb-19):         $args{'bread_crumbs'} = $crumbs;
                   10622:eb-19):         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
          (raeburn 10623:):     }
                   10624:):     unless ($nodisplayflag) {
                   10625:):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
                   10626:):     }
                   10627:): }
                   10628:): 
1.1       albertel 10629: sub handler {
1.41      ng       10630:     my $request=$_[0];
1.434     albertel 10631:     &reset_caches();
1.596.2.4  raeburn  10632:     if ($request->header_only) {
                   10633:         &Apache::loncommon::content_type($request,'text/html');
                   10634:         $request->send_http_header;
                   10635:         return OK;
1.41      ng       10636:     }
                   10637:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10638: 
1.324     albertel 10639:     my $symb=&get_symb($request,1);
1.160     albertel 10640:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10641:     my $command=$commands[0];
1.447     foxr     10642: 
1.160     albertel 10643:     if ($#commands > 0) {
                   10644: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10645:     }
1.447     foxr     10646: 
1.513     foxr     10647:     $ssi_error = 0;
1.535     raeburn  10648:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  10649:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.12.2.  (raeburn 10650:):                                                     {'bread_crumbs' => $brcrum});
1.324     albertel 10651:     if ($symb eq '' && $command eq '') {
1.257     albertel 10652: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  10653:             &Apache::loncommon::content_type($request,'text/html');
                   10654:             $request->send_http_header;
                   10655:             $request->print($start_page);
1.257     albertel 10656: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   10657: 		($env{'form.codethree'})) {
                   10658: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   10659: 		    $env{'form.codethree'};
1.41      ng       10660: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   10661: 		    &Apache::lonnet::checkin($token);
                   10662: 		if ($tsymb) {
1.137     albertel 10663: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       10664: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     10665: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 10666: 					  ('grade_username' => $tuname,
                   10667: 					   'grade_domain' => $tudom,
                   10668: 					   'grade_courseid' => $tcrsid,
                   10669: 					   'grade_symb' => $tsymb)));
1.41      ng       10670: 		    } else {
1.45      ng       10671: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 10672: 		    }
1.41      ng       10673: 		} else {
1.45      ng       10674: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       10675: 		}
1.14      www      10676: 	    } else {
1.41      ng       10677: 		$request->print(&Apache::lonxml::tokeninputfield());
                   10678: 	    }
1.596.2.4  raeburn  10679:         } elsif ($env{'request.course.id'}) {
                   10680:             &init_perm(); 
                   10681:             if (!%perm) {
                   10682:                 $request->internal_redirect('/adm/quickgrades');
1.596.2.12.2.  3(raebur 10683:3):                 return OK;
1.596.2.4  raeburn  10684:             } else {
                   10685:                 &Apache::loncommon::content_type($request,'text/html');
                   10686:                 $request->send_http_header;
                   10687:                 $request->print($start_page);
                   10688:             }
                   10689:         }
1.41      ng       10690:     } else {
1.596.2.4  raeburn  10691:         &init_perm();
                   10692:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  10693:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10694:                     ($command =~ /^scantronupload/)) {
                   10695:                 # Not in a course.
                   10696:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10697:                 return HTTP_NOT_ACCEPTABLE;
                   10698:             }
1.596.2.4  raeburn  10699:         } elsif (!%perm) {
                   10700:             $request->internal_redirect('/adm/quickgrades');
                   10701:         }
                   10702:         &Apache::loncommon::content_type($request,'text/html');
                   10703:         $request->send_http_header;
1.596.2.12.2.  1.2.3(ra 10704:eb-19):         if (($command eq 'scantron_selectphase' && $perm{'mgr'}) || 
                   10705:eb-19):             (($command eq 'scantronupload') &&
                   10706:eb-19):              (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   10707:eb-19):               &Apache::lonnet::allowed('usc',$env{'request.course.id'})))) {
                   10708:eb-19):             &startpage($request,$symb,[{href=>'/adm/grades', text=>"Grading"}],1,1,
                   10709:eb-19):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   10710:eb-19):         } else {
                   10711:eb-19):             unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
                   10712:eb-19):                 $request->print($start_page); 
                   10713:eb-19):             }
          (raeburn 10714:):         }
1.104     albertel 10715: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.596.2.12.2.  (raeburn 10716:):             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10717:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10718:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10719:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10720:):                                               $env{'form.userdom'});
                   10721:):             }
                   10722:):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10723:):             if ($versionform) {
                   10724:):                 $request->print($versionform);
                   10725:):             }
                   10726:):             $request->print('<br clear="all" />');
1.257     albertel 10727: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.596.2.12.2.  (raeburn 10728:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10729:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10730:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10731:):                                           $env{'form.userdom'},
                   10732:):                                           $env{'form.inhibitmenu'});
                   10733:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10734:):             if ($versionform) {
                   10735:):                 $request->print($versionform);
                   10736:):             }
                   10737:):             $request->print('<br clear="all" />');
                   10738:):             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10739: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       10740: 	    &pickStudentPage($request);
1.103     albertel 10741: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       10742: 	    &displayPage($request);
1.104     albertel 10743: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       10744: 	    &updateGradeByPage($request);
1.104     albertel 10745: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       10746: 	    &processGroup($request);
1.104     albertel 10747: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 10748: 	    $request->print(&grading_menu($request));
                   10749: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   10750: 	    $request->print(&submit_options($request));
1.104     albertel 10751: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       10752: 	    $request->print(&viewgrades($request));
1.104     albertel 10753: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       10754: 	    $request->print(&processHandGrade($request));
1.106     albertel 10755: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       10756: 	    $request->print(&editgrades($request));
1.106     albertel 10757: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       10758: 	    $request->print(&verifyreceipt($request));
1.400     www      10759:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   10760:             $request->print(&process_clicker($request));
                   10761:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   10762:             $request->print(&process_clicker_file($request));
1.414     www      10763:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   10764:             $request->print(&assign_clicker_grades($request));
1.106     albertel 10765: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       10766: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 10767: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       10768: 	    $request->print(&csvupload($request));
1.106     albertel 10769: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       10770: 	    $request->print(&csvuploadmap($request));
1.246     albertel 10771: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10772: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 10773: 		$request->print(&csvuploadoptions($request));
1.41      ng       10774: 	    } else {
1.257     albertel 10775: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10776: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10777: 		} else {
1.257     albertel 10778: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10779: 		}
                   10780: 		$request->print(&csvuploadmap($request));
                   10781: 	    }
1.246     albertel 10782: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10783: 	    $request->print(&csvuploadassign($request));
1.106     albertel 10784: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 10785: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 10786:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10787:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 10788: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   10789: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 10790: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 10791: 	    $request->print(&scantron_process_students($request));
1.157     albertel 10792:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10793:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10794: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 10795:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 10796:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10797:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10798: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 10799:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 10800:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10801: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 10802:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  10803:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   10804:             $request->print(&checkscantron_results($request));     
1.106     albertel 10805: 	} elsif ($command) {
1.562     bisitz   10806: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10807: 	}
1.2       albertel 10808:     }
1.513     foxr     10809:     if ($ssi_error) {
                   10810: 	&ssi_print_error($request);
                   10811:     }
1.353     albertel 10812:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 10813:     &reset_caches();
1.596.2.4  raeburn  10814:     return OK;
1.44      ng       10815: }
                   10816: 
1.1       albertel 10817: 1;
                   10818: 
1.13      albertel 10819: __END__;
1.531     jms      10820: 
                   10821: 
                   10822: =head1 NAME
                   10823: 
                   10824: Apache::grades
                   10825: 
                   10826: =head1 SYNOPSIS
                   10827: 
                   10828: Handles the viewing of grades.
                   10829: 
                   10830: This is part of the LearningOnline Network with CAPA project
                   10831: described at http://www.lon-capa.org.
                   10832: 
                   10833: =head1 OVERVIEW
                   10834: 
                   10835: Do an ssi with retries:
                   10836: While I'd love to factor out this with the vesrion in lonprintout,
                   10837: 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
                   10838: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10839: 
                   10840: At least the logic that drives this has been pulled out into loncommon.
                   10841: 
                   10842: 
                   10843: 
                   10844: ssi_with_retries - Does the server side include of a resource.
                   10845:                      if the ssi call returns an error we'll retry it up to
                   10846:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 10847:4):                      If we still have a problem, no text is appended to the
1.531     jms      10848:                      output and we set some global variables.
                   10849:                      to indicate to the caller an SSI error occurred.  
                   10850:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 10851:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      10852:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10853:                      by informing the user that this happened.
                   10854: 
                   10855: Parameters:
                   10856:   resource   - The resource to include.  This is passed directly, without
                   10857:                interpretation to lonnet::ssi.
                   10858:   form       - The form hash parameters that guide the interpretation of the resource
                   10859:                
                   10860:   retries    - Number of retries allowed before giving up completely.
                   10861: Returns:
                   10862:   On success, returns the rendered resource identified by the resource parameter.
                   10863: Side Effects:
                   10864:   The following global variables can be set:
                   10865:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10866:                               It is up to the caller to initialize this to false
                   10867:                               if desired.
                   10868:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10869:                               of the resource that could not be rendered by the ssi
                   10870:                               call.
                   10871:    ssi_error_message   - The error string fetched from the ssi response
                   10872:                               in the event of an error.
                   10873: 
                   10874: 
                   10875: =head1 HANDLER SUBROUTINE
                   10876: 
                   10877: ssi_with_retries()
                   10878: 
                   10879: =head1 SUBROUTINES
                   10880: 
                   10881: =over
                   10882: 
                   10883: =item scantron_get_correction() : 
                   10884: 
                   10885:    Builds the interface screen to interact with the operator to fix a
                   10886:    specific error condition in a specific scanline
                   10887: 
                   10888:  Arguments:
                   10889:     $r           - Apache request object
                   10890:     $i           - number of the current scanline
                   10891:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  1.2.3(ra 10892:eb-19):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      10893:     $line        - full contents of the current scanline
                   10894:     $error       - error condition, valid values are
                   10895:                    'incorrectCODE', 'duplicateCODE',
                   10896:                    'doublebubble', 'missingbubble',
                   10897:                    'duplicateID', 'incorrectID'
                   10898:     $arg         - extra information needed
                   10899:        For errors:
                   10900:          - duplicateID   - paper number that this studentID was seen before on
                   10901:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10902:                            seen on before
                   10903:          - incorrectCODE - current incorrect CODE 
                   10904:          - doublebubble  - array ref of the bubble lines that have double
                   10905:                            bubble errors
                   10906:          - missingbubble - array ref of the bubble lines that have missing
                   10907:                            bubble errors
                   10908: 
1.596.2.12.2.  6(raebur 10909:3):    $randomorder - True if exam folder has randomorder set
                   10910:3):    $randompick  - True if exam folder has randompick set
                   10911:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10912:3):                      for current line to question number used for same question
                   10913:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   10914:3):    $startline   - Reference to hash where key is question number (0 is first)
                   10915:3):                   and value is number of first bubble line for current student
                   10916:3):                   or code-based randompick and/or randomorder.
                   10917:3): 
                   10918:3): 
1.531     jms      10919: =item  scantron_get_maxbubble() : 
                   10920: 
1.582     raeburn  10921:    Arguments:
                   10922:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10923:                       failure to retrieve a navmap object.
                   10924:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10925:        calling routine should trap the error condition and display the warning
                   10926:        found in &navmap_errormsg().
                   10927: 
1.596.2.12.2.  (raeburn 10928:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   10929:): 
1.531     jms      10930:    Returns the maximum number of bubble lines that are expected to
                   10931:    occur. Does this by walking the selected sequence rendering the
                   10932:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10933:    for what the current value of the problem counter is.
                   10934: 
                   10935:    Caches the results to $env{'form.scantron_maxbubble'},
                   10936:    $env{'form.scantron.bubble_lines.n'}, 
                   10937:    $env{'form.scantron.first_bubble_line.n'} and
                   10938:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 10939:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      10940:    lines for response n and number of the first bubble line for response n,
                   10941:    and a comma separated list of numbers of bubble lines for sub-questions
                   10942:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10943: 
                   10944: 
                   10945: =item  scantron_validate_missingbubbles() : 
                   10946: 
                   10947:    Validates all scanlines in the selected file to not have any
                   10948:     answers that don't have bubbles that have not been verified
                   10949:     to be bubble free.
                   10950: 
                   10951: =item  scantron_process_students() : 
                   10952: 
1.596.2.6  raeburn  10953:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10954: 
                   10955:    The parsed scanline hash is added to %env 
                   10956: 
                   10957:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10958:    foreach resource , with the form data of
                   10959: 
                   10960: 	'submitted'     =>'scantron' 
                   10961: 	'grade_target'  =>'grade',
                   10962: 	'grade_username'=> username of student
                   10963: 	'grade_domain'  => domain of student
                   10964: 	'grade_courseid'=> of course
                   10965: 	'grade_symb'    => symb of resource to grade
                   10966: 
                   10967:     This triggers a grading pass. The problem grading code takes care
                   10968:     of converting the bubbled letter information (now in %env) into a
                   10969:     valid submission.
                   10970: 
                   10971: =item  scantron_upload_scantron_data() :
                   10972: 
1.596.2.6  raeburn  10973:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10974: 
                   10975: =item  scantron_upload_scantron_data_save() : 
                   10976: 
                   10977:    Adds a provided bubble information data file to the course if user
                   10978:    has the correct privileges to do so. 
                   10979: 
                   10980: =item  valid_file() :
                   10981: 
                   10982:    Validates that the requested bubble data file exists in the course.
                   10983: 
                   10984: =item  scantron_download_scantron_data() : 
                   10985: 
                   10986:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  10987:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10988:    course.
                   10989: 
                   10990: =item  scantron_validate_ID() : 
                   10991: 
                   10992:    Validates all scanlines in the selected file to not have any
1.556     weissno  10993:    invalid or underspecified student/employee IDs
1.531     jms      10994: 
1.582     raeburn  10995: =item navmap_errormsg() :
                   10996: 
                   10997:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   10998:    Should be called whenever the request to instantiate a navmap object fails.  
                   10999: 
1.531     jms      11000: =back
                   11001: 
                   11002: =cut

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