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

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.6(ra    4:eb-19): # $Id: grades.pm,v 1.596.2.12.2.41.2.5 2019/02/06 05:55:25 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.596.2.12.2.  1.2.6(ra   47:eb-19): use HTML::Parser();
                     48:eb-19): use File::MMagic;
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.596.2.12.2.  (raeburn   57:): my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.44      ng        103: sub getpartlist {
1.582     raeburn   104:     my ($symb,$errorref) = @_;
1.439     albertel  105: 
                    106:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   107:     unless (ref($navmap)) {
                    108:         if (ref($errorref)) { 
                    109:             $$errorref = 'navmap';
                    110:             return;
                    111:         }
                    112:     }
1.439     albertel  113:     my $res      = $navmap->getBySymb($symb);
                    114:     my $partlist = $res->parts();
                    115:     my $url      = $res->src();
                    116:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    117: 
1.146     albertel  118:     my @stores;
1.439     albertel  119:     foreach my $part (@{ $partlist }) {
1.146     albertel  120: 	foreach my $key (@metakeys) {
                    121: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    122: 	}
                    123:     }
                    124:     return @stores;
1.2       albertel  125: }
                    126: 
1.44      ng        127: # --- Get the symbolic name of a problem and the url
1.324     albertel  128: sub get_symb {
1.173     albertel  129:     my ($request,$silent) = @_;
1.596.2.12.2.  (raeburn  130:):     my $symb=$env{'form.symb'};
                    131:):     unless ($symb) {
                    132:):         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    133:):         $symb = &Apache::lonnet::symbread($url);
                    134:):         if ($symb eq '') { 
                    135:): 	    if (!$silent) {
                    136:):                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
                    137:): 	        return ();
                    138:): 	    }
                    139:):         }
1.173     albertel  140:     }
1.418     albertel  141:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  142:     return ($symb);
1.32      ng        143: }
                    144: 
1.129     ng        145: #--- Format fullname, username:domain if different for display
                    146: #--- Use anywhere where the student names are listed
                    147: sub nameUserString {
                    148:     my ($type,$fullname,$uname,$udom) = @_;
                    149:     if ($type eq 'header') {
1.485     albertel  150: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        151:     } else {
1.398     albertel  152: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    153: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        154:     }
                    155: }
                    156: 
1.44      ng        157: #--- Get the partlist and the response type for a given problem. ---
                    158: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        159: sub response_type {
1.582     raeburn   160:     my ($symb,$response_error) = @_;
1.377     albertel  161: 
                    162:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   163:     unless (ref($navmap)) {
                    164:         if (ref($response_error)) {
                    165:             $$response_error = 1;
                    166:         }
                    167:         return;
                    168:     }
1.377     albertel  169:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   170:     unless (ref($res)) {
                    171:         $$response_error = 1;
                    172:         return;
                    173:     }
1.377     albertel  174:     my $partlist = $res->parts();
1.392     albertel  175:     my %vPart = 
                    176: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  177:     my (%response_types,%handgrade);
                    178:     foreach my $part (@{ $partlist }) {
1.392     albertel  179: 	next if (%vPart && !exists($vPart{$part}));
                    180: 
1.377     albertel  181: 	my @types = $res->responseType($part);
                    182: 	my @ids = $res->responseIds($part);
                    183: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    184: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    185: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    186: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    187: 				     '.handgrade',$symb);
1.41      ng        188: 	}
                    189:     }
1.377     albertel  190:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        191: }
                    192: 
1.375     albertel  193: sub flatten_responseType {
                    194:     my ($responseType) = @_;
                    195:     my @part_response_id =
                    196: 	map { 
                    197: 	    my $part = $_;
                    198: 	    map {
                    199: 		[$part,$_]
                    200: 		} sort(keys(%{ $responseType->{$part} }));
                    201: 	} sort(keys(%$responseType));
                    202:     return @part_response_id;
                    203: }
                    204: 
1.207     albertel  205: sub get_display_part {
1.324     albertel  206:     my ($partID,$symb)=@_;
1.207     albertel  207:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    208:     if (defined($display) and $display ne '') {
1.577     bisitz    209:         $display.= ' (<span class="LC_internal_info">'
                    210:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  211:     } else {
                    212: 	$display=$partID;
                    213:     }
                    214:     return $display;
                    215: }
1.269     raeburn   216: 
1.118     ng        217: #--- Show resource title
                    218: #--- and parts and response type
                    219: sub showResourceInfo {
1.582     raeburn   220:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  221:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   222:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    223:     if (ref($res_error)) {
                    224:         if ($$res_error) {
                    225:             return;
                    226:         }
                    227:     }
1.584     bisitz    228:     $result.=&Apache::loncommon::start_data_table()
                    229:             .&Apache::loncommon::start_data_table_header_row();
                    230:     if ($checkboxes) {
                    231:         $result.='<th>&nbsp;</th>';
                    232:     }
                    233:     $result.='<th>'.&mt('Problem Part').'</th>'
                    234:             .'<th>'.&mt('Res. ID').'</th>'
                    235:             .'<th>'.&mt('Type').'</th>'
                    236:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        237:     my %resptype = ();
1.122     ng        238:     my $hdgrade='no';
1.154     albertel  239:     my %partsseen;
1.524     raeburn   240:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    241:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    242:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    243:             my $responsetype = $responseType->{$partID}->{$resID};
                    244:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    245:             $result.=&Apache::loncommon::start_data_table_row();
                    246:             if ($checkboxes) {
                    247:                 if (exists($partsseen{$partID})) {
                    248:                     $result.="<td>&nbsp;</td>";
                    249:                 } else {
                    250:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    251:                 }
                    252:                 $partsseen{$partID}=1;
                    253:             }
                    254:             my $display_part=&get_display_part($partID,$symb);
                    255:             $result.='<td>'.$display_part.'</td>'
                    256:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    257:                     .'<td>'.&mt($responsetype).'</td>'
1.596.2.12.2.  2(raebur  258:2): #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
1.584     bisitz    259:                     .&Apache::loncommon::end_data_table_row();
                    260:         }
1.118     ng        261:     }
1.584     bisitz    262:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  263:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        264: }
                    265: 
1.434     albertel  266: sub reset_caches {
                    267:     &reset_analyze_cache();
                    268:     &reset_perm();
1.596.2.12.2.  (raeburn  269:):     &reset_old_essays();
1.434     albertel  270: }
                    271: 
                    272: {
                    273:     my %analyze_cache;
1.557     raeburn   274:     my %analyze_cache_formkeys;
1.148     albertel  275: 
1.434     albertel  276:     sub reset_analyze_cache {
                    277: 	undef(%analyze_cache);
1.557     raeburn   278:         undef(%analyze_cache_formkeys);
1.434     albertel  279:     }
                    280: 
                    281:     sub get_analyze {
1.596.2.12.2.  (raeburn  282:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  283: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   284:         if ($type eq 'randomizetry') {
                    285:             if ($trial ne '') {
                    286:                 $key .= "\0".$trial;
                    287:             }
                    288:         }
1.557     raeburn   289: 	if (exists($analyze_cache{$key})) {
                    290:             my $getupdate = 0;
                    291:             if (ref($add_to_hash) eq 'HASH') {
                    292:                 foreach my $item (keys(%{$add_to_hash})) {
                    293:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    294:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    295:                             $getupdate = 1;
                    296:                             last;
                    297:                         }
                    298:                     } else {
                    299:                         $getupdate = 1;
                    300:                     }
                    301:                 }
                    302:             }
                    303:             if (!$getupdate) {
                    304:                 return $analyze_cache{$key};
                    305:             }
                    306:         }
1.434     albertel  307: 
                    308: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    309: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   310:         my %form = ('grade_target'      => 'analyze',
                    311:                     'grade_domain'      => $udom,
                    312:                     'grade_symb'        => $symb,
                    313:                     'grade_courseid'    =>  $env{'request.course.id'},
                    314:                     'grade_username'    => $uname,
                    315:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  316:):         if ($bubbles_per_row ne '') {
                    317:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    318:):         }
1.596.2.2  raeburn   319:         if ($type eq 'randomizetry') {
                    320:             $form{'grade_questiontype'} = $type;
                    321:             if ($rndseed ne '') {
                    322:                 $form{'grade_rndseed'} = $rndseed;
                    323:             }
                    324:         }
1.557     raeburn   325:         if (ref($add_to_hash)) {
                    326:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   327:         }
1.557     raeburn   328: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  329: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    330: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   331:         if (ref($add_to_hash) eq 'HASH') {
                    332:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    333:         } else {
                    334:             $analyze_cache_formkeys{$key} = {};
                    335:         }
1.434     albertel  336: 	return $analyze_cache{$key} = \%analyze;
                    337:     }
                    338: 
                    339:     sub get_order {
1.596.2.2  raeburn   340: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    341: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  342: 	return $analyze->{"$partid.$respid.shown"};
                    343:     }
                    344: 
                    345:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   346: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    347: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    348:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   349:         if (ref($foils) eq 'ARRAY') {
                    350: 	    foreach my $foil (@{$foils}) {
                    351: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    352: 		    return $foil;
                    353: 	        }
1.434     albertel  354: 	    }
                    355: 	}
                    356:     }
1.554     raeburn   357: 
                    358:     sub scantron_partids_tograde {
1.596.2.12.2.  1(raebur  359:7):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   360:         my (%analysis,@parts);
                    361:         if (ref($resource)) {
                    362:             my $symb = $resource->symb();
1.557     raeburn   363:             my $add_to_form;
                    364:             if ($check_for_randomlist) {
                    365:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    366:             }
1.596.2.12.2.  1(raebur  367:7):             if ($scancode) {
                    368:7):                 if (ref($add_to_form) eq 'HASH') {
                    369:7):                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    370:7):                 } else {
                    371:7):                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    372:7):                 }
                    373:7):             }
          (raeburn  374:):             my $analyze =
                    375:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    376:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   377:             if (ref($analyze) eq 'HASH') {
                    378:                 %analysis = %{$analyze};
                    379:             }
                    380:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    381:                 foreach my $part (@{$analysis{'parts'}}) {
                    382:                     my ($id,$respid) = split(/\./,$part);
                    383:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    384:                         push(@parts,$part);
                    385:                     }
                    386:                 }
                    387:             }
                    388:         }
                    389:         return (\%analysis,\@parts);
                    390:     }
                    391: 
1.148     albertel  392: }
1.434     albertel  393: 
1.118     ng        394: #--- Clean response type for display
1.335     albertel  395: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    396: #        response types only.
1.118     ng        397: sub cleanRecord {
1.336     albertel  398:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   399: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  400:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  401:     if ($response =~ /^(option|rank)$/) {
                    402: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  403:4):         my @answer = %answer;
                    404:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  405: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    406: 	my ($toprow,$bottomrow);
                    407: 	foreach my $foil (@$order) {
                    408: 	    if ($grading{$foil} == 1) {
                    409: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    410: 	    } else {
                    411: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    412: 	    }
1.398     albertel  413: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  414: 	}
                    415: 	return '<blockquote><table border="1">'.
1.466     albertel  416: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    417: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   418: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  419:     } elsif ($response eq 'match') {
                    420: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  421:4):         my @answer = %answer;
                    422:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  423: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    424: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    425: 	my ($toprow,$middlerow,$bottomrow);
                    426: 	foreach my $foil (@$order) {
                    427: 	    my $item=shift(@items);
                    428: 	    if ($grading{$foil} == 1) {
                    429: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  430: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  431: 	    } else {
                    432: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  433: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  434: 	    }
1.398     albertel  435: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        436: 	}
1.126     ng        437: 	return '<blockquote><table border="1">'.
1.466     albertel  438: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    439: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  440: 	    $middlerow.'</tr>'.
1.466     albertel  441: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   442: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  443:     } elsif ($response eq 'radiobutton') {
                    444: 	my %answer=&Apache::lonnet::str2hash($answer);
                    445: 	my ($toprow,$bottomrow);
1.434     albertel  446: 	my $correct = 
1.596.2.2  raeburn   447: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  448: 	foreach my $foil (@$order) {
1.148     albertel  449: 	    if (exists($answer{$foil})) {
1.434     albertel  450: 		if ($foil eq $correct) {
1.466     albertel  451: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  452: 		} else {
1.466     albertel  453: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  454: 		}
                    455: 	    } else {
1.466     albertel  456: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  457: 	    }
1.398     albertel  458: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  459: 	}
                    460: 	return '<blockquote><table border="1">'.
1.466     albertel  461: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    462: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   463: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  464:     } elsif ($response eq 'essay') {
1.257     albertel  465: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        466: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  467: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    468: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        469: 
1.257     albertel  470: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    471: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    472: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    473: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    474: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    475: 	    $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        476: 	}
1.596.2.12.2.  2(raebur  477:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  478:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  479:4):         my $result=&mt('Smile representation: [_1]',
                    480:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  481: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    482: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    483: 	return $result;
1.335     albertel  484:     } elsif ( $response eq 'Task') {
                    485: 	if ( $answer eq 'SUBMITTED') {
                    486: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  487: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  488: 	    return $result;
                    489: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    490: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    491: 			       keys(%{$record}));
                    492: 	    return join('<br />',($version,@matches));
                    493: 			       
                    494: 			       
                    495: 	} else {
                    496: 	    my $result =
                    497: 		'<p>'
                    498: 		.&mt('Overall result: [_1]',
                    499: 		     $record->{$version."resource.$respid.$partid.status"})
                    500: 		.'</p>';
                    501: 	    
                    502: 	    $result .= '<ul>';
                    503: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    504: 			     keys(%{$record}));
                    505: 	    foreach my $grade (sort(@grade)) {
                    506: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    507: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    508: 				     $dim, $record->{$grade}).
                    509: 			  '</li>';
                    510: 	    }
                    511: 	    $result.='</ul>';
                    512: 	    return $result;
                    513: 	}
1.596.2.12.2.  8(raebur  514:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    515:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  516: 	$answer = 
                    517: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    518: 							      $answer);
1.596.2.12.2.  8(raebur  519:4):         return $answer;
1.122     ng        520:     }
1.596.2.12.2.  8(raebur  521:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        522: }
                    523: 
                    524: #-- A couple of common js functions
                    525: sub commonJSfunctions {
                    526:     my $request = shift;
                    527:     $request->print(<<COMMONJSFUNCTIONS);
                    528: <script type="text/javascript" language="javascript">
                    529:     function radioSelection(radioButton) {
                    530: 	var selection=null;
                    531: 	if (radioButton.length > 1) {
                    532: 	    for (var i=0; i<radioButton.length; i++) {
                    533: 		if (radioButton[i].checked) {
                    534: 		    return radioButton[i].value;
                    535: 		}
                    536: 	    }
                    537: 	} else {
                    538: 	    if (radioButton.checked) return radioButton.value;
                    539: 	}
                    540: 	return selection;
                    541:     }
                    542: 
                    543:     function pullDownSelection(selectOne) {
                    544: 	var selection="";
                    545: 	if (selectOne.length > 1) {
                    546: 	    for (var i=0; i<selectOne.length; i++) {
                    547: 		if (selectOne[i].selected) {
                    548: 		    return selectOne[i].value;
                    549: 		}
                    550: 	    }
                    551: 	} else {
1.138     albertel  552:             // only one value it must be the selected one
                    553: 	    return selectOne.value;
1.118     ng        554: 	}
                    555:     }
                    556: </script>
                    557: COMMONJSFUNCTIONS
                    558: }
                    559: 
1.44      ng        560: #--- Dumps the class list with usernames,list of sections,
                    561: #--- section, ids and fullnames for each user.
                    562: sub getclasslist {
1.449     banghart  563:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  564:     my @getsec;
1.450     banghart  565:     my @getgroup;
1.442     banghart  566:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  567:     if (!ref($getsec)) {
                    568: 	if ($getsec ne '' && $getsec ne 'all') {
                    569: 	    @getsec=($getsec);
                    570: 	}
                    571:     } else {
                    572: 	@getsec=@{$getsec};
                    573:     }
                    574:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  575:     if (!ref($getgroup)) {
                    576: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    577: 	    @getgroup=($getgroup);
                    578: 	}
                    579:     } else {
                    580: 	@getgroup=@{$getgroup};
                    581:     }
                    582:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  583: 
1.449     banghart  584:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  585:     # Bail out if we were unable to get the classlist
1.56      matthew   586:     return if (! defined($classlist));
1.449     banghart  587:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   588:     #
                    589:     my %sections;
                    590:     my %fullnames;
1.205     matthew   591:     foreach my $student (keys(%$classlist)) {
                    592:         my $end      = 
                    593:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    594:         my $start    = 
                    595:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    596:         my $id       = 
                    597:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    598:         my $section  = 
                    599:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    600:         my $fullname = 
                    601:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    602:         my $status   = 
                    603:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  604:         my $group   = 
                    605:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        606: 	# filter students according to status selected
1.442     banghart  607: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    608: 	    if (!($stu_status =~ $status)) {
1.450     banghart  609: 		delete($classlist->{$student});
1.76      ng        610: 		next;
                    611: 	    }
                    612: 	}
1.450     banghart  613: 	# filter students according to groups selected
1.453     banghart  614: 	my @stu_groups = split(/,/,$group);
1.450     banghart  615: 	if (@getgroup) {
                    616: 	    my $exclude = 1;
1.454     banghart  617: 	    foreach my $grp (@getgroup) {
                    618: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  619: 	            if ($stu_group eq $grp) {
                    620: 	                $exclude = 0;
                    621:     	            } 
1.450     banghart  622: 	        }
1.453     banghart  623:     	        if (($grp eq 'none') && !$group) {
                    624:         	        $exclude = 0;
                    625:         	}
1.450     banghart  626: 	    }
                    627: 	    if ($exclude) {
                    628: 	        delete($classlist->{$student});
                    629: 	    }
                    630: 	}
1.205     matthew   631: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  632: 	if (&canview($section)) {
1.291     albertel  633: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  634: 		$sections{$section}++;
1.450     banghart  635: 		if ($classlist->{$student}) {
                    636: 		    $fullnames{$student}=$fullname;
                    637: 		}
1.103     albertel  638: 	    } else {
1.205     matthew   639: 		delete($classlist->{$student});
1.103     albertel  640: 	    }
                    641: 	} else {
1.205     matthew   642: 	    delete($classlist->{$student});
1.103     albertel  643: 	}
1.44      ng        644:     }
                    645:     my %seen = ();
1.56      matthew   646:     my @sections = sort(keys(%sections));
                    647:     return ($classlist,\@sections,\%fullnames);
1.44      ng        648: }
                    649: 
1.103     albertel  650: sub canmodify {
                    651:     my ($sec)=@_;
                    652:     if ($perm{'mgr'}) {
                    653: 	if (!defined($perm{'mgr_section'})) {
                    654: 	    # can modify whole class
                    655: 	    return 1;
                    656: 	} else {
                    657: 	    if ($sec eq $perm{'mgr_section'}) {
                    658: 		#can modify the requested section
                    659: 		return 1;
                    660: 	    } else {
                    661: 		# can't modify the request section
                    662: 		return 0;
                    663: 	    }
                    664: 	}
                    665:     }
                    666:     #can't modify
                    667:     return 0;
                    668: }
                    669: 
                    670: sub canview {
                    671:     my ($sec)=@_;
                    672:     if ($perm{'vgr'}) {
                    673: 	if (!defined($perm{'vgr_section'})) {
                    674: 	    # can modify whole class
                    675: 	    return 1;
                    676: 	} else {
                    677: 	    if ($sec eq $perm{'vgr_section'}) {
                    678: 		#can modify the requested section
                    679: 		return 1;
                    680: 	    } else {
                    681: 		# can't modify the request section
                    682: 		return 0;
                    683: 	    }
                    684: 	}
                    685:     }
                    686:     #can't modify
                    687:     return 0;
                    688: }
                    689: 
1.44      ng        690: #--- Retrieve the grade status of a student for all the parts
                    691: sub student_gradeStatus {
1.324     albertel  692:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  693:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        694:     my %partstatus = ();
                    695:     foreach (@$partlist) {
1.128     ng        696: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        697: 	$status              = 'nothing' if ($status eq '');
                    698: 	$partstatus{$_}      = $status;
                    699: 	my $subkey           = "resource.$_.submitted_by";
                    700: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    701:     }
                    702:     return %partstatus;
                    703: }
                    704: 
1.45      ng        705: # hidden form and javascript that calls the form
                    706: # Use by verifyscript and viewgrades
                    707: # Shows a student's view of problem and submission
                    708: sub jscriptNform {
1.324     albertel  709:     my ($symb) = @_;
1.442     banghart  710:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        711:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    712: 	'    function viewOneStudent(user,domain) {'."\n".
                    713: 	'	document.onestudent.student.value = user;'."\n".
                    714: 	'	document.onestudent.userdom.value = domain;'."\n".
                    715: 	'	document.onestudent.submit();'."\n".
                    716: 	'    }'."\n".
                    717: 	'</script>'."\n";
                    718:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  719: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  720: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    721: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  722: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        723: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    724: 	'<input type="hidden" name="student" value="" />'."\n".
                    725: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    726: 	'</form>'."\n";
                    727:     return $jscript;
                    728: }
1.39      ng        729: 
1.447     foxr      730: 
                    731: 
1.315     bowersj2  732: # Given the score (as a number [0-1] and the weight) what is the final
                    733: # point value? This function will round to the nearest tenth, third,
                    734: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  735: sub compute_points {
1.315     bowersj2  736:     my ($score, $weight) = @_;
                    737:     
                    738:     my $tolerance = .00001;
                    739:     my $points = $score * $weight;
                    740: 
                    741:     # Check for nearness to 1/x.
                    742:     my $check_for_nearness = sub {
                    743:         my ($factor) = @_;
                    744:         my $num = ($points * $factor) + $tolerance;
                    745:         my $floored_num = floor($num);
1.316     albertel  746:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  747:             return $floored_num / $factor;
                    748:         }
                    749:         return $points;
                    750:     };
                    751: 
                    752:     $points = $check_for_nearness->(10);
                    753:     $points = $check_for_nearness->(3);
                    754:     $points = $check_for_nearness->(4);
                    755:     
                    756:     return $points;
                    757: }
                    758: 
1.44      ng        759: #------------------ End of general use routines --------------------
1.87      www       760: 
                    761: #
                    762: # Find most similar essay
                    763: #
                    764: 
                    765: sub most_similar {
1.596.2.12.2.  (raeburn  766:):     my ($uname,$udom,$symb,$uessay)=@_;
                    767:): 
                    768:):     unless ($symb) { return ''; }
                    769:): 
                    770:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       771: 
                    772: # ignore spaces and punctuation
                    773: 
                    774:     $uessay=~s/\W+/ /gs;
                    775: 
1.282     www       776: # ignore empty submissions (occuring when only files are sent)
                    777: 
1.596.2.4  raeburn   778:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       779: 
1.87      www       780: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       781:     my $limit=0.6;
1.87      www       782:     my $sname='';
                    783:     my $sdom='';
                    784:     my $scrsid='';
                    785:     my $sessay='';
                    786: # go through all essays ...
1.596.2.12.2.  (raeburn  787:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  788: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       789: # ... except the same student
1.426     albertel  790:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  791:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  792: 	$tessay=~s/\W+/ /gs;
1.87      www       793: # String similarity gives up if not even limit
1.426     albertel  794: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       795: # Found one
1.426     albertel  796: 	if ($tsimilar>$limit) {
                    797: 	    $limit=$tsimilar;
                    798: 	    $sname=$tname;
                    799: 	    $sdom=$tdom;
                    800: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  801:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  802: 	}
1.87      www       803:     }
1.88      www       804:     if ($limit>0.6) {
1.87      www       805:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    806:     } else {
                    807:        return ('','','','',0);
                    808:     }
                    809: }
                    810: 
1.44      ng        811: #-------------------------------------------------------------------
                    812: 
                    813: #------------------------------------ Receipt Verification Routines
1.45      ng        814: #
1.44      ng        815: #--- Check whether a receipt number is valid.---
                    816: sub verifyreceipt {
                    817:     my $request  = shift;
                    818: 
1.257     albertel  819:     my $courseid = $env{'request.course.id'};
1.184     www       820:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  821: 	$env{'form.receipt'};
1.44      ng        822:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  823:     my ($symb)   = &get_symb($request);
1.44      ng        824: 
1.487     albertel  825:     my $title.=
                    826: 	'<h3><span class="LC_info">'.
1.584     bisitz    827: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  828: 	'</span></h3>'."\n".
1.596.2.12.2.  2(raebur  829:3): 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
1.487     albertel  830: 	'</h4>'."\n";
1.44      ng        831: 
                    832:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   833:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  834:     
                    835:     my $receiptparts=0;
1.390     albertel  836:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    837: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  838:     my $parts=['0'];
1.582     raeburn   839:     if ($receiptparts) {
                    840:         my $res_error; 
                    841:         ($parts)=&response_type($symb,\$res_error);
                    842:         if ($res_error) {
                    843:             return &navmap_errormsg();
                    844:         } 
                    845:     }
1.486     albertel  846:     
                    847:     my $header = 
                    848: 	&Apache::loncommon::start_data_table().
                    849: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  850: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    851: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    852: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  853:     if ($receiptparts) {
1.487     albertel  854: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  855:     }
                    856:     $header.=
                    857: 	&Apache::loncommon::end_data_table_header_row();
                    858: 
1.294     albertel  859:     foreach (sort 
                    860: 	     {
                    861: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    862: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    863: 		 }
                    864: 		 return $a cmp $b;
                    865: 	     } (keys(%$fullname))) {
1.44      ng        866: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  867: 	foreach my $part (@$parts) {
                    868: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  869: 		$contents.=
                    870: 		    &Apache::loncommon::start_data_table_row().
                    871: 		    '<td>&nbsp;'."\n".
1.177     albertel  872: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  873: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  874: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    875: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    876: 		if ($receiptparts) {
                    877: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    878: 		}
1.486     albertel  879: 		$contents.= 
                    880: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  881: 		
                    882: 		$matches++;
                    883: 	    }
1.44      ng        884: 	}
                    885:     }
                    886:     if ($matches == 0) {
1.584     bisitz    887:         $string = $title
                    888:                  .'<p class="LC_warning">'
                    889:                  .&mt('No match found for the above receipt number.')
                    890:                  .'</p>';
1.44      ng        891:     } else {
1.324     albertel  892: 	$string = &jscriptNform($symb).$title.
1.487     albertel  893: 	    '<p>'.
1.584     bisitz    894: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  895: 	    '</p>'.
1.486     albertel  896: 	    $header.
                    897: 	    $contents.
                    898: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        899:     }
1.324     albertel  900:     return $string.&show_grading_menu_form($symb);
1.44      ng        901: }
                    902: 
                    903: #--- This is called by a number of programs.
                    904: #--- Called from the Grading Menu - View/Grade an individual student
                    905: #--- Also called directly when one clicks on the subm button 
                    906: #    on the problem page.
1.30      ng        907: sub listStudents {
1.41      ng        908:     my ($request) = shift;
1.49      albertel  909: 
1.324     albertel  910:     my ($symb) = &get_symb($request);
1.257     albertel  911:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    912:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    913:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  914:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  915:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    916:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  917:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    918: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  919: 
1.548     bisitz    920:     my $result='<h3><span class="LC_info">&nbsp;'
                    921: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  922: 	.'</span></h3>';
1.118     ng        923: 
1.324     albertel  924:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  925: 
1.596.2.12.2.  6(raebur  926:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   927: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    928: 		'single'   => 'Please select the student before clicking on the Next button.',
                    929: 	     );
1.596.2.12.2.  6(raebur  930:6):     &js_escape(\%js_lt);
1.45      ng        931:     $request->print(<<LISTJAVASCRIPT);
                    932: <script type="text/javascript" language="javascript">
1.110     ng        933:     function checkSelect(checkBox) {
                    934: 	var ctr=0;
                    935: 	var sense="";
                    936: 	if (checkBox.length > 1) {
                    937: 	    for (var i=0; i<checkBox.length; i++) {
                    938: 		if (checkBox[i].checked) {
                    939: 		    ctr++;
                    940: 		}
                    941: 	    }
1.596.2.12.2.  6(raebur  942:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng        943: 	} else {
                    944: 	    if (checkBox.checked) {
                    945: 		ctr = 1;
                    946: 	    }
1.596.2.12.2.  6(raebur  947:6): 	    sense = '$js_lt{'single'}';
1.110     ng        948: 	}
                    949: 	if (ctr == 0) {
1.485     albertel  950: 	    alert(sense);
1.110     ng        951: 	    return false;
                    952: 	}
                    953: 	document.gradesub.submit();
                    954:     }
                    955: 
                    956:     function reLoadList(formname) {
1.112     ng        957: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        958: 	formname.command.value = 'submission';
                    959: 	formname.submit();
                    960:     }
1.45      ng        961: </script>
                    962: LISTJAVASCRIPT
                    963: 
1.118     ng        964:     &commonJSfunctions($request);
1.41      ng        965:     $request->print($result);
1.39      ng        966: 
1.401     albertel  967:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    968:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  969:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  970: 	"\n".$table;
                    971: 	
1.561     bisitz    972:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    973:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    974:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    975:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    976:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    977:                   .&Apache::lonhtmlcommon::row_closure();
                    978:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    979:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    980:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    981:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    982:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  983: 
                    984:     my $submission_options;
1.257     albertel  985:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  986: 	$submission_options.=
                    987: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  988:     }
1.442     banghart  989:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    990:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  991:     $env{'form.Status'} = $saveStatus;
1.485     albertel  992:     $submission_options.=
1.592     bisitz    993:         '<span class="LC_nobreak">'.
                    994:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    995:         &mt('last submission only').' </label></span>'."\n".
                    996:         '<span class="LC_nobreak">'.
                    997:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    998:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    999:         '<span class="LC_nobreak">'.
                   1000:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                   1001:         &mt('by dates and submissions').'</label></span>'."\n".
                   1002:         '<span class="LC_nobreak">'.
                   1003:         '<label><input type="radio" name="lastSub" value="all" /> '.
                   1004:         &mt('all details').'</label></span>';
1.561     bisitz   1005:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                   1006:                   .$submission_options
                   1007:                   .&Apache::lonhtmlcommon::row_closure();
                   1008: 
                   1009:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1010:                   .'<select name="increment">'
                   1011:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1012:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1013:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1014:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1015:                   .'</select>'
                   1016:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1017: 
                   1018:     $gradeTable .= 
1.432     banghart 1019:         &build_section_inputs().
1.45      ng       1020: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel 1021: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                   1022: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                   1023: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1024: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1025: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1026: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1027: 
1.257     albertel 1028:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz   1029: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1030:     } else {
1.561     bisitz   1031:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1032:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1033:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1034:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1035:     }
1.112     ng       1036: 
1.561     bisitz   1037:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1038:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1039:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1040:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1041: 
                   1042:     $gradeTable .= '<p>'
                   1043:                   .&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"
                   1044:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1045:                   .'</p>';
1.249     albertel 1046: 
                   1047: # checkall buttons
                   1048:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1049:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1050:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1051:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1052:     $gradeTable.=&check_buttons();
1.450     banghart 1053:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1054:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1055: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1056:     my $loop = 0;
                   1057:     while ($loop < 2) {
1.485     albertel 1058: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1059: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1060: 	if ($env{'form.showgrading'} eq 'yes' 
                   1061: 	    && $submitonly ne 'queued'
                   1062: 	    && $submitonly ne 'all') {
1.485     albertel 1063: 	    foreach my $part (sort(@$partlist)) {
                   1064: 		my $display_part=
                   1065: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1066: 		$gradeTable.=
                   1067: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1068: 	    }
1.301     albertel 1069: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1070: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1071: 	}
                   1072: 	$loop++;
1.126     ng       1073: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1074:     }
1.474     albertel 1075:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1076: 
1.45      ng       1077:     my $ctr = 0;
1.294     albertel 1078:     foreach my $student (sort 
                   1079: 			 {
                   1080: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1081: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1082: 			     }
                   1083: 			     return $a cmp $b;
                   1084: 			 }
                   1085: 			 (keys(%$fullname))) {
1.41      ng       1086: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1087: 
1.110     ng       1088: 	my %status = ();
1.301     albertel 1089: 
                   1090: 	if ($submitonly eq 'queued') {
                   1091: 	    my %queue_status = 
                   1092: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1093: 							$udom,$uname);
                   1094: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1095: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1096: 	}
                   1097: 
                   1098: 	if ($env{'form.showgrading'} eq 'yes' 
                   1099: 	    && $submitonly ne 'queued'
                   1100: 	    && $submitonly ne 'all') {
1.324     albertel 1101: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1102: 	    my $submitted = 0;
1.164     albertel 1103: 	    my $graded = 0;
1.248     albertel 1104: 	    my $incorrect = 0;
1.110     ng       1105: 	    foreach (keys(%status)) {
1.145     albertel 1106: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1107: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1108: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1109: 		
1.110     ng       1110: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1111: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1112: 		    $submitted = 0;
1.150     albertel 1113: 		    my ($part)=split(/\./,$partid);
1.110     ng       1114: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1115: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1116: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1117: 		}
1.41      ng       1118: 	    }
1.248     albertel 1119: 	    
1.156     albertel 1120: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1121: 				     $submitonly eq 'incorrect' ||
                   1122: 				     $submitonly eq 'graded'));
1.248     albertel 1123: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1124: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1125: 	}
1.34      ng       1126: 
1.45      ng       1127: 	$ctr++;
1.249     albertel 1128: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1129:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1130: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1131: 	    if ($ctr%2 ==1) {
                   1132: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1133: 	    }
1.126     ng       1134: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1135:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1136:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1137: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1138: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1139: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1140: 
1.257     albertel 1141: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1142: 		foreach (sort(keys(%status))) {
1.485     albertel 1143: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1144: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1145: 		}
1.41      ng       1146: 	    }
1.126     ng       1147: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1148: 	    if ($ctr%2 ==0) {
                   1149: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1150: 	    }
1.41      ng       1151: 	}
                   1152:     }
1.110     ng       1153:     if ($ctr%2 ==1) {
1.126     ng       1154: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1155: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1156: 		&& $submitonly ne 'queued'
                   1157: 		&& $submitonly ne 'all') {
1.110     ng       1158: 		foreach (@$partlist) {
                   1159: 		    $gradeTable.='<td>&nbsp;</td>';
                   1160: 		}
1.301     albertel 1161: 	    } elsif ($submitonly eq 'queued') {
                   1162: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1163: 	    }
1.474     albertel 1164: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1165:     }
                   1166: 
1.474     albertel 1167:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1168:         '<input type="button" '.
                   1169:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1170:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1171:     if ($ctr == 0) {
1.96      albertel 1172: 	my $num_students=(scalar(keys(%$fullname)));
                   1173: 	if ($num_students eq 0) {
1.485     albertel 1174: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1175: 	} else {
1.171     albertel 1176: 	    my $submissions='submissions';
                   1177: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1178: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1179: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1180: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1181:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1182: 		    $num_students).
                   1183: 		'</span><br />';
1.96      albertel 1184: 	}
1.46      ng       1185:     } elsif ($ctr == 1) {
1.474     albertel 1186: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1187:     }
1.324     albertel 1188:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1189:     $request->print($gradeTable);
1.44      ng       1190:     return '';
1.10      ng       1191: }
                   1192: 
1.44      ng       1193: #---- Called from the listStudents routine
1.249     albertel 1194: 
                   1195: sub check_script {
                   1196:     my ($form, $type)=@_;
                   1197:     my $chkallscript='<script type="text/javascript">
                   1198:     function checkall() {
                   1199:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1200:             ele = document.forms.'.$form.'.elements[i];
                   1201:             if (ele.name == "'.$type.'") {
                   1202:             document.forms.'.$form.'.elements[i].checked=true;
                   1203:                                        }
                   1204:         }
                   1205:     }
                   1206: 
                   1207:     function checksec() {
                   1208:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1209:             ele = document.forms.'.$form.'.elements[i];
                   1210:            string = document.forms.'.$form.'.chksec.value;
                   1211:            if
                   1212:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1213:               document.forms.'.$form.'.elements[i].checked=true;
                   1214:             }
                   1215:         }
                   1216:     }
                   1217: 
                   1218: 
                   1219:     function uncheckall() {
                   1220:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1221:             ele = document.forms.'.$form.'.elements[i];
                   1222:             if (ele.name == "'.$type.'") {
                   1223:             document.forms.'.$form.'.elements[i].checked=false;
                   1224:                                        }
                   1225:         }
                   1226:     }
                   1227: 
                   1228: </script>'."\n";
                   1229:     return $chkallscript;
                   1230: }
                   1231: 
                   1232: sub check_buttons {
1.485     albertel 1233:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1234:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1235:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1236:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1237:     return $buttons;
                   1238: }
                   1239: 
1.44      ng       1240: #     Displays the submissions for one student or a group of students
1.34      ng       1241: sub processGroup {
1.41      ng       1242:     my ($request)  = shift;
                   1243:     my $ctr        = 0;
1.155     albertel 1244:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1245:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1246: 
1.396     banghart 1247:     foreach my $student (@stuchecked) {
                   1248: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1249: 	$env{'form.student'}        = $uname;
                   1250: 	$env{'form.userdom'}        = $udom;
                   1251: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1252: 	&submission($request,$ctr,$total);
                   1253: 	$ctr++;
                   1254:     }
                   1255:     return '';
1.35      ng       1256: }
1.34      ng       1257: 
1.44      ng       1258: #------------------------------------------------------------------------------------
                   1259: #
                   1260: #-------------------------- Next few routines handles grading by student, essentially
                   1261: #                           handles essay response type problem/part
                   1262: #
                   1263: #--- Javascript to handle the submission page functionality ---
                   1264: sub sub_page_js {
                   1265:     my $request = shift;
1.596.2.12.2.  6(raebur 1266:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1267:6):     &js_escape(\$alertmsg);
1.44      ng       1268:     $request->print(<<SUBJAVASCRIPT);
                   1269: <script type="text/javascript" language="javascript">
1.71      ng       1270:     function updateRadio(formname,id,weight) {
1.125     ng       1271: 	var gradeBox = formname["GD_BOX"+id];
                   1272: 	var radioButton = formname["RADVAL"+id];
                   1273: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1274: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1275: 	gradeBox.value = pts;
                   1276: 	var resetbox = false;
                   1277: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1278: 	    alert("$alertmsg"+pts);
1.71      ng       1279: 	    for (var i=0; i<radioButton.length; i++) {
                   1280: 		if (radioButton[i].checked) {
                   1281: 		    gradeBox.value = i;
                   1282: 		    resetbox = true;
                   1283: 		}
                   1284: 	    }
                   1285: 	    if (!resetbox) {
                   1286: 		formtextbox.value = "";
                   1287: 	    }
                   1288: 	    return;
1.44      ng       1289: 	}
1.71      ng       1290: 
                   1291: 	if (pts > weight) {
                   1292: 	    var resp = confirm("You entered a value ("+pts+
                   1293: 			       ") greater than the weight for the part. Accept?");
                   1294: 	    if (resp == false) {
1.125     ng       1295: 		gradeBox.value = oldpts;
1.71      ng       1296: 		return;
                   1297: 	    }
1.44      ng       1298: 	}
1.13      albertel 1299: 
1.71      ng       1300: 	for (var i=0; i<radioButton.length; i++) {
                   1301: 	    radioButton[i].checked=false;
                   1302: 	    if (pts == i && pts != "") {
                   1303: 		radioButton[i].checked=true;
                   1304: 	    }
                   1305: 	}
                   1306: 	updateSelect(formname,id);
1.125     ng       1307: 	formname["stores"+id].value = "0";
1.41      ng       1308:     }
1.5       albertel 1309: 
1.72      ng       1310:     function writeBox(formname,id,pts) {
1.125     ng       1311: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1312: 	if (checkSolved(formname,id) == 'update') {
                   1313: 	    gradeBox.value = pts;
                   1314: 	} else {
1.125     ng       1315: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1316: 	    gradeBox.value = oldpts;
1.125     ng       1317: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1318: 	    for (var i=0; i<radioButton.length; i++) {
                   1319: 		radioButton[i].checked=false;
1.72      ng       1320: 		if (i == oldpts) {
1.71      ng       1321: 		    radioButton[i].checked=true;
                   1322: 		}
                   1323: 	    }
1.41      ng       1324: 	}
1.125     ng       1325: 	formname["stores"+id].value = "0";
1.71      ng       1326: 	updateSelect(formname,id);
                   1327: 	return;
1.41      ng       1328:     }
1.44      ng       1329: 
1.71      ng       1330:     function clearRadBox(formname,id) {
                   1331: 	if (checkSolved(formname,id) == 'noupdate') {
                   1332: 	    updateSelect(formname,id);
                   1333: 	    return;
                   1334: 	}
1.125     ng       1335: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1336: 	for (var i=0; i<gradeSelect.length; i++) {
                   1337: 	    if (gradeSelect[i].selected) {
                   1338: 		var selectx=i;
                   1339: 	    }
                   1340: 	}
1.125     ng       1341: 	var stores = formname["stores"+id];
1.71      ng       1342: 	if (selectx == stores.value) { return };
1.125     ng       1343: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1344: 	gradeBox.value = "";
1.125     ng       1345: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1346: 	for (var i=0; i<radioButton.length; i++) {
                   1347: 	    radioButton[i].checked=false;
                   1348: 	}
                   1349: 	stores.value = selectx;
                   1350:     }
1.5       albertel 1351: 
1.71      ng       1352:     function checkSolved(formname,id) {
1.125     ng       1353: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1354: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1355: 	    if (!reply) {return "noupdate";}
1.120     ng       1356: 	    formname.overRideScore.value = 'yes';
1.41      ng       1357: 	}
1.71      ng       1358: 	return "update";
1.13      albertel 1359:     }
1.71      ng       1360: 
                   1361:     function updateSelect(formname,id) {
1.125     ng       1362: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1363: 	return;
1.41      ng       1364:     }
1.33      ng       1365: 
1.121     ng       1366: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1367:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1368: 	formname.gradeOpt.value = val;
1.71      ng       1369: 	if (val == "Save & Next") {
                   1370: 	    for (i=0;i<=total;i++) {
                   1371: 		for (j=0;j<parttot;j++) {
1.125     ng       1372: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1373: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1374: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1375: 			if (points == "") {
1.125     ng       1376: 			    var name = formname["name"+i].value;
1.129     ng       1377: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1378: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1379: 					       ", part "+partid+". Continue?");
1.71      ng       1380: 			    if (resp == false) {
1.125     ng       1381: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1382: 				return false;
                   1383: 			    }
                   1384: 			}
                   1385: 		    }
                   1386: 		}
                   1387: 	    }
                   1388: 	}
1.121     ng       1389: 	if (val == "Grade Student") {
                   1390: 	    formname.showgrading.value = "yes";
                   1391: 	    if (formname.Status.value == "") {
                   1392: 		formname.Status.value = "Active";
                   1393: 	    }
                   1394: 	    formname.studentNo.value = total;
                   1395: 	}
1.120     ng       1396: 	formname.submit();
                   1397:     }
                   1398: 
1.71      ng       1399: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1400:     function checkSubmitPage(formname,total) {
                   1401: 	noscore = new Array(100);
                   1402: 	var ptr = 0;
                   1403: 	for (i=1;i<total;i++) {
1.125     ng       1404: 	    var partid = formname["q_"+i].value;
1.127     ng       1405: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1406: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1407: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1408: 		if (points == "" && status != "correct_by_student") {
                   1409: 		    noscore[ptr] = i;
                   1410: 		    ptr++;
                   1411: 		}
                   1412: 	    }
                   1413: 	}
                   1414: 	if (ptr != 0) {
                   1415: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1416: 	    var prolist = "";
                   1417: 	    if (ptr == 1) {
                   1418: 		prolist = noscore[0];
                   1419: 	    } else {
                   1420: 		var i = 0;
                   1421: 		while (i < ptr-1) {
                   1422: 		    prolist += noscore[i]+", ";
                   1423: 		    i++;
                   1424: 		}
                   1425: 		prolist += "and "+noscore[i];
                   1426: 	    }
                   1427: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1428: 	    if (resp == false) {
                   1429: 		return false;
                   1430: 	    }
                   1431: 	}
1.45      ng       1432: 
1.71      ng       1433: 	formname.submit();
                   1434:     }
                   1435: </script>
                   1436: SUBJAVASCRIPT
                   1437: }
1.45      ng       1438: 
1.71      ng       1439: #--- javascript for essay type problem --
                   1440: sub sub_page_kw_js {
                   1441:     my $request = shift;
1.80      ng       1442:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1443:     &commonJSfunctions($request);
1.350     albertel 1444: 
1.351     albertel 1445:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1446:     <script text="text/javascript">
                   1447:     function checkInput() {
                   1448:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1449:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1450:       var usrctr = document.msgcenter.usrctr.value;
                   1451:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1452:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1453: 
                   1454:       var msgchk = "";
                   1455:       if (document.msgcenter.subchk.checked) {
                   1456:          msgchk = "msgsub,";
                   1457:       }
                   1458:       var includemsg = 0;
                   1459:       for (var i=1; i<=nmsg; i++) {
                   1460:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1461:           var frmmsg = document.msgcenter["msg"+i];
                   1462:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1463:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1464:           showflg.value = "1";
                   1465:           var chkbox = document.msgcenter["msgn"+i];
                   1466:           if (chkbox.checked) {
                   1467:              msgchk += "savemsg"+i+",";
                   1468:              includemsg = 1;
                   1469:           }
                   1470:       }
                   1471:       if (document.msgcenter.newmsgchk.checked) {
                   1472:          msgchk += "newmsg"+usrctr;
                   1473:          includemsg = 1;
                   1474:       }
                   1475:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1476:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1477:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1478:       includemsg.value = msgchk;
                   1479: 
                   1480:       self.close()
                   1481: 
                   1482:     }
                   1483:     </script>
                   1484: INNERJS
                   1485: 
1.351     albertel 1486:     my $inner_js_highlight_central=<<INNERJS;
                   1487:  <script type="text/javascript">
                   1488:     function updateChoice(flag) {
                   1489:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1490:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1491:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1492:       opener.document.SCORE.refresh.value = "on";
                   1493:       if (opener.document.SCORE.keywords.value!=""){
                   1494:          opener.document.SCORE.submit();
                   1495:       }
                   1496:       self.close()
                   1497:     }
                   1498: </script>
                   1499: INNERJS
                   1500: 
                   1501:     my $start_page_msg_central = 
                   1502:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1503: 				       {'js_ready'  => 1,
                   1504: 					'only_body' => 1,
                   1505: 					'bgcolor'   =>'#FFFFFF',});
                   1506:     my $end_page_msg_central = 
                   1507: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1508: 
                   1509: 
                   1510:     my $start_page_highlight_central = 
                   1511:         &Apache::loncommon::start_page('Highlight Central',
                   1512: 				       $inner_js_highlight_central,
1.350     albertel 1513: 				       {'js_ready'  => 1,
                   1514: 					'only_body' => 1,
                   1515: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1516:     my $end_page_highlight_central = 
1.350     albertel 1517: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1518: 
1.219     www      1519:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1520:     $docopen=~s/^document\.//;
1.596.2.12.2.  6(raebur 1521:6):     my %js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1522:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1523:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1524:                 adds => 'Add selection to keyword list? Edit if desired.',
1.596.2.12.2.  6(raebur 1525:6):                 col1 => 'red',
                   1526:6):                 col2 => 'green',
                   1527:6):                 col3 => 'blue',
                   1528:6):                 siz1 => 'normal',
                   1529:6):                 siz2 => '+1',
                   1530:6):                 siz3 => '+2',
                   1531:6):                 sty1 => 'normal',
                   1532:6):                 sty2 => 'italic',
                   1533:6):                 sty3 => 'bold',
                   1534:6):              );
                   1535:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1536:                 comp => 'Compose Message for: ',
                   1537:                 incl => 'Include',
                   1538:                 type => 'Type',
                   1539:                 subj => 'Subject',
                   1540:                 mesa => 'Message',
                   1541:                 new  => 'New',
                   1542:                 save => 'Save',
                   1543:                 canc => 'Cancel',
                   1544:                 kehi => 'Keyword Highlight Options',
                   1545:                 txtc => 'Text Color',
                   1546:                 font => 'Font Size',
                   1547:                 fnst => 'Font Style',
                   1548:              );
1.596.2.12.2.  6(raebur 1549:6):     &js_escape(\%js_lt);
                   1550:6):     &html_escape(\%html_js_lt);
                   1551:6):     &js_escape(\%html_js_lt);
1.71      ng       1552:     $request->print(<<SUBJAVASCRIPT);
                   1553: <script type="text/javascript" language="javascript">
1.45      ng       1554: 
1.44      ng       1555: //===================== Show list of keywords ====================
1.122     ng       1556:   function keywords(formname) {
1.596.2.12.2.  6(raebur 1557:6):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1558:     if (nret==null) return;
1.122     ng       1559:     formname.keywords.value = nret;
1.44      ng       1560: 
1.122     ng       1561:     if (formname.keywords.value != "") {
1.128     ng       1562: 	formname.refresh.value = "on";
1.122     ng       1563: 	formname.submit();
1.44      ng       1564:     }
                   1565:     return;
                   1566:   }
                   1567: 
                   1568: //===================== Script to view submitted by ==================
                   1569:   function viewSubmitter(submitter) {
                   1570:     document.SCORE.refresh.value = "on";
                   1571:     document.SCORE.NCT.value = "1";
                   1572:     document.SCORE.unamedom0.value = submitter;
                   1573:     document.SCORE.submit();
                   1574:     return;
                   1575:   }
                   1576: 
                   1577: //===================== Script to add keyword(s) ==================
                   1578:   function getSel() {
                   1579:     if (document.getSelection) txt = document.getSelection();
                   1580:     else if (document.selection) txt = document.selection.createRange().text;
                   1581:     else return;
                   1582:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1583:     if (cleantxt=="") {
1.596.2.12.2.  6(raebur 1584:6): 	alert("$js_lt{'plse'}");
1.44      ng       1585: 	return;
                   1586:     }
1.596.2.12.2.  6(raebur 1587:6):     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1588:     if (nret==null) return;
1.127     ng       1589:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1590:     if (document.SCORE.keywords.value != "") {
1.127     ng       1591: 	document.SCORE.refresh.value = "on";
1.44      ng       1592: 	document.SCORE.submit();
                   1593:     }
                   1594:     return;
                   1595:   }
                   1596: 
                   1597: //====================== Script for composing message ==============
1.80      ng       1598:    // preload images
                   1599:    img1 = new Image();
                   1600:    img1.src = "$iconpath/mailbkgrd.gif";
                   1601:    img2 = new Image();
                   1602:    img2.src = "$iconpath/mailto.gif";
                   1603: 
1.44      ng       1604:   function msgCenter(msgform,usrctr,fullname) {
                   1605:     var Nmsg  = msgform.savemsgN.value;
                   1606:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1607:     var subject = msgform.msgsub.value;
1.127     ng       1608:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1609:     re = /msgsub/;
                   1610:     var shwsel = "";
                   1611:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1612:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1613:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1614:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1615: 	var testmsg = "savemsg"+i+",";
                   1616: 	re = new RegExp(testmsg,"g");
1.44      ng       1617: 	shwsel = "";
                   1618: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1619: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1620: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1621: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1622: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1623:     }
1.125     ng       1624:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1625:     shwsel = "";
                   1626:     re = /newmsg/;
                   1627:     if (re.test(msgchk)) { shwsel = "checked" }
                   1628:     newMsg(newmsg,shwsel);
                   1629:     msgTail(); 
                   1630:     return;
                   1631:   }
                   1632: 
1.123     ng       1633:   function checkEntities(strx) {
                   1634:     if (strx.length == 0) return strx;
                   1635:     var orgStr = ["&", "<", ">", '"']; 
                   1636:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1637:     var counter = 0;
                   1638:     while (counter < 4) {
                   1639: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1640: 	counter++;
                   1641:     }
                   1642:     return strx;
                   1643:   }
                   1644: 
                   1645:   function strReplace(strx, orgStr, newStr) {
                   1646:     return strx.split(orgStr).join(newStr);
                   1647:   }
                   1648: 
1.44      ng       1649:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1650:     var height = 70*Nmsg+250;
1.44      ng       1651:     if (height > 600) {
                   1652: 	height = 600;
                   1653:     }
1.118     ng       1654:     var xpos = (screen.width-600)/2;
                   1655:     xpos = (xpos < 0) ? '0' : xpos;
                   1656:     var ypos = (screen.height-height)/2-30;
                   1657:     ypos = (ypos < 0) ? '0' : ypos;
                   1658: 
1.596.2.12.2.  (raeburn 1659:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1660:     pWin.focus();
                   1661:     pDoc = pWin.document;
1.219     www      1662:     pDoc.$docopen;
1.351     albertel 1663:     pDoc.write('$start_page_msg_central');
1.76      ng       1664: 
                   1665:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1666:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  6(raebur 1667:6):     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1668: 
1.564     bisitz   1669:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1670:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.12.2.  6(raebur 1671: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       1672: }
                   1673:     function displaySubject(msg,shwsel) {
1.76      ng       1674:     pDoc = pWin.document;
                   1675:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.12.2.  6(raebur 1676:6):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.465     albertel 1677:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1678:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1679: }
                   1680: 
1.72      ng       1681:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1682:     pDoc = pWin.document;
                   1683:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1684:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1685:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1686:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1687: }
                   1688: 
                   1689:   function newMsg(newmsg,shwsel) {
1.76      ng       1690:     pDoc = pWin.document;
                   1691:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.12.2.  6(raebur 1692:6):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1693:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1694:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1695: }
                   1696: 
                   1697:   function msgTail() {
1.76      ng       1698:     pDoc = pWin.document;
1.465     albertel 1699:     pDoc.write("<\\/table>");
                   1700:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1701:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1702:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1703:     pDoc.write("<\\/form>");
1.351     albertel 1704:     pDoc.write('$end_page_msg_central');
1.128     ng       1705:     pDoc.close();
1.44      ng       1706: }
                   1707: 
                   1708: //====================== Script for keyword highlight options ==============
                   1709:   function kwhighlight() {
                   1710:     var kwclr    = document.SCORE.kwclr.value;
                   1711:     var kwsize   = document.SCORE.kwsize.value;
                   1712:     var kwstyle  = document.SCORE.kwstyle.value;
                   1713:     var redsel = "";
                   1714:     var grnsel = "";
                   1715:     var blusel = "";
1.596.2.12.2.  6(raebur 1716:6):     var txtcol1 = "$js_lt{'col1'}";
                   1717:6):     var txtcol2 = "$js_lt{'col2'}";
                   1718:6):     var txtcol3 = "$js_lt{'col3'}";
                   1719:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1720:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1721:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1722:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1723:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1724:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1725:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1726:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1727:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1728:     var sznsel = "";
                   1729:     var sz1sel = "";
                   1730:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1731:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1732:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1733:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1734:     var synsel = "";
                   1735:     var syisel = "";
                   1736:     var sybsel = "";
1.596.2.12.2.  8(raebur 1737:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1738:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1739:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1740:     highlightCentral();
1.596.2.12.2.  8(raebur 1741:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1742:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1743:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1744:     highlightend();
                   1745:     return;
                   1746:   }
                   1747: 
                   1748:   function highlightCentral() {
1.76      ng       1749: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1750:     var xpos = (screen.width-400)/2;
                   1751:     xpos = (xpos < 0) ? '0' : xpos;
                   1752:     var ypos = (screen.height-330)/2-30;
                   1753:     ypos = (ypos < 0) ? '0' : ypos;
                   1754: 
1.206     albertel 1755:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1756:     hwdWin.focus();
                   1757:     var hDoc = hwdWin.document;
1.219     www      1758:     hDoc.$docopen;
1.351     albertel 1759:     hDoc.write('$start_page_highlight_central');
1.76      ng       1760:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1761:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1762: 
1.596.2.12.2.  8(raebur 1763:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1764: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       1765:   }
                   1766: 
                   1767:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1768:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1769:4):     hDoc.write("<tr>");
1.76      ng       1770:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1771:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1772:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1773:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1774:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1775:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1776:     hDoc.write("<\\/tr>");
1.44      ng       1777:   }
                   1778: 
                   1779:   function highlightend() { 
1.76      ng       1780:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1781:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1782:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1783:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1784:     hDoc.write("<\\/form>");
1.351     albertel 1785:     hDoc.write('$end_page_highlight_central');
1.128     ng       1786:     hDoc.close();
1.44      ng       1787:   }
                   1788: 
                   1789: </script>
                   1790: SUBJAVASCRIPT
                   1791: }
                   1792: 
1.349     albertel 1793: sub get_increment {
1.348     bowersj2 1794:     my $increment = $env{'form.increment'};
                   1795:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1796:         $increment != .1) {
                   1797:         $increment = 1;
                   1798:     }
                   1799:     return $increment;
                   1800: }
                   1801: 
1.585     bisitz   1802: sub gradeBox_start {
                   1803:     return (
                   1804:         &Apache::loncommon::start_data_table()
                   1805:        .&Apache::loncommon::start_data_table_header_row()
                   1806:        .'<th>'.&mt('Part').'</th>'
                   1807:        .'<th>'.&mt('Points').'</th>'
                   1808:        .'<th>&nbsp;</th>'
                   1809:        .'<th>'.&mt('Assign Grade').'</th>'
                   1810:        .'<th>'.&mt('Weight').'</th>'
                   1811:        .'<th>'.&mt('Grade Status').'</th>'
                   1812:        .&Apache::loncommon::end_data_table_header_row()
                   1813:     );
                   1814: }
                   1815: 
                   1816: sub gradeBox_end {
                   1817:     return (
                   1818:         &Apache::loncommon::end_data_table()
                   1819:     );
                   1820: }
1.71      ng       1821: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1822: sub gradeBox {
1.322     albertel 1823:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1824:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1825: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1826:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1827:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1828:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1829:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1830:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1831: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1832:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1833:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1834:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1835: 				       [$partid]);
                   1836:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1837:     if ($last_resets{$partid}) {
                   1838:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1839:     }
1.596.2.12.2.  8(raebur 1840:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1841:     my $ctr = 0;
1.348     bowersj2 1842:     my $thisweight = 0;
1.349     albertel 1843:     my $increment = &get_increment();
1.485     albertel 1844: 
                   1845:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1846:     while ($thisweight<=$wgt) {
1.532     bisitz   1847: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1848:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1849: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1850: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1851: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1852:         $thisweight += $increment;
1.71      ng       1853: 	$ctr++;
                   1854:     }
1.485     albertel 1855:     $radio.='</tr></table>';
                   1856: 
                   1857:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1858: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1859: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1860: 	$wgt.')" /></td>'."\n";
1.485     albertel 1861:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1862: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1863: 	' </td>'."\n";
                   1864:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1865: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1866:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1867: 	$line.='<option></option>'.
                   1868: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1869:     } else {
1.485     albertel 1870: 	$line.='<option selected="selected"></option>'.
                   1871: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1872:     }
1.485     albertel 1873:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1874: 
                   1875: 
                   1876:     $result .= 
1.596.2.12.2.  8(raebur 1877:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1878:3):     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1.71      ng       1879:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1880: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1881: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1882: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1883:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1884:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1885:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1886:         $aggtries.'" />'."\n";
1.582     raeburn  1887:     my $res_error;
                   1888:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 1889:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1890:     if ($res_error) {
                   1891:         return &navmap_errormsg();
                   1892:     }
1.318     banghart 1893:     return $result;
                   1894: }
1.322     albertel 1895: 
                   1896: sub handback_box {
1.582     raeburn  1897:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1898:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1899:     my (@respids);
1.596.2.4  raeburn  1900:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1901:     foreach my $part_response_id (@part_response_id) {
                   1902:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1903:         if ($part eq $partid) {
1.375     albertel 1904:             push(@respids,$resp);
1.323     banghart 1905:         }
                   1906:     }
1.318     banghart 1907:     my $result;
1.323     banghart 1908:     foreach my $respid (@respids) {
1.322     albertel 1909: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1910: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1911: 	next if (!@$files);
1.596.2.4  raeburn  1912: 	my $file_counter = 0;
1.313     banghart 1913: 	foreach my $file (@$files) {
1.368     banghart 1914: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1915:                 $file_counter++;
1.368     banghart 1916:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1917:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1918:     	        $file_disp = "$name.$ext";
                   1919:     	        $file = $file_path.$file_disp;
                   1920:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1921:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1922:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1923:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1924: 	    }
1.322     albertel 1925: 	}
1.596.2.4  raeburn  1926:         if ($file_counter) {
                   1927:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1928:                        '<span class="LC_info">'.
                   1929:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1930:         }
1.313     banghart 1931:     }
1.318     banghart 1932:     return $result;    
1.71      ng       1933: }
1.44      ng       1934: 
1.58      albertel 1935: sub show_problem {
1.382     albertel 1936:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1937:     my $rendered;
1.382     albertel 1938:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1939:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1940:     if ($mode eq 'both' or $mode eq 'text') {
                   1941: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1942: 						       $env{'request.course.id'},
                   1943: 						       undef,\%form);
1.144     albertel 1944:     }
1.58      albertel 1945:     if ($removeform) {
                   1946: 	$rendered=~s|<form(.*?)>||g;
                   1947: 	$rendered=~s|</form>||g;
1.374     albertel 1948: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1949:     }
1.144     albertel 1950:     my $companswer;
                   1951:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1952: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1953: 	$companswer=
                   1954: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1955: 						    $env{'request.course.id'},
                   1956: 						    %form);
1.144     albertel 1957:     }
1.58      albertel 1958:     if ($removeform) {
                   1959: 	$companswer=~s|<form(.*?)>||g;
                   1960: 	$companswer=~s|</form>||g;
1.144     albertel 1961: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1962:     }
1.596.2.12.2.  (raeburn 1963:):     my $renderheading = &mt('View of the problem');
                   1964:):     my $answerheading = &mt('Correct answer');
                   1965:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1966:):         my $stu_fullname = $env{'form.fullname'};
                   1967:):         if ($stu_fullname eq '') {
                   1968:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1969:):         }
                   1970:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1971:):         if ($forwhom ne '') {
                   1972:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1973:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1974:):         }
                   1975:):     }
1.468     albertel 1976:     $rendered=
1.588     bisitz   1977:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1978:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1979:        .$rendered
                   1980:        .'</div>';
1.468     albertel 1981:     $companswer=
1.588     bisitz   1982:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1983:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1984:        .$companswer
                   1985:        .'</div>';
1.468     albertel 1986:     my $result;
1.144     albertel 1987:     if ($mode eq 'both') {
1.588     bisitz   1988:         $result=$rendered.$companswer;
1.144     albertel 1989:     } elsif ($mode eq 'text') {
1.588     bisitz   1990:         $result=$rendered;
1.144     albertel 1991:     } elsif ($mode eq 'answer') {
1.588     bisitz   1992:         $result=$companswer;
1.144     albertel 1993:     }
1.71      ng       1994:     return $result;
1.58      albertel 1995: }
1.397     albertel 1996: 
1.396     banghart 1997: sub files_exist {
                   1998:     my ($r, $symb) = @_;
                   1999:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 2000: 
1.396     banghart 2001:     foreach my $student (@students) {
                   2002:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2003:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2004: 					      $udom,$uname);
1.396     banghart 2005:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2006:         foreach my $submission (@$string) {
                   2007:             my ($partid,$respid) =
                   2008: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2009:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2010: 					   \%record);
                   2011:             return 1 if (@$files);
1.396     banghart 2012:         }
                   2013:     }
1.397     albertel 2014:     return 0;
1.396     banghart 2015: }
1.397     albertel 2016: 
1.394     banghart 2017: sub download_all_link {
                   2018:     my ($r,$symb) = @_;
1.395     albertel 2019:     my $all_students = 
                   2020: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2021: 
                   2022:     my $parts =
                   2023: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2024: 
1.394     banghart 2025:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2026:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2027:                              'cgi.'.$identifier.'.symb' => $symb,
                   2028:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2029:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2030: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 2031:     return
                   2032: }
1.395     albertel 2033: 
1.432     banghart 2034: sub build_section_inputs {
                   2035:     my $section_inputs;
                   2036:     if ($env{'form.section'} eq '') {
                   2037:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2038:     } else {
                   2039:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2040:         foreach my $section (@sections) {
1.432     banghart 2041:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2042:         }
                   2043:     }
                   2044:     return $section_inputs;
                   2045: }
                   2046: 
1.44      ng       2047: # --------------------------- show submissions of a student, option to grade 
                   2048: sub submission {
                   2049:     my ($request,$counter,$total) = @_;
1.257     albertel 2050:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2051:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2052:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2053:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  (raeburn 2054:):     my ($symb) = &get_symb($request); 
1.324     albertel 2055:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2056: 
                   2057:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2058:4):         $request->print(
                   2059:4):             '<span class="LC_warning">'.
                   2060:4):             &mt('Unable to view requested student.').
                   2061:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2062:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2063:4):             '</span>');
1.324     albertel 2064: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2065: 	return;
                   2066:     }
                   2067: 
1.257     albertel 2068:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2069:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2070:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2071:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2072:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2073: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2074: 	'/check.gif" height="16" border="0" />';
1.41      ng       2075: 
                   2076:     # header info
                   2077:     if ($counter == 0) {
                   2078: 	&sub_page_js($request);
1.257     albertel 2079: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2080: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2081: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2082: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2083: 	    &download_all_link($request, $symb);
                   2084: 	}
1.485     albertel 2085: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1.596.2.12.2.  2(raebur 2086:3): 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2087: 
1.44      ng       2088: 	# option to display problem, only once else it cause problems 
                   2089:         # with the form later since the problem has a form.
1.257     albertel 2090: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2091: 	    my $mode;
1.257     albertel 2092: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2093: 		$mode='both';
1.257     albertel 2094: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2095: 		$mode='text';
1.257     albertel 2096: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2097: 		$mode='answer';
                   2098: 	    }
1.329     albertel 2099: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2100: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2101: 	}
1.441     www      2102: 
1.596.2.12.2.  0(raebur 2103:3): 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2104:         # if this subroutine has been called once.
1.41      ng       2105: 	my %keyhash = ();
1.257     albertel 2106: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2107: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2108: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2109: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2110: 
1.257     albertel 2111: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2112: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2113: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2114: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2115: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2116: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2117: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2118: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2119: 	}
1.257     albertel 2120: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2121: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2122: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2123: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2124: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2125: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2126: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2127: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2128: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2129: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2130: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2131: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2132: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2133: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2134: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2135: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2136: 			&build_section_inputs().
1.326     albertel 2137: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2138: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2139: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2140: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2141: 	if ($env{'form.handgrade'} eq 'yes') {
                   2142: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2143: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2144: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2145: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2146: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2147: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2148: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2149: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2150: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2151: 	    }
1.123     ng       2152: 	}
1.41      ng       2153: 	
                   2154: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2155: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2156: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2157: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2158: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2159: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2160: 		'" />'."\n".
                   2161: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2162: 	    $cts++;
                   2163: 	}
                   2164: 	$request->print($prnmsg);
1.32      ng       2165: 
1.257     albertel 2166: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2167: 
                   2168:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2169:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2170:                           keyw => 'Keyword Options',
                   2171:                           list => 'List',
                   2172:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2173:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2174:                      );
1.88      www      2175: #
                   2176: # Print out the keyword options line
                   2177: #
1.596.2.12.2.  8(raebur 2178:4):             $request->print(
                   2179:4):                 '<div class="LC_columnSection">'
                   2180:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2181:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2182:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2183:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2184:4):  class="page">'.$lt{'past'}.'</a>',
                   2185:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2186:4):                     {legend => $lt{'keyw'}})
                   2187:4):                .'</fieldset></div>'
                   2188:4):             );
                   2189:4): 
1.88      www      2190: #
                   2191: # Load the other essays for similarity check
                   2192: #
1.324     albertel 2193:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2194: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2195: 	    $apath=&escape($apath);
1.88      www      2196: 	    $apath=~s/\W/\_/gs;
1.596.2.12.2.  (raeburn 2197:):             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2198:         }
                   2199:     }
1.44      ng       2200: 
1.441     www      2201: # This is where output for one specific student would start
1.592     bisitz   2202:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2203:     $request->print(
                   2204:         "\n\n"
                   2205:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2206:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2207:        ."\n"
                   2208:     );
1.441     www      2209: 
1.592     bisitz   2210:     # Show additional functions if allowed
                   2211:     if ($perm{'vgr'}) {
                   2212:         $request->print(
                   2213:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2214:3):                 'View recent activity',
1.592     bisitz   2215:                 $uname,$udom,'check')
                   2216:            .' '
                   2217:         );
                   2218:     }
                   2219:     if ($perm{'opa'}) {
                   2220:         $request->print(
                   2221:             &Apache::loncommon::pprmlink(
                   2222:                 &mt('Set/Change parameters'),
                   2223:                 $uname,$udom,$symb,'check'));
                   2224:     }
                   2225: 
                   2226:     # Show Problem
1.257     albertel 2227:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2228: 	my $mode;
1.257     albertel 2229: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2230: 	    $mode='both';
1.257     albertel 2231: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2232: 	    $mode='text';
1.257     albertel 2233: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2234: 	    $mode='answer';
                   2235: 	}
1.329     albertel 2236: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2237: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2238:     }
1.144     albertel 2239: 
1.257     albertel 2240:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2241:     my $res_error;
                   2242:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2243:     if ($res_error) {
                   2244:         $request->print(&navmap_errormsg());
                   2245:         return;
                   2246:     }
1.41      ng       2247: 
1.44      ng       2248:     # Display student info
1.41      ng       2249:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2250: 
                   2251:     my $result='<div class="LC_Box">'
                   2252:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2253:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2254:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2255:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2256:         $result.='<p class="LC_info">'
                   2257:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2258:                 ."</p>\n";
1.469     albertel 2259:     }
                   2260: 
1.118     ng       2261:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2262:     my $fullname;
                   2263:     my $col_fullnames = [];
1.257     albertel 2264:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2265: 	(my $sub_result,$fullname,$col_fullnames)=
                   2266: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2267: 				 $counter);
                   2268: 	$result.=$sub_result;
1.41      ng       2269:     }
1.44      ng       2270:     $request->print($result."\n");
1.588     bisitz   2271: 
1.44      ng       2272:     # print student answer/submission
1.588     bisitz   2273:     # Options are (1) Handgraded submission only
1.44      ng       2274:     #             (2) Last submission, includes submission that is not handgraded 
                   2275:     #                  (for multi-response type part)
                   2276:     #             (3) Last submission plus the parts info
                   2277:     #             (4) The whole record for this student
1.596.2.12.2.  1(raebur 2278:3): 
1.151     albertel 2279: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2280: 	
                   2281: 	my $lastsubonly;
                   2282: 
1.588     bisitz   2283:         if ($$timestamp eq '') {
                   2284:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2285:         } else {
1.592     bisitz   2286:             $lastsubonly =
                   2287:                 '<div class="LC_grade_submissions_body">'
                   2288:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2289: 
1.151     albertel 2290: 	    my %seenparts;
1.375     albertel 2291: 	    my @part_response_id = &flatten_responseType($responseType);
                   2292: 	    foreach my $part (@part_response_id) {
1.393     albertel 2293: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2294: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2295: 
1.375     albertel 2296: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2297: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2298: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2299: 		    if (exists($seenparts{$partid})) { next; }
                   2300: 		    $seenparts{$partid}=1;
1.596.2.12.2.  8(raebur 2301:3):                     $request->print(
                   2302:3):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2303:3):                         ' <b>'.&mt('Collaborative submission by: [_1]',
                   2304:3):                                    '<a href="javascript:viewSubmitter(\''.
                   2305:3):                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2306:3):                                    '\');" target="_self">'.
                   2307:3):                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2308:3):                         '<br />');
1.151     albertel 2309: 		    next;
                   2310: 		}
                   2311: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2312: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2313:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2314:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2315:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2316:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2317:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2318: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2319: 		    next;
                   2320: 		}
1.468     albertel 2321: 		foreach my $submission (@$string) {
                   2322: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2323: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596.2.12.2.  0(raebur 2324:4): 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.151     albertel 2325: 		    # Similarity check
                   2326: 		    my $similar='';
1.596.2.2  raeburn  2327:                     my ($type,$trial,$rndseed);
                   2328:                     if ($hide eq 'rand') {
                   2329:                         $type = 'randomizetry';
                   2330:                         $trial = $record{"resource.$partid.tries"};
                   2331:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2332:                     }
1.596.2.12.2.  1(raebur 2333:3): 		    if ($env{'form.checkPlag'}) {
1.151     albertel 2334: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.596.2.12.2.  (raeburn 2335:): 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2336: 			if ($osim) {
                   2337: 			    $osim=int($osim*100.0);
1.426     albertel 2338: 			    my %old_course_desc = 
                   2339: 				&Apache::lonnet::coursedescription($ocrsid,
                   2340: 								   {'one_time' => 1});
                   2341: 
1.596.2.2  raeburn  2342:                             if ($hide eq 'anon') {
1.596     raeburn  2343:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2344:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2345:                             } else {
                   2346: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2347: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2348: 				        $osim,
                   2349: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2350: 				        $old_course_desc{'description'},
                   2351: 				        $old_course_desc{'num'},
                   2352: 				        $old_course_desc{'domain'}).
                   2353: 				    '</span></h3><blockquote><i>'.
                   2354: 				    &keywords_highlight($oessay).
                   2355: 				    '</i></blockquote><hr />';
                   2356:                             }
1.151     albertel 2357: 			}
1.150     albertel 2358: 		    }
1.596.2.2  raeburn  2359: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2360:                                          undef,$type,$trial,$rndseed);
1.596.2.12.2.  1(raebur 2361:3):                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
                   2362:3):                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2363: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2364:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2365:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2366:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2367:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2368:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2369: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2370: 			if (@$files) {
1.596.2.2  raeburn  2371:                             if ($hide eq 'anon') {
1.596     raeburn  2372:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2373:                             } else {
1.596.2.12.2.  8(raebur 2374:3):                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2375:3):                                             .'<br /><span class="LC_warning">';
                   2376:3):                                 if(@$files == 1) {
                   2377:3):                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2378:3):                                 } else {
                   2379:3):                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2380:3):                                 }
                   2381:3):                                 $lastsubonly .= '</span>';
                   2382:3): 
1.596     raeburn  2383:                                 foreach my $file (@$files) {
                   2384:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
1.596.2.12.2.  8(raebur 2385:3):                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2386:                                 }
                   2387:                             }
1.236     albertel 2388: 			    $lastsubonly.='<br />';
1.41      ng       2389: 			}
1.596.2.2  raeburn  2390:                         if ($hide eq 'anon') {
1.596.2.12.2.  8(raebur 2391:3):                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
1.596     raeburn  2392:                         } else {
1.596.2.12.2.  0(raebur 2393:4): 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2394:4):                             if ($draft) {
                   2395:4):                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2396:4):                             }
                   2397:4):                             $subval =
1.596     raeburn  2398: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2399: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596.2.12.2.  0(raebur 2400:4):                             if ($responsetype eq 'essay') {
                   2401:4):                                 $subval =~ s{\n}{<br />}g;
                   2402:4):                             }
                   2403:4):                             $lastsubonly.=$subval."\n";
1.596     raeburn  2404:                         }
1.151     albertel 2405: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2406: 			$lastsubonly.='</div>';
1.41      ng       2407: 		    }
                   2408: 		}
                   2409: 	    }
1.588     bisitz   2410: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2411: 	}
                   2412: 	$request->print($lastsubonly);
1.596.2.12.2.  1(raebur 2413:3):    if ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2414: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2415: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2416:3):     }
                   2417:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2418:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2419: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2420: 								 $env{'request.course.id'},
1.44      ng       2421: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2422:5): 								 'Apache::grades::keywords_highlight',
                   2423:5):                                                                  $usec,$identifier));
1.41      ng       2424:     }
1.120     ng       2425: 
1.121     ng       2426:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2427: 	.$udom.'" />'."\n");
1.44      ng       2428:     # return if view submission with no grading option
1.257     albertel 2429:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2430: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2431: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2432: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2433: 	$toGrade.='</div>'."\n";
1.257     albertel 2434: 	if (($env{'form.command'} eq 'submission') || 
                   2435: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2436: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2437: 	}
1.180     albertel 2438: 	$request->print($toGrade);
1.41      ng       2439: 	return;
1.180     albertel 2440:     } else {
1.468     albertel 2441: 	$request->print('</div>'."\n");
1.41      ng       2442:     }
1.33      ng       2443: 
1.121     ng       2444:     # essay grading message center
1.257     albertel 2445:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2446: 	my $result='<div class="LC_grade_message_center">';
                   2447:     
                   2448: 	$result.='<div class="LC_grade_message_center_header">'.
                   2449: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2450: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2451: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2452: 	if (scalar(@$col_fullnames) > 0) {
                   2453: 	    my $lastone = pop(@$col_fullnames);
                   2454: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2455: 	}
                   2456: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2457: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2458: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2459: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2460: 	    ',\''.$msgfor.'\');" target="_self">'.
1.596.2.12.2.  8(raebur 2461:3): 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2462: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.596.2.12.2.  8(raebur 2463:3): 	    ' <img src="'.$request->dir_config('lonIconsURL').
1.118     ng       2464: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2465: 	    '<br />&nbsp;('.
1.468     albertel 2466: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2467: 	$result.='</div></div>';
1.121     ng       2468: 	$request->print($result);
1.118     ng       2469:     }
1.41      ng       2470: 
                   2471:     my %seen = ();
                   2472:     my @partlist;
1.129     ng       2473:     my @gradePartRespid;
1.375     albertel 2474:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2475:     $request->print(
1.588     bisitz   2476:         '<div class="LC_Box">'
                   2477:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2478:     );
1.592     bisitz   2479:     $request->print(&gradeBox_start());
1.375     albertel 2480:     foreach my $part_response_id (@part_response_id) {
                   2481:     	my ($partid,$respid) = @{ $part_response_id };
                   2482: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2483: 	next if ($seen{$partid} > 0);
1.41      ng       2484: 	$seen{$partid}++;
1.393     albertel 2485: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2486: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2487: 	push(@partlist,$partid);
                   2488: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2489: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2490:     }
1.585     bisitz   2491:     $request->print(&gradeBox_end()); # </div>
                   2492:     $request->print('</div>');
1.468     albertel 2493: 
                   2494:     $request->print('<div class="LC_grade_info_links">');
                   2495:     $request->print('</div>');
                   2496: 
1.45      ng       2497:     $result='<input type="hidden" name="partlist'.$counter.
                   2498: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2499:     $result.='<input type="hidden" name="gradePartRespid'.
                   2500: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2501:     my $ctr = 0;
                   2502:     while ($ctr < scalar(@partlist)) {
                   2503: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2504: 	    $partlist[$ctr].'" />'."\n";
                   2505: 	$ctr++;
                   2506:     }
1.468     albertel 2507:     $request->print($result.''."\n");
1.41      ng       2508: 
1.441     www      2509: # Done with printing info for one student
                   2510: 
1.468     albertel 2511:     $request->print('</div>');#LC_grade_show_user
1.441     www      2512: 
                   2513: 
1.41      ng       2514:     # print end of form
                   2515:     if ($counter == $total) {
1.592     bisitz   2516:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2517: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2518: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2519: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2520: 	my $ntstu ='<select name="NTSTU">'.
                   2521: 	    '<option>1</option><option>2</option>'.
                   2522: 	    '<option>3</option><option>5</option>'.
                   2523: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2524: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2525: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2526:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2527: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2528: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2529: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2530: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2531:         $endform.='<span class="LC_warning">'.
                   2532:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2533:                   '</span>'."\n" ;
1.349     albertel 2534:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2535:             "' name='increment' />";
1.485     albertel 2536: 	$endform.='</td></tr></table></form>';
1.324     albertel 2537: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2538: 	$request->print($endform);
                   2539:     }
                   2540:     return '';
1.38      ng       2541: }
                   2542: 
1.464     albertel 2543: sub check_collaborators {
                   2544:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2545:     my ($result,@col_fullnames);
                   2546:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2547:     foreach my $part (keys(%$handgrade)) {
                   2548: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2549: 					'.maxcollaborators',
                   2550: 					$symb,$udom,$uname);
                   2551: 	next if ($ncol <= 0);
                   2552: 	$part =~ s/\_/\./g;
                   2553: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2554: 	my (@good_collaborators, @bad_collaborators);
                   2555: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2556: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2557: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2558: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2559: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2560: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2561: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2562: 	    # Doing this grep allows 'fuzzy' specification
                   2563: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2564: 			       keys(%$classlist));
                   2565: 	    if (! scalar(@matches)) {
                   2566: 		push(@bad_collaborators, $possible_collaborator);
                   2567: 	    } else {
                   2568: 		push(@good_collaborators, @matches);
                   2569: 	    }
                   2570: 	}
                   2571: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2572: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2573: 	    foreach my $name (@good_collaborators) {
                   2574: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2575: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2576: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2577: 	    }
1.596.2.4  raeburn  2578: 	    $result.='</ol><br />'."\n";
1.466     albertel 2579: 	    my ($part)=split(/\./,$part);
1.464     albertel 2580: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2581: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2582: 		"\n";
                   2583: 	}
                   2584: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2585: 	    $result.='<div class="LC_warning">';
1.464     albertel 2586: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2587: 	    $result .= '</div>';
                   2588: 	}         
                   2589: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2590: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2591: 	    $result .= &mt('This student has submitted too many '.
                   2592: 		'collaborators.  Maximum is [_1].',$ncol);
                   2593: 	    $result .= '</div>';
                   2594: 	}
                   2595:     }
                   2596:     return ($result,$fullname,\@col_fullnames);
                   2597: }
                   2598: 
1.44      ng       2599: #--- Retrieve the last submission for all the parts
1.38      ng       2600: sub get_last_submission {
1.119     ng       2601:     my ($returnhash)=@_;
1.596     raeburn  2602:     my (@string,$timestamp,%lasthidden);
1.119     ng       2603:     if ($$returnhash{'version'}) {
1.46      ng       2604: 	my %lasthash=();
                   2605: 	my ($version);
1.119     ng       2606: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2607: 	    foreach my $key (sort(split(/\:/,
                   2608: 					$$returnhash{$version.':keys'}))) {
                   2609: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2610: 		$timestamp = 
1.545     raeburn  2611: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2612: 	    }
                   2613: 	}
1.596.2.2  raeburn  2614:         my (%typeparts,%randombytry);
1.596     raeburn  2615:         my $showsurv = 
                   2616:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2617:         foreach my $key (sort(keys(%lasthash))) {
                   2618:             if ($key =~ /\.type$/) {
                   2619:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2620:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2621:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2622:                     my ($ign,@parts) = split(/\./,$key);
                   2623:                     pop(@parts);
1.596.2.3  raeburn  2624:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2625:                     if ($lasthash{$key} eq 'randomizetry') {
                   2626:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2627:                     } else {
                   2628:                         unless ($showsurv) {
                   2629:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2630:                         }
1.596     raeburn  2631:                     }
                   2632:                     delete($lasthash{$key});
                   2633:                 }
                   2634:             }
                   2635:         }
                   2636:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2637:         my @randomize = keys(%randombytry);
1.397     albertel 2638: 	foreach my $key (keys(%lasthash)) {
                   2639: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2640:             my $hide;
                   2641:             if (@hidden) {
                   2642:                 foreach my $id (@hidden) {
                   2643:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2644:                         $hide = 'anon';
1.596     raeburn  2645:                         last;
                   2646:                     }
                   2647:                 }
                   2648:             }
1.596.2.2  raeburn  2649:             unless ($hide) {
                   2650:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2651:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2652:                         if ($key =~ /^\Q$id\E/) {
                   2653:                             $hide = 'rand';
                   2654:                             last;
                   2655:                         }
                   2656:                     }
                   2657:                 }
                   2658:             }
1.397     albertel 2659: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  0(raebur 2660:4): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
                   2661:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2662:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2663:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2664: 	}
                   2665:     }
1.397     albertel 2666:     if (!@string) {
                   2667: 	$string[0] =
1.539     riegler  2668: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2669:     }
                   2670:     return (\@string,\$timestamp);
1.38      ng       2671: }
1.35      ng       2672: 
1.44      ng       2673: #--- High light keywords, with style choosen by user.
1.38      ng       2674: sub keywords_highlight {
1.44      ng       2675:     my $string    = shift;
1.257     albertel 2676:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2677:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2678:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2679:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2680:     foreach my $keyword (@keylist) {
                   2681: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2682:     }
                   2683:     return $string;
1.38      ng       2684: }
1.36      ng       2685: 
1.596.2.12.2.  (raeburn 2686:): # For Tasks provide a mechanism to display previous version for one specific student
                   2687:): 
                   2688:): sub show_previous_task_version {
                   2689:):     my ($request,$symb) = @_;
                   2690:):     if ($symb eq '') {
          8(raebur 2691:4):         $request->print(
                   2692:4):             '<span class="LC_error">'.
                   2693:4):             &mt('Unable to handle ambiguous references.').
                   2694:4):             '</span>');
          (raeburn 2695:):         return '';
                   2696:):     }
                   2697:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2698:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2699:):     if (!&canview($usec)) {
          8(raebur 2700:4):         $request->print('<span class="LC_warning">'.
                   2701:4):                         &mt('Unable to view previous version for requested student.').
                   2702:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2703:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2704:4):                         '</span>');
          (raeburn 2705:):         return;
                   2706:):     }
                   2707:):     my $mode = 'both';
                   2708:):     my $isTask = ($symb =~/\.task$/);
                   2709:):     if ($isTask) {
                   2710:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2711:):             if ($env{'form.fullname'} eq '') {
                   2712:):                 $env{'form.fullname'} =
                   2713:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2714:):             }
                   2715:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2716:):             $request->print("\n\n".
                   2717:):                             '<div class="LC_grade_show_user">'.
                   2718:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2719:):                             '</h2>'."\n");
                   2720:):             &Apache::lonxml::clear_problem_counter();
                   2721:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2722:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2723:):             $request->print("\n</div>");
                   2724:):         }
                   2725:):     }
                   2726:):     return;
                   2727:): }
                   2728:): 
                   2729:): sub choose_task_version_form {
                   2730:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2731:):     my $isTask = ($symb =~/\.task$/);
                   2732:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2733:):     if ($isTask) {
                   2734:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2735:):                                               $udom,$uname);
                   2736:):         if (($record{'resource.0.version'} eq '') ||
                   2737:):             ($record{'resource.0.version'} < 2)) {
                   2738:):             return ($record{'resource.0.version'},
                   2739:):                     $record{'resource.0.version'},$result,$js);
                   2740:):         } else {
                   2741:):             $current = $record{'resource.0.version'};
                   2742:):         }
                   2743:):         if ($env{'form.previousversion'}) {
                   2744:):             $displayed = $env{'form.previousversion'};
                   2745:):             $rowtitle = &mt('Choose another version:')
                   2746:):         } else {
                   2747:):             $displayed = $current;
                   2748:):             $rowtitle = &mt('Show earlier version:');
                   2749:):         }
                   2750:):         $result = '<div class="LC_left_float">';
                   2751:):         my $list;
                   2752:):         my $numversions = 0;
                   2753:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2754:):             if ($i == $current) {
                   2755:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   2756:):                     next;
                   2757:):                 } else {
                   2758:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2759:):                     $numversions ++;
                   2760:):                 }
                   2761:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2762:):                 unless ($i == $env{'form.previousversion'}) {
                   2763:):                     $numversions ++;
                   2764:):                 }
                   2765:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2766:):             }
                   2767:):         }
                   2768:):         if ($numversions) {
                   2769:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2770:):             $result .=
                   2771:):                 '<form name="getprev" method="post" action=""'.
                   2772:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2773:):                 &Apache::loncommon::start_data_table().
                   2774:):                 &Apache::loncommon::start_data_table_row().
                   2775:):                 '<th align="left">'.$rowtitle.'</th>'.
                   2776:):                 '<td><select name="version">'.
                   2777:):                 '<option>'.&mt('Select').'</option>'.
                   2778:):                 $list.
                   2779:):                 '</select></td>'.
                   2780:):                 &Apache::loncommon::end_data_table_row();
                   2781:):             unless ($nomenu) {
                   2782:):                 $result .= &Apache::loncommon::start_data_table_row().
                   2783:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2784:):                 '<td><span class="LC_nobreak">'.
                   2785:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2786:):                 &mt('Yes').'</label>'.
                   2787:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2788:):                 '</span></td>'.
                   2789:):                 &Apache::loncommon::end_data_table_row();
                   2790:):             }
                   2791:):             $result .=
                   2792:):                 &Apache::loncommon::start_data_table_row().
                   2793:):                 '<th align="left">&nbsp;</th>'.
                   2794:):                 '<td>'.
                   2795:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2796:):                 '</td>'.
                   2797:):                 &Apache::loncommon::end_data_table_row().
                   2798:):                 &Apache::loncommon::end_data_table().
                   2799:):                 '</form>';
                   2800:):             $js = &previous_display_javascript($nomenu,$current);
                   2801:):         } elsif ($displayed && $nomenu) {
                   2802:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2803:):         } else {
                   2804:):             $result .= &mt('No previous versions to show for this student');
                   2805:):         }
                   2806:):         $result .= '</div>';
                   2807:):     }
                   2808:):     return ($current,$displayed,$result,$js);
                   2809:): }
                   2810:): 
                   2811:): sub previous_display_javascript {
                   2812:):     my ($nomenu,$current) = @_;
                   2813:):     my $js = <<"JSONE";
                   2814:): <script type="text/javascript">
                   2815:): // <![CDATA[
                   2816:): function previousVersion(uname,udom,symb) {
                   2817:):     var current = '$current';
                   2818:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2819:):     var prevstr = new RegExp("^\\\\d+\$");
                   2820:):     if (!prevstr.test(version)) {
                   2821:):         return false;
                   2822:):     }
                   2823:):     var url = '';
                   2824:):     if (version == current) {
                   2825:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2826:):     } else {
                   2827:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2828:):     }
                   2829:): JSONE
                   2830:):     if ($nomenu) {
                   2831:):         $js .= <<"JSTWO";
                   2832:):     document.location.href = url;
                   2833:): JSTWO
                   2834:):     } else {
                   2835:):         $js .= <<"JSTHREE";
                   2836:):     var newwin = 0;
                   2837:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2838:):         if (document.getprev.prevwin[i].checked == true) {
                   2839:):             newwin = document.getprev.prevwin[i].value;
                   2840:):         }
                   2841:):     }
                   2842:):     if (newwin == 1) {
                   2843:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2844:):         url = url+'&inhibitmenu=yes';
                   2845:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2846:):             previousWin = window.open(url,'',options,1);
                   2847:):         } else {
                   2848:):             previousWin.location.href = url;
                   2849:):         }
                   2850:):         previousWin.focus();
                   2851:):         return false;
                   2852:):     } else {
                   2853:):         document.location.href = url;
                   2854:):         return false;
                   2855:):     }
                   2856:): JSTHREE
                   2857:):     }
                   2858:):     $js .= <<"ENDJS";
                   2859:):     return false;
                   2860:): }
                   2861:): // ]]>
                   2862:): </script>
                   2863:): ENDJS
                   2864:): 
                   2865:): }
                   2866:): 
1.44      ng       2867: #--- Called from submission routine
1.38      ng       2868: sub processHandGrade {
1.41      ng       2869:     my ($request) = shift;
1.596.2.12.2.  (raeburn 2870:):     my ($symb)   = &get_symb($request);
1.324     albertel 2871:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2872:     my $button = $env{'form.gradeOpt'};
                   2873:     my $ngrade = $env{'form.NCT'};
                   2874:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2875:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2876:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2877: 
1.44      ng       2878:     if ($button eq 'Save & Next') {
                   2879: 	my $ctr = 0;
                   2880: 	while ($ctr < $ngrade) {
1.257     albertel 2881: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 2882:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2883:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2884: 	    if ($errorflag eq 'no_score') {
                   2885: 		$ctr++;
                   2886: 		next;
                   2887: 	    }
1.104     albertel 2888: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 2889:4):                 $request->print(
                   2890:4):                     '<span class="LC_error">'
                   2891:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2892:4):                    .'</span>');
1.104     albertel 2893: 		$ctr++;
                   2894: 		next;
                   2895: 	    }
1.596.2.12.2.  1(raebur 2896:5):             if ($numhidden) {
                   2897:5):                 $request->print(
                   2898:5):                     '<span class="LC_info">'
                   2899:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2900:5):                    .'</span><br />');
                   2901:5):             }
1.257     albertel 2902: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2903: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2904: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2905:             my ($feedurl,$showsymb) =
                   2906: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2907: 	    my $messagetail;
1.62      albertel 2908: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2909: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2910: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2911: 		$subject.=' ['.$restitle.']';
1.44      ng       2912: 		my (@msgnum) = split(/,/,$includemsg);
                   2913: 		foreach (@msgnum) {
1.257     albertel 2914: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2915: 		}
1.80      ng       2916: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2917: 		if ($env{'form.withgrades'.$ctr}) {
                   2918: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2919: 		    $messagetail = " for <a href=\"".
1.418     albertel 2920: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2921: 		}
                   2922: 		$msgstatus = 
                   2923:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2924: 						     $message.$messagetail,
1.418     albertel 2925:                                                      undef,$feedurl,undef,
1.386     raeburn  2926:                                                      undef,undef,$showsymb,
                   2927:                                                      $restitle);
1.574     bisitz   2928: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2929: 				$msgstatus.'<br />');
1.44      ng       2930: 	    }
1.257     albertel 2931: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2932: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2933: 		foreach my $collabstr (@collabstrs) {
                   2934: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2935: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2936: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2937: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2938: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2939: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2940: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2941: 			    next;
1.418     albertel 2942: 			} elsif ($message ne '') {
                   2943: 			    my ($baseurl,$showsymb) = 
                   2944: 				&get_feedurl_and_symb($symb,$collaborator,
                   2945: 						      $udom);
                   2946: 			    if ($env{'form.withgrades'.$ctr}) {
                   2947: 				$messagetail = " for <a href=\"".
1.386     raeburn  2948:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2949: 			    }
1.418     albertel 2950: 			    $msgstatus = 
                   2951: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2952: 			}
1.44      ng       2953: 		    }
                   2954: 		}
                   2955: 	    }
                   2956: 	    $ctr++;
                   2957: 	}
                   2958:     }
                   2959: 
1.257     albertel 2960:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2961: 	# Keywords sorted in alphabatical order
1.257     albertel 2962: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2963: 	my %keyhash = ();
1.257     albertel 2964: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2965: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2966: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2967: 	$env{'form.keywords'} = join(' ',@keywords);
                   2968: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2969: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2970: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2971: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2972: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2973: 
                   2974: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2975: 	# New messages are saved in env for the next student.
1.119     ng       2976: 	# All messages are saved in nohist_handgrade.db
                   2977: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2978: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2979: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2980: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2981: 		$idx++;
                   2982: 	    }
                   2983: 	    $ctr++;
1.41      ng       2984: 	}
1.119     ng       2985: 	$ctr = 0;
                   2986: 	while ($ctr < $ngrade) {
1.257     albertel 2987: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2988: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2989: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2990: 		$idx++;
                   2991: 	    }
                   2992: 	    $ctr++;
1.41      ng       2993: 	}
1.257     albertel 2994: 	$env{'form.savemsgN'} = --$idx;
                   2995: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2996: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2997: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2998:     }
1.44      ng       2999:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3000:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3001:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3002: 	my ($ctr,$total) = (0,0);
                   3003: 	while ($ctr < $ngrade) {
1.257     albertel 3004: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3005: 	    $ctr++;
                   3006: 	}
1.257     albertel 3007: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3008: 	$ctr = 0;
                   3009: 	while ($ctr < $total) {
1.257     albertel 3010: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3011: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3012: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       3013: 	    &submission($request,$ctr,$total-1);
1.41      ng       3014: 	    $ctr++;
                   3015: 	}
                   3016: 	return '';
                   3017:     }
1.36      ng       3018: 
1.121     ng       3019: # Go directly to grade student - from submission or link from chart page
1.120     ng       3020:     if ($button eq 'Grade Student') {
1.324     albertel 3021: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 3022: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   3023: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3024: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       3025: 	&submission($request,0,0);
                   3026: 	return '';
                   3027:     }
                   3028: 
1.44      ng       3029:     # Get the next/previous one or group of students
1.257     albertel 3030:     my $firststu = $env{'form.unamedom0'};
                   3031:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3032:     my $ctr = 2;
1.41      ng       3033:     while ($laststu eq '') {
1.257     albertel 3034: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3035: 	$ctr++;
                   3036: 	$laststu = $firststu if ($ctr > $ngrade);
                   3037:     }
1.44      ng       3038: 
1.41      ng       3039:     my (@parsedlist,@nextlist);
                   3040:     my ($nextflg) = 0;
1.524     raeburn  3041:     foreach my $item (sort 
1.294     albertel 3042: 	     {
                   3043: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3044: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3045: 		 }
                   3046: 		 return $a cmp $b;
                   3047: 	     } (keys(%$fullname))) {
1.41      ng       3048: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3049: 	    push(@parsedlist,$item);
1.41      ng       3050: 	}
1.524     raeburn  3051: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3052: 	if ($button eq 'Previous') {
1.524     raeburn  3053: 	    last if ($item eq $firststu);
                   3054: 	    push(@parsedlist,$item);
1.41      ng       3055: 	}
                   3056:     }
                   3057:     $ctr = 0;
                   3058:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3059:     my $res_error;
                   3060:     my ($partlist) = &response_type($symb,\$res_error);
                   3061:     if ($res_error) {
                   3062:         $request->print(&navmap_errormsg());
                   3063:         return;
                   3064:     }
1.41      ng       3065:     foreach my $student (@parsedlist) {
1.257     albertel 3066: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3067: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3068: 	
                   3069: 	if ($submitonly eq 'queued') {
                   3070: 	    my %queue_status = 
                   3071: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3072: 							$udom,$uname);
                   3073: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3074: 	}
                   3075: 
1.156     albertel 3076: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3077: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3078: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3079: 	    my $submitted = 0;
1.248     albertel 3080: 	    my $ungraded = 0;
                   3081: 	    my $incorrect = 0;
1.524     raeburn  3082: 	    foreach my $item (keys(%status)) {
                   3083: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3084: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3085: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3086: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3087: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3088: 		    $submitted = 0;
                   3089: 		}
1.41      ng       3090: 	    }
1.156     albertel 3091: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3092: 				     $submitonly eq 'incorrect' ||
                   3093: 				     $submitonly eq 'graded'));
1.248     albertel 3094: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3095: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3096: 	}
1.524     raeburn  3097: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3098: 	last if ($ctr == $ntstu);
1.41      ng       3099: 	$ctr++;
                   3100:     }
1.36      ng       3101: 
1.41      ng       3102:     $ctr = 0;
                   3103:     my $total = scalar(@nextlist)-1;
1.39      ng       3104: 
1.524     raeburn  3105:     foreach (sort(@nextlist)) {
1.41      ng       3106: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3107: 	$env{'form.student'}  = $uname;
                   3108: 	$env{'form.userdom'}  = $udom;
                   3109: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       3110: 	&submission($request,$ctr,$total);
                   3111: 	$ctr++;
                   3112:     }
                   3113:     if ($total < 0) {
1.485     albertel 3114: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  3115: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 3116: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 3117: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       3118: 	$request->print($the_end);
                   3119:     }
                   3120:     return '';
1.38      ng       3121: }
1.36      ng       3122: 
1.44      ng       3123: #---- Save the score and award for each student, if changed
1.38      ng       3124: sub saveHandGrade {
1.324     albertel 3125:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3126:     my @version_parts;
1.104     albertel 3127:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3128: 					   $env{'request.course.id'});
1.104     albertel 3129:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3130:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3131:     my @parts_graded;
1.77      ng       3132:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3133:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3134:     my %aggregate = ();
                   3135:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3136:5):     if ($env{'form.HIDE'.$newflg}) {
                   3137:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3138:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3139:5):         $totchg += $numchgs;
                   3140:5):     }
1.301     albertel 3141:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3142:     foreach my $new_part (@parts) {
1.337     banghart 3143: 	#collaborator ($submi may vary for different parts
1.259     banghart 3144: 	if ($submitter && $new_part ne $part) { next; }
                   3145: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3146: 	if ($dropMenu eq 'excused') {
1.259     banghart 3147: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3148: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3149: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3150: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3151: 		}
1.364     banghart 3152: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3153: 	    }
1.125     ng       3154: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3155: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3156: 	    foreach my $key (keys(%record)) {
1.259     banghart 3157: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3158: 	    }
1.259     banghart 3159: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3160: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3161:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3162: 
                   3163:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3164: 					       [$new_part]);
                   3165:             my $aggtries =$totaltries;
1.269     raeburn  3166:             if ($last_resets{$new_part}) {
1.270     albertel 3167:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3168: 					   $new_part);
1.269     raeburn  3169:             }
1.270     albertel 3170: 
                   3171:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3172:             if ($aggtries > 0) {
1.327     albertel 3173:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3174:                 $aggregateflag = 1;
                   3175:             }
1.125     ng       3176: 	} elsif ($dropMenu eq '') {
1.259     banghart 3177: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3178: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3179: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3180: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3181: 		next;
                   3182: 	    }
1.259     banghart 3183: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3184: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3185: 	    my $partial= $pts/$wgt;
1.259     banghart 3186: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3187: 		#do not update score for part if not changed.
1.346     banghart 3188:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3189: 		next;
1.251     banghart 3190: 	    } else {
1.524     raeburn  3191: 	        push(@parts_graded,$new_part);
1.153     albertel 3192: 	    }
1.259     banghart 3193: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3194: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3195: 	    }
1.259     banghart 3196: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3197: 	    if ($partial == 0) {
1.153     albertel 3198: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3199: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3200: 		}
1.41      ng       3201: 	    } else {
1.153     albertel 3202: 		if ($record{$reckey} ne 'correct_by_override') {
                   3203: 		    $newrecord{$reckey} = 'correct_by_override';
                   3204: 		}
                   3205: 	    }	    
                   3206: 	    if ($submitter && 
1.259     banghart 3207: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3208: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3209: 	    }
1.259     banghart 3210: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3211: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3212: 	}
1.259     banghart 3213: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3214: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3215: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3216: 	        $dropMenu eq 'reset status')
                   3217: 	   {
1.524     raeburn  3218: 	    push(@version_parts,$new_part);
1.259     banghart 3219: 	}
1.41      ng       3220:     }
1.301     albertel 3221:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3222:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3223: 
1.344     albertel 3224:     if (%newrecord) {
                   3225:         if (@version_parts) {
1.364     banghart 3226:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3227:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3228: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3229: 	    foreach my $new_part (@version_parts) {
                   3230: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3231: 				$new_part,\%newrecord);
                   3232: 	    }
1.259     banghart 3233:         }
1.44      ng       3234: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3235: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3236: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3237: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3238:     }
1.269     raeburn  3239:     if ($aggregateflag) {
                   3240:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3241: 			      $cdom,$cnum);
1.269     raeburn  3242:     }
1.596.2.12.2.  1(raebur 3243:5):     return ('',$pts,$wgt,$totchg);
                   3244:5): }
                   3245:5): 
                   3246:5): sub makehidden {
                   3247:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3248:5):     return unless (ref($record) eq 'HASH');
                   3249:5):     my %modified;
                   3250:5):     my $numchanged = 0;
                   3251:5):     if (exists($record->{$version.':keys'})) {
                   3252:5):         my $partsregexp = $parts;
                   3253:5):         $partsregexp =~ s/,/|/g;
                   3254:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3255:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3256:5):                  my $item = $1;
                   3257:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3258:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3259:5):                  }
                   3260:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3261:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3262:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3263:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3264:5):             }
                   3265:5):         }
                   3266:5):         if (keys(%modified)) {
                   3267:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3268:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3269:5):                 $numchanged ++;
                   3270:5):             }
                   3271:5):         }
                   3272:5):     }
                   3273:5):     return $numchanged;
1.36      ng       3274: }
1.322     albertel 3275: 
1.380     albertel 3276: sub check_and_remove_from_queue {
                   3277:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3278:     my @ungraded_parts;
                   3279:     foreach my $part (@{$parts}) {
                   3280: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3281: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3282: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3283: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3284: 		) {
                   3285: 	    push(@ungraded_parts, $part);
                   3286: 	}
                   3287:     }
                   3288:     if ( !@ungraded_parts ) {
                   3289: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3290: 					       $cnum,$domain,$stuname);
                   3291:     }
                   3292: }
                   3293: 
1.337     banghart 3294: sub handback_files {
                   3295:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3296:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3297:     my $res_error;
                   3298:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3299:     if ($res_error) {
                   3300:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3301:         return;
                   3302:     }
1.596.2.4  raeburn  3303:     my @handedback;
                   3304:     my $file_msg;
1.375     albertel 3305:     my @part_response_id = &flatten_responseType($responseType);
                   3306:     foreach my $part_response_id (@part_response_id) {
                   3307:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3308: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3309:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3310:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3311:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3312: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3313:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3314:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3315:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3316:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3317: 		        &file_name_version_ext($answer_file);
1.355     banghart 3318: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3319:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3320:):                     my ($dir_list,$listerror) =
                   3321:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3322:):                                                  $domain,$stuname,$getpropath);
                   3323:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3324:3):                     # fix filename
1.355     banghart 3325:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3326:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3327:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3328:             	                                $save_file_name);
1.337     banghart 3329:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3330:                         $request->print('<br /><span class="LC_error">'.
                   3331:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3332:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3333:                                         '</span>');
1.356     banghart 3334:                     } else {
1.360     banghart 3335:                         # mark the file as read only
1.596.2.4  raeburn  3336:                         push(@handedback,$save_file_name);
1.367     albertel 3337: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3338: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3339: 			}
                   3340:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3341: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3342: 
1.337     banghart 3343:                     }
1.596.2.12.2.  3(raebur 3344: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 3345:                 }
                   3346:             }
                   3347:         }
1.596.2.4  raeburn  3348:     }
                   3349:     if (@handedback > 0) {
                   3350:         $request->print('<br />');
                   3351:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3352:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3353:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3354:         my ($subject,$message);
                   3355:         if (scalar(@handedback) == 1) {
                   3356:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3357:         } else {
                   3358:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3359:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3360:         }
                   3361:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3362:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3363:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3364:         my ($feedurl,$showsymb) =
                   3365:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3366:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3367:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3368:         my $msgstatus =
                   3369:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3370:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3371:                  $restitle);
                   3372:         if ($msgstatus) {
                   3373:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3374:         }
                   3375:     }
1.338     banghart 3376:     return;
1.337     banghart 3377: }
                   3378: 
1.418     albertel 3379: sub get_feedurl_and_symb {
                   3380:     my ($symb,$uname,$udom) = @_;
                   3381:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3382:     $url = &Apache::lonnet::clutter($url);
                   3383:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3384: 					$symb,$udom,$uname);
                   3385:     if ($encrypturl =~ /^yes$/i) {
                   3386: 	&Apache::lonenc::encrypted(\$url,1);
                   3387: 	&Apache::lonenc::encrypted(\$symb,1);
                   3388:     }
                   3389:     return ($url,$symb);
                   3390: }
                   3391: 
1.313     banghart 3392: sub get_submitted_files {
                   3393:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3394:     my @files;
                   3395:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3396:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3397:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3398:     	    push(@files,$file_url.$file);
                   3399:         }
                   3400:     }
                   3401:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3402:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3403:     }
                   3404:     return (\@files);
                   3405: }
1.322     albertel 3406: 
1.269     raeburn  3407: # ----------- Provides number of tries since last reset.
                   3408: sub get_num_tries {
                   3409:     my ($record,$last_reset,$part) = @_;
                   3410:     my $timestamp = '';
                   3411:     my $num_tries = 0;
                   3412:     if ($$record{'version'}) {
                   3413:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3414:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3415:                 $timestamp = $$record{$version.':timestamp'};
                   3416:                 if ($timestamp > $last_reset) {
                   3417:                     $num_tries ++;
                   3418:                 } else {
                   3419:                     last;
                   3420:                 }
                   3421:             }
                   3422:         }
                   3423:     }
                   3424:     return $num_tries;
                   3425: }
                   3426: 
                   3427: # ----------- Determine decrements required in aggregate totals 
                   3428: sub decrement_aggs {
                   3429:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3430:     my %decrement = (
                   3431:                         attempts => 0,
                   3432:                         users => 0,
                   3433:                         correct => 0
                   3434:                     );
                   3435:     $decrement{'attempts'} = $aggtries;
                   3436:     if ($solvedstatus =~ /^correct/) {
                   3437:         $decrement{'correct'} = 1;
                   3438:     }
                   3439:     if ($aggtries == $totaltries) {
                   3440:         $decrement{'users'} = 1;
                   3441:     }
1.524     raeburn  3442:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3443:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3444:     }
                   3445:     return;
                   3446: }
                   3447: 
                   3448: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3449: sub get_last_resets {
1.270     albertel 3450:     my ($symb,$courseid,$partids) =@_;
                   3451:     my %last_resets;
1.269     raeburn  3452:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3453:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3454:     my @keys;
                   3455:     foreach my $part (@{$partids}) {
                   3456: 	push(@keys,"$symb\0$part\0resettime");
                   3457:     }
                   3458:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3459: 				     $cdom,$cname);
                   3460:     foreach my $part (@{$partids}) {
                   3461: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3462:     }
1.270     albertel 3463:     return %last_resets;
1.269     raeburn  3464: }
                   3465: 
1.251     banghart 3466: # ----------- Handles creating versions for portfolio files as answers
                   3467: sub version_portfiles {
1.343     banghart 3468:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3469:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3470:     my @returned_keys;
1.255     banghart 3471:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3472:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3473:     foreach my $key (keys(%$record)) {
1.259     banghart 3474:         my $new_portfiles;
1.263     banghart 3475:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3476:             my @versioned_portfiles;
1.367     albertel 3477:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3478:             foreach my $file (@portfiles) {
1.306     banghart 3479:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3480:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3481: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3482: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3483:):                 my $getpropath = 1;
                   3484:):                 my ($dir_list,$listerror) =
                   3485:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3486:):                                              $stu_name,$getpropath);
                   3487:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3488:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3489:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3490:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3491:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3492:                         [$directory.$new_answer],
1.306     banghart 3493:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3494:                 }
1.252     banghart 3495:             }
1.343     banghart 3496:             $$record{$key} = join(',',@versioned_portfiles);
                   3497:             push(@returned_keys,$key);
1.251     banghart 3498:         }
                   3499:     } 
1.343     banghart 3500:     return (@returned_keys);   
1.305     banghart 3501: }
                   3502: 
1.307     banghart 3503: sub get_next_version {
1.341     banghart 3504:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3505:     my $version;
1.596.2.12.2.  (raeburn 3506:):     if (ref($dir_list) eq 'ARRAY') {
                   3507:):         foreach my $row (@{$dir_list}) {
                   3508:):             my ($file) = split(/\&/,$row,2);
                   3509:):             my ($file_name,$file_version,$file_ext) =
                   3510:): 	        &file_name_version_ext($file);
                   3511:):             if (($file_name eq $answer_name) && 
                   3512:): 	        ($file_ext eq $answer_ext)) {
                   3513:):                 # gets here if filename and extension match, 
                   3514:):                 # regardless of version
1.307     banghart 3515:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3516:):                     # a versioned file is found  so save it for later
                   3517:):                     if ($file_version > $version) {
                   3518:): 		        $version = $file_version;
                   3519:):                     }
1.307     banghart 3520: 	        }
                   3521:             }
                   3522:         }
1.596.2.12.2.  (raeburn 3523:):     }
1.307     banghart 3524:     $version ++;
                   3525:     return($version);
                   3526: }
                   3527: 
1.305     banghart 3528: sub version_selected_portfile {
1.306     banghart 3529:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3530:     my ($answer_name,$answer_ver,$answer_ext) =
                   3531:         &file_name_version_ext($file_name);
                   3532:     my $new_answer;
                   3533:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3534:     if($env{'form.copy'} eq '-1') {
                   3535:         $new_answer = 'problem getting file';
                   3536:     } else {
                   3537:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3538:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3539:                             $stu_name,$domain,'copy',
                   3540: 		        '/portfolio'.$directory.$new_answer);
                   3541:     }    
                   3542:     return ($new_answer);
1.251     banghart 3543: }
                   3544: 
1.304     albertel 3545: sub file_name_version_ext {
                   3546:     my ($file)=@_;
                   3547:     my @file_parts = split(/\./, $file);
                   3548:     my ($name,$version,$ext);
                   3549:     if (@file_parts > 1) {
                   3550: 	$ext=pop(@file_parts);
                   3551: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3552: 	    $version=pop(@file_parts);
                   3553: 	}
                   3554: 	$name=join('.',@file_parts);
                   3555:     } else {
                   3556: 	$name=join('.',@file_parts);
                   3557:     }
                   3558:     return($name,$version,$ext);
                   3559: }
                   3560: 
1.44      ng       3561: #--------------------------------------------------------------------------------------
                   3562: #
                   3563: #-------------------------- Next few routines handles grading by section or whole class
                   3564: #
                   3565: #--- Javascript to handle grading by section or whole class
1.42      ng       3566: sub viewgrades_js {
                   3567:     my ($request) = shift;
                   3568: 
1.539     riegler  3569:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3570:6):     &js_escape(\$alertmsg);
1.41      ng       3571:     $request->print(<<VIEWJAVASCRIPT);
                   3572: <script type="text/javascript" language="javascript">
1.45      ng       3573:    function writePoint(partid,weight,point) {
1.125     ng       3574: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3575: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3576: 	if (point == "textval") {
1.125     ng       3577: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3578: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3579: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3580: 		var resetbox = false;
                   3581: 		for (var i=0; i<radioButton.length; i++) {
                   3582: 		    if (radioButton[i].checked) {
                   3583: 			textbox.value = i;
                   3584: 			resetbox = true;
                   3585: 		    }
                   3586: 		}
                   3587: 		if (!resetbox) {
                   3588: 		    textbox.value = "";
                   3589: 		}
                   3590: 		return;
                   3591: 	    }
1.109     matthew  3592: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3593: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3594: 				   ") greater than the weight for the part. Accept?");
                   3595: 		if (resp == false) {
                   3596: 		    textbox.value = "";
                   3597: 		    return;
                   3598: 		}
                   3599: 	    }
1.42      ng       3600: 	    for (var i=0; i<radioButton.length; i++) {
                   3601: 		radioButton[i].checked=false;
1.109     matthew  3602: 		if (parseFloat(point) == i) {
1.42      ng       3603: 		    radioButton[i].checked=true;
                   3604: 		}
                   3605: 	    }
1.41      ng       3606: 
1.42      ng       3607: 	} else {
1.125     ng       3608: 	    textbox.value = parseFloat(point);
1.42      ng       3609: 	}
1.41      ng       3610: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3611: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3612: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3613: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3614: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3615: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3616: 	    if (saveval != "correct") {
                   3617: 		scorename.value = point;
1.43      ng       3618: 		if (selname[0].selected != true) {
                   3619: 		    selname[0].selected = true;
                   3620: 		}
1.42      ng       3621: 	    }
                   3622: 	}
1.125     ng       3623: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3624:     }
                   3625: 
                   3626:     function writeRadText(partid,weight) {
1.125     ng       3627: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3628: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3629:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3630: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3631: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3632: 	    for (var i=0; i<radioButton.length; i++) {
                   3633: 		radioButton[i].checked=false;
                   3634: 
                   3635: 	    }
                   3636: 	    textbox.value = "";
                   3637: 
                   3638: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3639: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3640: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3641: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3642: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3643: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3644: 		if ((saveval != "correct") || override) {
1.42      ng       3645: 		    scorename.value = "";
1.125     ng       3646: 		    if (selval[1].selected) {
                   3647: 			selname[1].selected = true;
                   3648: 		    } else {
                   3649: 			selname[2].selected = true;
                   3650: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3651: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3652: 		    }
1.42      ng       3653: 		}
                   3654: 	    }
1.43      ng       3655: 	} else {
                   3656: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3657: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3658: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3659: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3660: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3661: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3662: 		if ((saveval != "correct") || override) {
1.125     ng       3663: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3664: 		    selname[0].selected = true;
                   3665: 		}
                   3666: 	    }
                   3667: 	}	    
1.42      ng       3668:     }
                   3669: 
                   3670:     function changeSelect(partid,user) {
1.125     ng       3671: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3672: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3673: 	var point  = textbox.value;
1.125     ng       3674: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3675: 
1.109     matthew  3676: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3677: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3678: 	    textbox.value = "";
                   3679: 	    return;
                   3680: 	}
1.109     matthew  3681: 	if (parseFloat(point) > parseFloat(weight)) {
                   3682: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3683: 			       ") greater than the weight of the part. Accept?");
                   3684: 	    if (resp == false) {
                   3685: 		textbox.value = "";
                   3686: 		return;
                   3687: 	    }
                   3688: 	}
1.42      ng       3689: 	selval[0].selected = true;
                   3690:     }
                   3691: 
                   3692:     function changeOneScore(partid,user) {
1.125     ng       3693: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3694: 	if (selval[1].selected || selval[2].selected) {
                   3695: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3696: 	    if (selval[2].selected) {
                   3697: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3698: 	    }
1.269     raeburn  3699:         }
1.42      ng       3700:     }
                   3701: 
                   3702:     function resetEntry(numpart) {
                   3703: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3704: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3705: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3706: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3707: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3708: 	    for (var i=0; i<radioButton.length; i++) {
                   3709: 		radioButton[i].checked=false;
                   3710: 
                   3711: 	    }
                   3712: 	    textbox.value = "";
                   3713: 	    selval[0].selected = true;
                   3714: 
                   3715: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3716: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3717: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3718: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3719: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3720: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3721: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3722: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3723: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3724: 		if (saveselval == "excused") {
1.43      ng       3725: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3726: 		} else {
1.43      ng       3727: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3728: 		}
                   3729: 	    }
1.41      ng       3730: 	}
1.42      ng       3731:     }
                   3732: 
1.41      ng       3733: </script>
                   3734: VIEWJAVASCRIPT
1.42      ng       3735: }
                   3736: 
1.44      ng       3737: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3738: sub viewgrades {
                   3739:     my ($request) = shift;
                   3740:     &viewgrades_js($request);
1.41      ng       3741: 
1.324     albertel 3742:     my ($symb) = &get_symb($request);
1.168     albertel 3743:     #need to make sure we have the correct data for later EXT calls, 
                   3744:     #thus invalidate the cache
                   3745:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3746:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3747:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3748:     &Apache::lonnet::clear_EXT_cache_status();
                   3749: 
1.398     albertel 3750:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.596.2.12.2.  9(raebur 3751:3):     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3752: 
                   3753:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3754:     $result.=&jscriptNform($symb);
1.41      ng       3755: 
1.44      ng       3756:     #beginning of class grading form
1.442     banghart 3757:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3758:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3759: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3760: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3761: 	&build_section_inputs().
1.257     albertel 3762: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3763: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3764: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3765: 
1.596.2.12.2.  7(raebur 3766:6):     #retrieve selected groups
                   3767:6):     my (@groups,$group_display);
          8(raebur 3768:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 3769:6):     if (grep(/^all$/,@groups)) {
                   3770:6):         @groups = ('all');
                   3771:6):     } elsif (grep(/^none$/,@groups)) {
                   3772:6):         @groups = ('none');
                   3773:6):     } elsif (@groups > 0) {
                   3774:6):         $group_display = join(', ',@groups);
                   3775:6):     }
                   3776:6): 
                   3777:6):     my ($common_header,$specific_header,@sections,$section_display);
                   3778:6):     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3779:6):     if (grep(/^all$/,@sections)) {
                   3780:6):         @sections = ('all');
                   3781:6):         if ($group_display) {
                   3782:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3783:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3784:6):         } elsif (grep(/^none$/,@groups)) {
                   3785:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3786:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3787:6):         } else {
                   3788:6):             $common_header = &mt('Assign Common Grade to Class');
                   3789:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3790:6):         }
                   3791:6):     } elsif (grep(/^none$/,@sections)) {
                   3792:6):         @sections = ('none');
                   3793:6):         if ($group_display) {
                   3794:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3795:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3796:6):         } elsif (grep(/^none$/,@groups)) {
                   3797:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3798:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3799:6):         } else {
                   3800:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3801:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3802:6):         }
                   3803:6):     } else {
                   3804:6):         $section_display = join (", ",@sections);
                   3805:6):         if ($group_display) {
                   3806:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3807:6):                                  $section_display,$group_display);
                   3808:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3809:6):                                    $section_display,$group_display);
                   3810:6):         } elsif (grep(/^none$/,@groups)) {
                   3811:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3812:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3813:6):         } else {
                   3814:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3815:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3816:6):         }
1.52      albertel 3817:     }
1.596.2.12.2.  7(raebur 3818:6):     my %submit_types = &substatus_options();
                   3819:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3820:6): 
                   3821:6):     if ($env{'form.submitonly'} eq 'all') {
                   3822:6):         $result.= '<h3>'.$common_header.'</h3>';
                   3823:6):     } else {
                   3824:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   3825:6):     }
                   3826:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3827:     #radio buttons/text box for assigning points for a section or class.
                   3828:     #handles different parts of a problem
1.582     raeburn  3829:     my $res_error;
                   3830:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3831:     if ($res_error) {
                   3832:         return &navmap_errormsg();
                   3833:     }
1.42      ng       3834:     my %weight = ();
                   3835:     my $ctsparts = 0;
1.45      ng       3836:     my %seen = ();
1.375     albertel 3837:     my @part_response_id = &flatten_responseType($responseType);
                   3838:     foreach my $part_response_id (@part_response_id) {
                   3839:     	my ($partid,$respid) = @{ $part_response_id };
                   3840: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3841: 	next if $seen{$partid};
                   3842: 	$seen{$partid}++;
1.375     albertel 3843: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3844: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3845: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3846: 
1.324     albertel 3847: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3848: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3849: 	my $ctr = 0;
1.42      ng       3850: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3851: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3852: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3853: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3854: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3855: 	    $ctr++;
                   3856: 	}
1.485     albertel 3857: 	$radio.='</tr></table>';
                   3858: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3859: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3860: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3861: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 3862:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3863:3):                 '<select name="SELVAL_'.$partid.'" '.
                   3864:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3865: 		$weight{$partid}.')"> '.
1.401     albertel 3866: 	    '<option selected="selected"> </option>'.
1.485     albertel 3867: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3868: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3869: 	    '</select></td>'.
                   3870:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3871: 	$line.='<input type="hidden" name="partid_'.
                   3872: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3873: 	$line.='<input type="hidden" name="weight_'.
                   3874: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3875: 
                   3876: 	$result.=
                   3877: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3878: 	    '<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 3879: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3880: 	$ctsparts++;
1.41      ng       3881:     }
1.474     albertel 3882:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3883: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3884:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3885: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3886: 
1.44      ng       3887:     #table listing all the students in a section/class
                   3888:     #header of table
1.596.2.12.2.  7(raebur 3889:6):     if ($env{'form.submitonly'} eq 'all') { 
                   3890:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   3891:6):     } else {
                   3892:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   3893:6):     }
                   3894:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3895: 	      &Apache::loncommon::start_data_table_header_row().
                   3896: 	      '<th>'.&mt('No.').'</th>'.
                   3897: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3898:     my $partserror;
                   3899:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3900:     if ($partserror) {
                   3901:         return &navmap_errormsg();
                   3902:     }
1.324     albertel 3903:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3904:     my @partids = ();
1.41      ng       3905:     foreach my $part (@parts) {
                   3906: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3907:         my $narrowtext = &mt('Tries');
                   3908: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3909: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3910: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3911:         push(@partids,$partid);
1.324     albertel 3912: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3913: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3914: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 3915:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   3916:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3917: 	    next;
1.485     albertel 3918: 	    
1.207     albertel 3919: 	} else {
1.485     albertel 3920: 	    if ($display =~ /Problem Status/) {
                   3921: 		my $grade_status_mt = &mt('Grade Status');
                   3922: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3923: 	    }
                   3924: 	    my $part_mt = &mt('Part:');
                   3925: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3926: 	}
1.485     albertel 3927: 
1.474     albertel 3928: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3929:     }
1.474     albertel 3930:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3931: 
1.270     albertel 3932:     my %last_resets = 
                   3933: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3934: 
1.41      ng       3935:     #get info for each student
1.44      ng       3936:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 3937:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3938:     my $ctr = 0;
1.294     albertel 3939:     foreach (sort 
                   3940: 	     {
                   3941: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3942: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3943: 		 }
                   3944: 		 return $a cmp $b;
                   3945: 	     } (keys(%$fullname))) {
1.324     albertel 3946: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 3947:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       3948:     }
1.474     albertel 3949:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3950:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3951:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3952: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 3953:6):     if ($ctr == 0) {
1.442     banghart 3954:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 3955:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3956:6):                 '<span class="LC_warning">';
                   3957:6):         if ($env{'form.submitonly'} eq 'all') {
                   3958:6):             if (grep(/^all$/,@sections)) {
                   3959:6):                 if (grep(/^all$/,@groups)) {
                   3960:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3961:6):                                    $stu_status);
                   3962:6):                 } elsif (grep(/^none$/,@groups)) {
                   3963:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3964:6):                                    $stu_status);
                   3965:6):                 } else {
                   3966:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3967:6):                                    $group_display,$stu_status);
                   3968:6):                 }
                   3969:6):             } elsif (grep(/^none$/,@sections)) {
                   3970:6):                 if (grep(/^all$/,@groups)) {
                   3971:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3972:6):                                    $stu_status);
                   3973:6):                 } elsif (grep(/^none$/,@groups)) {
                   3974:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3975:6):                                    $stu_status);
                   3976:6):                 } else {
                   3977:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3978:6):                                    $group_display,$stu_status);
                   3979:6):                 }
                   3980:6):             } else {
                   3981:6):                 if (grep(/^all$/,@groups)) {
                   3982:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3983:6):                                    $section_display,$stu_status);
                   3984:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 3985:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 3986:6):                                    $section_display,$stu_status);
                   3987:6):                 } else {
                   3988:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3989:6):                                    $section_display,$group_display,$stu_status);
                   3990:6):                 }
                   3991:6):             }
                   3992:6):         } else {
                   3993:6):             if (grep(/^all$/,@sections)) {
                   3994:6):                 if (grep(/^all$/,@groups)) {
                   3995:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3996:6):                                    $stu_status,$submission_status);
                   3997:6):                 } elsif (grep(/^none$/,@groups)) {
                   3998:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3999:6):                                    $stu_status,$submission_status);
                   4000:6):                 } else {
                   4001:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4002:6):                                    $group_display,$stu_status,$submission_status);
                   4003:6):                 }
                   4004:6):             } elsif (grep(/^none$/,@sections)) {
                   4005:6):                 if (grep(/^all$/,@groups)) {
                   4006:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4007:6):                                    $stu_status,$submission_status);
                   4008:6):                 } elsif (grep(/^none$/,@groups)) {
                   4009: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.',
                   4010:6):                                    $stu_status,$submission_status);
                   4011:6):                 } else {
                   4012: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.',
                   4013:6):                                    $group_display,$stu_status,$submission_status);
                   4014:6):                 }
                   4015:6):             } else {
                   4016:6):                 if (grep(/^all$/,@groups)) {
                   4017:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4018:6):                                    $section_display,$stu_status,$submission_status);
                   4019:6):                 } elsif (grep(/^none$/,@groups)) {
                   4020: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.',
                   4021:6):                                    $section_display,$stu_status,$submission_status);
                   4022:6):                 } else {
                   4023: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.',
                   4024:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4025:6):                 }
                   4026:6):             }
                   4027:6): 	}
                   4028:6): 	$result .= '</span><br />';
1.96      albertel 4029:     }
1.324     albertel 4030:     $result.=&show_grading_menu_form($symb);
1.41      ng       4031:     return $result;
                   4032: }
                   4033: 
1.596.2.12.2.  7(raebur 4034:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4035: sub viewstudentgrade {
1.324     albertel 4036:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4037:     my ($uname,$udom) = split(/:/,$student);
                   4038:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4039:6):     my $submitonly = $env{'form.submitonly'};
                   4040:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4041:6):         my %partstatus = ();
                   4042:6):         if (ref($parts) eq 'ARRAY') {
                   4043:6):             foreach my $apart (@{$parts}) {
                   4044:6):                 my ($part,$type) = &split_part_type($apart);
                   4045:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4046:6):                 $status = 'nothing' if ($status eq '');
                   4047:6):                 $partstatus{$part}      = $status;
                   4048:6):                 my $subkey = "resource.$part.submitted_by";
                   4049:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4050:6):             }
                   4051:6):             my $submitted = 0;
                   4052:6):             my $graded = 0;
                   4053:6):             my $incorrect = 0;
                   4054:6):             foreach my $key (keys(%partstatus)) {
                   4055:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4056:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4057:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4058:6): 
                   4059:6):                 my $partid = (split(/\./,$key))[1];
                   4060:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4061:6):                     $submitted = 0;
                   4062:6):                 }
                   4063:6):             }
                   4064:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4065:6):                                        $submitonly eq 'incorrect' ||
                   4066:6):                                        $submitonly eq 'graded'));
                   4067:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4068:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4069:6):         }
                   4070:6):     }
                   4071:6):     if ($submitonly eq 'queued') {
                   4072:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4073:6):         my %queue_status =
                   4074:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4075:6):                                                     $udom,$uname);
                   4076:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4077:6):     }
                   4078:6):     $$ctr++;
                   4079:6):     my %aggregates = ();
1.474     albertel 4080:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4081:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4082:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4083: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4084: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4085: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4086:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4087:     foreach my $apart (@$parts) {
                   4088: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4089: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4090:         $result.='<td align="center">';
1.269     raeburn  4091:         my ($aggtries,$totaltries);
                   4092:         unless (exists($aggregates{$part})) {
1.270     albertel 4093: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4094: 
                   4095: 	    $aggtries = $totaltries;
1.269     raeburn  4096:             if ($$last_resets{$part}) {  
1.270     albertel 4097:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4098: 					   $part);
                   4099:             }
1.269     raeburn  4100:             $result.='<input type="hidden" name="'.
                   4101:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4102:             $result.='<input type="hidden" name="'.
                   4103:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4104:             $aggregates{$part} = 1;
                   4105:         }
1.41      ng       4106: 	if ($type eq 'awarded') {
1.320     albertel 4107: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4108: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4109: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4110: 	    $result.='<input type="text" name="'.
1.89      albertel 4111: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4112:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4113: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4114: 	} elsif ($type eq 'solved') {
                   4115: 	    my ($status,$foo)=split(/_/,$score,2);
                   4116: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4117: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4118: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4119: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4120: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4121:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4122: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4123: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4124: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4125: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4126: 	} else {
                   4127: 	    $result.='<input type="hidden" name="'.
                   4128: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4129: 		    "\n";
1.233     albertel 4130: 	    $result.='<input type="text" name="'.
1.122     ng       4131: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4132: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4133: 	}
                   4134:     }
1.474     albertel 4135:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4136:     return $result;
1.38      ng       4137: }
                   4138: 
1.44      ng       4139: #--- change scores for all the students in a section/class
                   4140: #    record does not get update if unchanged
1.38      ng       4141: sub editgrades {
1.41      ng       4142:     my ($request) = @_;
                   4143: 
1.596.2.12.2.  (raeburn 4144:):     my ($symb)=&get_symb($request);
1.433     banghart 4145:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4146:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4147:3):     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
                   4148:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4149: 
1.477     albertel 4150:     my $result= &Apache::loncommon::start_data_table().
                   4151: 	&Apache::loncommon::start_data_table_header_row().
                   4152: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4153: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4154:     my %scoreptr = (
                   4155: 		    'correct'  =>'correct_by_override',
                   4156: 		    'incorrect'=>'incorrect_by_override',
                   4157: 		    'excused'  =>'excused',
                   4158: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4159:                     'credited' =>'credit_attempted',
1.43      ng       4160: 		    'nothing'  => '',
                   4161: 		    );
1.257     albertel 4162:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4163: 
1.44      ng       4164:     my (@partid);
                   4165:     my %weight = ();
1.54      albertel 4166:     my %columns = ();
1.44      ng       4167:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4168: 
1.582     raeburn  4169:     my $partserror;
                   4170:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4171:     if ($partserror) {
                   4172:         return &navmap_errormsg();
                   4173:     }
1.54      albertel 4174:     my $header;
1.257     albertel 4175:     while ($ctr < $env{'form.totalparts'}) {
                   4176: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4177: 	push(@partid,$partid);
1.257     albertel 4178: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4179: 	$ctr++;
1.54      albertel 4180:     }
1.324     albertel 4181:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  1.2.2(ra 4182:pr-18):     my $totcolspan = 0;
1.54      albertel 4183:     foreach my $partid (@partid) {
1.478     albertel 4184: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4185: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4186: 	$columns{$partid}=2;
                   4187: 	foreach my $stores (@parts) {
                   4188: 	    my ($part,$type) = &split_part_type($stores);
                   4189: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4190: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4191: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4192: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4193:             my $narrowtext = &mt('Tries');
                   4194: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4195: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4196: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4197: 	    $columns{$partid}+=2;
                   4198: 	}
1.596.2.12.2.  1.2.2(ra 4199:pr-18):         $totcolspan += $columns{$partid};
1.54      albertel 4200:     }
                   4201:     foreach my $partid (@partid) {
1.324     albertel 4202: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4203: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4204: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4205: 	    '</th>';
1.54      albertel 4206: 
1.44      ng       4207:     }
1.477     albertel 4208:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4209: 	&Apache::loncommon::start_data_table_header_row().
                   4210: 	$header.
                   4211: 	&Apache::loncommon::end_data_table_header_row();
                   4212:     my @noupdate;
1.126     ng       4213:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4214:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4215: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4216: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4217: 	my %newrecord;
                   4218: 	my $updateflag = 0;
1.108     albertel 4219: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.596.2.12.2.  1.2.2(ra 4220:pr-18):         my $canmodify = &canmodify($usec);
                   4221:pr-18):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4222:pr-18):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4223:pr-18):         if (!$canmodify) {
                   4224:pr-18):             push(@noupdate,
                   4225:pr-18):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4226:pr-18):                  &mt('Not allowed to modify student')."</span></td>");
                   4227:pr-18):             next;
                   4228:pr-18):         }
1.269     raeburn  4229:         my %aggregate = ();
                   4230:         my $aggregateflag = 0;
1.281     albertel 4231: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4232: 	foreach (@partid) {
1.257     albertel 4233: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4234: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4235: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4236: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4237: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4238: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4239: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4240: 	    my $score;
                   4241: 	    if ($partial eq '') {
1.257     albertel 4242: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4243: 	    } elsif ($partial > 0) {
                   4244: 		$score = 'correct_by_override';
                   4245: 	    } elsif ($partial == 0) {
                   4246: 		$score = 'incorrect_by_override';
                   4247: 	    }
1.257     albertel 4248: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4249: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4250: 
1.292     albertel 4251: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4252: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4253: 	    if ($dropMenu eq 'reset status' &&
                   4254: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4255: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4256: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4257: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4258: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4259: 		$updateflag = 1;
1.269     raeburn  4260:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4261:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4262:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4263:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4264:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4265:                     $aggregateflag = 1;
                   4266:                 }
1.139     albertel 4267: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4268: 		$updateflag = 1;
                   4269: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4270: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4271: 		$rec_update++;
1.125     ng       4272: 	    }
                   4273: 
1.93      albertel 4274: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4275: 		'<td align="center">'.$awarded.
                   4276: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4277: 
1.54      albertel 4278: 
                   4279: 	    my $partid=$_;
                   4280: 	    foreach my $stores (@parts) {
                   4281: 		my ($part,$type) = &split_part_type($stores);
                   4282: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4283: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4284: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4285: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4286: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4287: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4288: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4289: 		    $updateflag=1;
                   4290: 		}
1.93      albertel 4291: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4292: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4293: 	    }
1.44      ng       4294: 	}
1.477     albertel 4295: 	$line.="\n";
1.301     albertel 4296: 
                   4297: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4298: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4299: 
1.44      ng       4300: 	if ($updateflag) {
                   4301: 	    $count++;
1.257     albertel 4302: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4303: 				    $udom,$uname);
1.301     albertel 4304: 
                   4305: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4306: 					      $cnum,$udom,$uname)) {
                   4307: 		# need to figure out if should be in queue.
                   4308: 		my %record =  
                   4309: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4310: 					     $udom,$uname);
                   4311: 		my $all_graded = 1;
                   4312: 		my $none_graded = 1;
                   4313: 		foreach my $part (@parts) {
                   4314: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4315: 			$all_graded = 0;
                   4316: 		    } else {
                   4317: 			$none_graded = 0;
                   4318: 		    }
                   4319: 		}
                   4320: 
                   4321: 		if ($all_graded || $none_graded) {
                   4322: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4323: 							   $symb,$cdom,$cnum,
                   4324: 							   $udom,$uname);
                   4325: 		}
                   4326: 	    }
                   4327: 
1.477     albertel 4328: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4329: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4330: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4331: 	    $updateCtr++;
1.93      albertel 4332: 	} else {
1.477     albertel 4333: 	    push(@noupdate,
                   4334: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4335: 	    $noupdateCtr++;
1.44      ng       4336: 	}
1.269     raeburn  4337:         if ($aggregateflag) {
                   4338:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4339: 				  $cdom,$cnum);
1.269     raeburn  4340:         }
1.93      albertel 4341:     }
1.477     albertel 4342:     if (@noupdate) {
1.596.2.12.2.  1.2.2(ra 4343:pr-18):         my $numcols=$totcolspan+2;
1.477     albertel 4344: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4345: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4346: 	    &mt('No Changes Occurred For the Students Below').
                   4347: 	    '</td>'.
1.477     albertel 4348: 	    &Apache::loncommon::end_data_table_row();
                   4349: 	foreach my $line (@noupdate) {
                   4350: 	    $result.=
                   4351: 		&Apache::loncommon::start_data_table_row().
                   4352: 		$line.
                   4353: 		&Apache::loncommon::end_data_table_row();
                   4354: 	}
1.44      ng       4355:     }
1.477     albertel 4356:     $result .= &Apache::loncommon::end_data_table().
                   4357: 	&show_grading_menu_form($symb);
1.478     albertel 4358:     my $msg = '<p><b>'.
                   4359: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4360: 	    $rec_update,$count).'</b><br />'.
                   4361: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4362: 	'</b></p>';
1.44      ng       4363:     return $title.$msg.$result;
1.5       albertel 4364: }
1.54      albertel 4365: 
                   4366: sub split_part_type {
                   4367:     my ($partstr) = @_;
                   4368:     my ($temp,@allparts)=split(/_/,$partstr);
                   4369:     my $type=pop(@allparts);
1.439     albertel 4370:     my $part=join('_',@allparts);
1.54      albertel 4371:     return ($part,$type);
                   4372: }
                   4373: 
1.44      ng       4374: #------------- end of section for handling grading by section/class ---------
                   4375: #
                   4376: #----------------------------------------------------------------------------
                   4377: 
1.5       albertel 4378: 
1.44      ng       4379: #----------------------------------------------------------------------------
                   4380: #
                   4381: #-------------------------- Next few routines handles grading by csv upload
                   4382: #
                   4383: #--- Javascript to handle csv upload
1.27      albertel 4384: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4385:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4386:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4387:6):   &js_escape(\$error1);
                   4388:6):   &js_escape(\$error2);
1.27      albertel 4389:   return(<<ENDPICK);
                   4390:   function verify(vf) {
                   4391:     var foundsomething=0;
                   4392:     var founduname=0;
1.243     albertel 4393:     var foundID=0;
1.27      albertel 4394:     for (i=0;i<=vf.nfields.value;i++) {
                   4395:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4396:       if (i==0 && tw!=0) { foundID=1; }
                   4397:       if (i==1 && tw!=0) { founduname=1; }
                   4398:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4399:     }
1.246     albertel 4400:     if (founduname==0 && foundID==0) {
                   4401: 	alert('$error1');
                   4402: 	return;
1.27      albertel 4403:     }
                   4404:     if (foundsomething==0) {
1.246     albertel 4405: 	alert('$error2');
                   4406: 	return;
1.27      albertel 4407:     }
                   4408:     vf.submit();
                   4409:   }
                   4410:   function flip(vf,tf) {
                   4411:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4412:     var i;
                   4413:     for (i=0;i<=vf.nfields.value;i++) {
                   4414:       //can not pick the same destination field for both name and domain
                   4415:       if (((i ==0)||(i ==1)) && 
                   4416:           ((tf==0)||(tf==1)) && 
                   4417:           (i!=tf) &&
                   4418:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4419:         eval('vf.f'+i+'.selectedIndex=0;')
                   4420:       }
                   4421:     }
                   4422:   }
                   4423: ENDPICK
                   4424: }
                   4425: 
                   4426: sub csvupload_javascript_forward_associate {
1.573     bisitz   4427:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4428:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4429:6):   &js_escape(\$error1);
                   4430:6):   &js_escape(\$error2);
1.27      albertel 4431:   return(<<ENDPICK);
                   4432:   function verify(vf) {
                   4433:     var foundsomething=0;
                   4434:     var founduname=0;
1.243     albertel 4435:     var foundID=0;
1.27      albertel 4436:     for (i=0;i<=vf.nfields.value;i++) {
                   4437:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4438:       if (tw==1) { foundID=1; }
                   4439:       if (tw==2) { founduname=1; }
                   4440:       if (tw>3) { foundsomething=1; }
1.27      albertel 4441:     }
1.246     albertel 4442:     if (founduname==0 && foundID==0) {
                   4443: 	alert('$error1');
                   4444: 	return;
1.27      albertel 4445:     }
                   4446:     if (foundsomething==0) {
1.246     albertel 4447: 	alert('$error2');
                   4448: 	return;
1.27      albertel 4449:     }
                   4450:     vf.submit();
                   4451:   }
                   4452:   function flip(vf,tf) {
                   4453:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4454:     var i;
                   4455:     //can not pick the same destination field twice
                   4456:     for (i=0;i<=vf.nfields.value;i++) {
                   4457:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4458:         eval('vf.f'+i+'.selectedIndex=0;')
                   4459:       }
                   4460:     }
                   4461:   }
                   4462: ENDPICK
                   4463: }
                   4464: 
1.26      albertel 4465: sub csvuploadmap_header {
1.324     albertel 4466:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4467:     my $javascript;
1.257     albertel 4468:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4469: 	$javascript=&csvupload_javascript_reverse_associate();
                   4470:     } else {
                   4471: 	$javascript=&csvupload_javascript_forward_associate();
                   4472:     }
1.45      ng       4473: 
1.324     albertel 4474:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 4475:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4476:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4477:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       4478:     $request->print(<<ENDPICK);
1.26      albertel 4479: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4480: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       4481: $result
1.326     albertel 4482: <hr />
1.26      albertel 4483: <h3>Identify fields</h3>
                   4484: Total number of records found in file: $distotal <hr />
                   4485: Enter as many fields as you can. The system will inform you and bring you back
                   4486: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4487: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4488: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4489: <input type="hidden" name="associate"  value="" />
                   4490: <input type="hidden" name="phase"      value="three" />
                   4491: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4492: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4493: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4494: <input type="hidden" name="upfile_associate" 
1.257     albertel 4495:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4496: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4497: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4498: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4499: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4500: <hr />
                   4501: <script type="text/javascript" language="Javascript">
                   4502: $javascript
                   4503: </script>
                   4504: ENDPICK
1.118     ng       4505:     return '';
1.26      albertel 4506: 
                   4507: }
                   4508: 
                   4509: sub csvupload_fields {
1.582     raeburn  4510:     my ($symb,$errorref) = @_;
                   4511:     my (@parts) = &getpartlist($symb,$errorref);
                   4512:     if (ref($errorref)) {
                   4513:         if ($$errorref) {
                   4514:             return;
                   4515:         }
                   4516:     }
                   4517: 
1.556     weissno  4518:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4519: 		['username','Student Username'],
                   4520: 		['domain','Student Domain']);
1.324     albertel 4521:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4522:     foreach my $part (sort(@parts)) {
                   4523: 	my @datum;
                   4524: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4525: 	my $name=$part;
                   4526: 	if  (!$display) { $display = $name; }
                   4527: 	@datum=($name,$display);
1.244     albertel 4528: 	if ($name=~/^stores_(.*)_awarded/) {
                   4529: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4530: 	}
1.41      ng       4531: 	push(@fields,\@datum);
                   4532:     }
                   4533:     return (@fields);
1.26      albertel 4534: }
                   4535: 
                   4536: sub csvuploadmap_footer {
1.41      ng       4537:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4538:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4539:     $request->print(<<ENDPICK);
1.26      albertel 4540: </table>
                   4541: <input type="hidden" name="nfields" value="$i" />
                   4542: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4543:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4544: </form>
                   4545: ENDPICK
                   4546: }
                   4547: 
1.283     albertel 4548: sub checkforfile_js {
1.539     riegler  4549:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4550:6):     &js_escape(\$alertmsg);
1.86      ng       4551:     my $result =<<CSVFORMJS;
                   4552: <script type="text/javascript" language="javascript">
                   4553:     function checkUpload(formname) {
                   4554: 	if (formname.upfile.value == "") {
1.539     riegler  4555: 	    alert("$alertmsg");
1.86      ng       4556: 	    return false;
                   4557: 	}
                   4558: 	formname.submit();
                   4559:     }
                   4560:     </script>
                   4561: CSVFORMJS
1.283     albertel 4562:     return $result;
                   4563: }
                   4564: 
                   4565: sub upcsvScores_form {
                   4566:     my ($request) = shift;
1.324     albertel 4567:     my ($symb)=&get_symb($request);
1.283     albertel 4568:     if (!$symb) {return '';}
                   4569:     my $result=&checkforfile_js();
1.257     albertel 4570:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4571:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4572:     $result.=$table;
1.326     albertel 4573:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4574:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4575:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4576: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4577:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4578:     my $upload=&mt("Upload Scores");
1.86      ng       4579:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4580:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4581:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4582:     $result.=<<ENDUPFORM;
1.106     albertel 4583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4584: <input type="hidden" name="symb" value="$symb" />
                   4585: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4586: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4587: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4588: $upfile_select
1.589     bisitz   4589: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4590: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4591: </form>
                   4592: ENDUPFORM
1.370     www      4593:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4594:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4595:     .'</td></tr></table>'."\n";
1.86      ng       4596:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4597:     $result.=&show_grading_menu_form($symb);
1.86      ng       4598:     return $result;
                   4599: }
                   4600: 
                   4601: 
1.26      albertel 4602: sub csvuploadmap {
1.41      ng       4603:     my ($request)= @_;
1.324     albertel 4604:     my ($symb)=&get_symb($request);
1.41      ng       4605:     if (!$symb) {return '';}
1.72      ng       4606: 
1.41      ng       4607:     my $datatoken;
1.257     albertel 4608:     if (!$env{'form.datatoken'}) {
1.41      ng       4609: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4610:     } else {
1.596.2.12.2.  1.2.1(ra 4611:ov-17):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4612:ov-17):         if ($datatoken ne '') {
                   4613:ov-17):             &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4614:ov-17):         }
1.26      albertel 4615:     }
1.41      ng       4616:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4617:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4618:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4619:     my ($i,$keyfields);
                   4620:     if (@records) {
1.582     raeburn  4621:         my $fieldserror;
                   4622: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4623:         if ($fieldserror) {
                   4624:             $request->print(&navmap_errormsg());
                   4625:             return;
                   4626:         }
1.257     albertel 4627: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4628: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4629: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4630: 							  \@fields);
                   4631: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4632: 	    chop($keyfields);
                   4633: 	} else {
                   4634: 	    unshift(@fields,['none','']);
                   4635: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4636: 							    \@fields);
1.311     banghart 4637:             foreach my $rec (@records) {
                   4638:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4639:                 if (%temp) {
                   4640:                     $keyfields=join(',',sort(keys(%temp)));
                   4641:                     last;
                   4642:                 }
                   4643:             }
1.41      ng       4644: 	}
                   4645:     }
                   4646:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4647:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4648: 
1.41      ng       4649:     return '';
1.27      albertel 4650: }
                   4651: 
1.246     albertel 4652: sub csvuploadoptions {
1.41      ng       4653:     my ($request)= @_;
1.324     albertel 4654:     my ($symb)=&get_symb($request);
1.257     albertel 4655:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4656:     my $ignore=&mt('Ignore First Line');
                   4657:     $request->print(<<ENDPICK);
                   4658: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4659: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4660: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4661: <!--
1.246     albertel 4662: <p>
                   4663: <label>
                   4664:    <input type="checkbox" name="show_full_results" />
                   4665:    Show a table of all changes
                   4666: </label>
                   4667: </p>
1.302     albertel 4668: -->
1.246     albertel 4669: <p>
                   4670: <label>
                   4671:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4672:    Overwrite any existing score
                   4673: </label>
                   4674: </p>
                   4675: ENDPICK
                   4676:     my %fields=&get_fields();
                   4677:     if (!defined($fields{'domain'})) {
1.257     albertel 4678: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4679: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4680:     }
1.257     albertel 4681:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4682: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4683: 	my $cleankey=$1;
                   4684: 	if ($cleankey eq 'command') { next; }
                   4685: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4686: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4687:     }
                   4688:     # FIXME do a check for any duplicated user ids...
                   4689:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4690:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4691: <hr /></form>'."\n");
1.324     albertel 4692:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4693:     return '';
                   4694: }
                   4695: 
                   4696: sub get_fields {
                   4697:     my %fields;
1.257     albertel 4698:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4699:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4700: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4701: 	    if ($env{'form.f'.$i} ne 'none') {
                   4702: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4703: 	    }
                   4704: 	} else {
1.257     albertel 4705: 	    if ($env{'form.f'.$i} ne 'none') {
                   4706: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4707: 	    }
                   4708: 	}
1.27      albertel 4709:     }
1.246     albertel 4710:     return %fields;
                   4711: }
                   4712: 
                   4713: sub csvuploadassign {
                   4714:     my ($request)= @_;
1.324     albertel 4715:     my ($symb)=&get_symb($request);
1.246     albertel 4716:     if (!$symb) {return '';}
1.345     bowersj2 4717:     my $error_msg = '';
1.596.2.12.2.  1.2.1(ra 4718:ov-17):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4719:ov-17):     if ($datatoken ne '') {
                   4720:ov-17):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4721:ov-17):     }
1.246     albertel 4722:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4723:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4724:     my %fields=&get_fields();
1.41      ng       4725:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4726:     my $courseid=$env{'request.course.id'};
1.97      albertel 4727:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4728:     my @notallowed;
1.41      ng       4729:     my @skipped;
1.596.2.4  raeburn  4730:     my @warnings;
1.41      ng       4731:     my $countdone=0;
                   4732:     foreach my $grade (@gradedata) {
                   4733: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4734: 	my $domain;
                   4735: 	if ($entries{$fields{'domain'}}) {
                   4736: 	    $domain=$entries{$fields{'domain'}};
                   4737: 	} else {
1.257     albertel 4738: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4739: 	}
1.243     albertel 4740: 	$domain=~s/\s//g;
1.41      ng       4741: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4742: 	$username=~s/\s//g;
1.243     albertel 4743: 	if (!$username) {
                   4744: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4745: 	    $id=~s/\s//g;
1.243     albertel 4746: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4747: 	    $username=$ids{$id};
                   4748: 	}
1.41      ng       4749: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4750: 	    my $id=$entries{$fields{'ID'}};
                   4751: 	    $id=~s/\s//g;
                   4752: 	    if ($id) {
                   4753: 		push(@skipped,"$id:$domain");
                   4754: 	    } else {
                   4755: 		push(@skipped,"$username:$domain");
                   4756: 	    }
1.41      ng       4757: 	    next;
                   4758: 	}
1.108     albertel 4759: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4760: 	if (!&canmodify($usec)) {
                   4761: 	    push(@notallowed,"$username:$domain");
                   4762: 	    next;
                   4763: 	}
1.244     albertel 4764: 	my %points;
1.41      ng       4765: 	my %grades;
                   4766: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4767: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4768: 		$dest eq 'domain') { next; }
                   4769: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4770: 	    if ($dest=~/stores_(.*)_points/) {
                   4771: 		my $part=$1;
                   4772: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4773: 					      $symb,$domain,$username);
1.345     bowersj2 4774:                 if ($wgt) {
                   4775:                     $entries{$fields{$dest}}=~s/\s//g;
                   4776:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4777:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4778:                                           : 'correct_by_override';
1.596.2.4  raeburn  4779:                     if ($pcr>1) {
                   4780:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4781:                     }
1.345     bowersj2 4782:                     $grades{"resource.$part.awarded"}=$pcr;
                   4783:                     $grades{"resource.$part.solved"}=$award;
                   4784:                     $points{$part}=1;
                   4785:                 } else {
                   4786:                     $error_msg = "<br />" .
                   4787:                         &mt("Some point values were assigned"
                   4788:                             ." for problems with a weight "
                   4789:                             ."of zero. These values were "
                   4790:                             ."ignored.");
                   4791:                 }
1.244     albertel 4792: 	    } else {
                   4793: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4794: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4795: 		my $store_key=$dest;
                   4796: 		$store_key=~s/^stores/resource/;
                   4797: 		$store_key=~s/_/\./g;
                   4798: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4799: 	    }
1.41      ng       4800: 	}
1.508     www      4801: 	if (! %grades) { 
                   4802:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4803:         } else {
                   4804: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4805: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4806: 					   $env{'request.course.id'},
                   4807: 					   $domain,$username);
1.508     www      4808: 	   if ($result eq 'ok') {
                   4809: 	      $request->print('.');
1.596.2.4  raeburn  4810: # Remove from grading queue
                   4811:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4812:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4813:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4814:                                              $domain,$username);
1.508     www      4815: 	   } else {
                   4816: 	      $request->print("<p><span class=\"LC_error\">".
                   4817:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4818:                                   "$username:$domain",$result)."</span></p>");
                   4819: 	   }
                   4820: 	   $request->rflush();
                   4821: 	   $countdone++;
                   4822:         }
1.41      ng       4823:     }
1.570     www      4824:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4825:     if (@warnings) {
                   4826:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4827:         $request->print(join(', ',@warnings));
                   4828:     }
1.41      ng       4829:     if (@skipped) {
1.571     www      4830: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4831:         $request->print(join(', ',@skipped));
1.106     albertel 4832:     }
                   4833:     if (@notallowed) {
1.571     www      4834: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4835: 	$request->print(join(', ',@notallowed));
1.41      ng       4836:     }
1.106     albertel 4837:     $request->print("<br />\n");
1.324     albertel 4838:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4839:     return $error_msg;
1.26      albertel 4840: }
1.44      ng       4841: #------------- end of section for handling csv file upload ---------
                   4842: #
                   4843: #-------------------------------------------------------------------
                   4844: #
1.122     ng       4845: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4846: #
                   4847: #--- Select a page/sequence and a student to grade
1.68      ng       4848: sub pickStudentPage {
                   4849:     my ($request) = shift;
                   4850: 
1.539     riegler  4851:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 4852:6):     &js_escape(\$alertmsg);
1.68      ng       4853:     $request->print(<<LISTJAVASCRIPT);
                   4854: <script type="text/javascript" language="javascript">
                   4855: 
                   4856: function checkPickOne(formname) {
1.76      ng       4857:     if (radioSelection(formname.student) == null) {
1.539     riegler  4858: 	alert("$alertmsg");
1.68      ng       4859: 	return;
                   4860:     }
1.125     ng       4861:     ptr = pullDownSelection(formname.selectpage);
                   4862:     formname.page.value = formname["page"+ptr].value;
                   4863:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4864:     formname.submit();
                   4865: }
                   4866: 
                   4867: </script>
                   4868: LISTJAVASCRIPT
1.118     ng       4869:     &commonJSfunctions($request);
1.324     albertel 4870:     my ($symb) = &get_symb($request);
1.257     albertel 4871:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4872:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4873:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4874: 
1.398     albertel 4875:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4876: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4877: 
1.80      ng       4878:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4879:     my $map_error;
                   4880:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4881:     if ($map_error) {
                   4882:         $request->print(&navmap_errormsg());
                   4883:         return; 
                   4884:     }
1.137     albertel 4885:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4886: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4887: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4888:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4889:     my $ctr=0;
1.68      ng       4890:     foreach (@$titles) {
                   4891: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4892: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4893: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4894: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4895: 	$ctr++;
1.68      ng       4896:     }
1.485     albertel 4897:     $select.= '</select>';
1.539     riegler  4898:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4899: 
1.70      ng       4900:     $ctr=0;
                   4901:     foreach (@$titles) {
                   4902: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4903: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4904: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4905: 	$ctr++;
                   4906:     }
1.72      ng       4907:     $result.='<input type="hidden" name="page" />'."\n".
                   4908: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4909: 
1.485     albertel 4910:     my $options =
                   4911: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4912: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4913:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4914: 
                   4915:     $options =
                   4916: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4917: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4918: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4919:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4920:     
                   4921:     $result.=&build_section_inputs();
1.442     banghart 4922:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4923:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4924: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4925: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4926: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4927: 
1.539     riegler  4928:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4929: 
1.80      ng       4930:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4931:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4932: 
1.68      ng       4933:     $request->print($result);
                   4934: 
1.485     albertel 4935:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4936: 	&Apache::loncommon::start_data_table().
                   4937: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4938: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4939: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4940: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4941: 	'<th>'.&nameUserString('header').'</th>'.
                   4942: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4943:  
1.76      ng       4944:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4945:     my $ptr = 1;
1.294     albertel 4946:     foreach my $student (sort 
                   4947: 			 {
                   4948: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4949: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4950: 			     }
                   4951: 			     return $a cmp $b;
                   4952: 			 } (keys(%$fullname))) {
1.68      ng       4953: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4954: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4955:                                   : '</td>');
1.126     ng       4956: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4957: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4958: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4959: 	$studentTable.=
                   4960: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4961:                          : '');
1.68      ng       4962: 	$ptr++;
                   4963:     }
1.484     albertel 4964:     if ($ptr%2 == 0) {
                   4965: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4966: 	    &Apache::loncommon::end_data_table_row();
                   4967:     }
                   4968:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4969:     $studentTable.='<input type="button" '.
1.589     bisitz   4970:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4971: 
1.324     albertel 4972:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4973:     $request->print($studentTable);
                   4974: 
                   4975:     return '';
                   4976: }
                   4977: 
                   4978: sub getSymbMap {
1.582     raeburn  4979:     my ($map_error) = @_;
1.132     bowersj2 4980:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4981:     unless (ref($navmap)) {
                   4982:         if (ref($map_error)) {
                   4983:             $$map_error = 'navmap';
                   4984:         }
                   4985:         return;
                   4986:     }
1.68      ng       4987:     my %symbx = ();
                   4988:     my @titles = ();
1.117     bowersj2 4989:     my $minder = 0;
                   4990: 
                   4991:     # Gather every sequence that has problems.
1.240     albertel 4992:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4993: 					       1,0,1);
1.117     bowersj2 4994:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4995: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4996: 	    my $title = $minder.'.'.
                   4997: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4998: 	    push(@titles, $title); # minder in case two titles are identical
                   4999: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5000: 	    $minder++;
1.241     albertel 5001: 	}
1.68      ng       5002:     }
                   5003:     return \@titles,\%symbx;
                   5004: }
                   5005: 
1.72      ng       5006: #
                   5007: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5008: sub displayPage {
                   5009:     my ($request) = shift;
                   5010: 
1.324     albertel 5011:     my ($symb) = &get_symb($request);
1.257     albertel 5012:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5013:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5014:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5015:     my $pageTitle = $env{'form.page'};
1.103     albertel 5016:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5017:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5018:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5019: 
                   5020:     #need to make sure we have the correct data for later EXT calls, 
                   5021:     #thus invalidate the cache
                   5022:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5023:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5024:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5025:     &Apache::lonnet::clear_EXT_cache_status();
                   5026: 
1.103     albertel 5027:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 5028:4): 	$request->print('<span class="LC_warning">'.
                   5029:4):                         &mt('Unable to view requested student. ([_1])',
                   5030:4):                             $env{'form.student'}).
                   5031:4):                         '</span>');
                   5032:4):         $request->print(&show_grading_menu_form($symb));
                   5033:4):         return;
1.103     albertel 5034:     }
1.398     albertel 5035:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5036:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5037: 	'</h3>'."\n";
1.500     albertel 5038:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5039:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5040: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5041:     } else {
                   5042: 	delete($env{'form.CODE'});
                   5043:     }
1.71      ng       5044:     &sub_page_js($request);
                   5045:     $request->print($result);
                   5046: 
1.132     bowersj2 5047:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5048:     unless (ref($navmap)) {
                   5049:         $request->print(&navmap_errormsg());
                   5050:         $request->print(&show_grading_menu_form($symb));
                   5051:         return;
                   5052:     }
1.257     albertel 5053:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5054:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5055:     if (!$map) {
1.485     albertel 5056: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 5057: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5058: 	return; 
                   5059:     }
1.68      ng       5060:     my $iterator = $navmap->getIterator($map->map_start(),
                   5061: 					$map->map_finish());
                   5062: 
1.71      ng       5063:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5064: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5065: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5066: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5067: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5068: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5069: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       5070: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 5071: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       5072: 
1.382     albertel 5073:     if (defined($env{'form.CODE'})) {
                   5074: 	$studentTable.=
                   5075: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5076:     }
1.381     albertel 5077:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5078: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5079: 
1.594     bisitz   5080:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5081:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5082:         '</span>'."\n".
1.484     albertel 5083: 	&Apache::loncommon::start_data_table().
                   5084: 	&Apache::loncommon::start_data_table_header_row().
                   5085: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 5086: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5087: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5088: 
1.329     albertel 5089:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5090:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5091:     $iterator->next(); # skip the first BEGIN_MAP
                   5092:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5093:     while ($depth > 0) {
1.68      ng       5094:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5095:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5096: 
1.385     albertel 5097:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5098: 	    my $parts = $curRes->parts();
1.68      ng       5099:             my $title = $curRes->compTitle();
1.71      ng       5100: 	    my $symbx = $curRes->symb();
1.484     albertel 5101: 	    $studentTable.=
                   5102: 		&Apache::loncommon::start_data_table_row().
                   5103: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5104: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5105:2): 		                        : '<br />('.&mt('[_1]parts',
                   5106:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5107: 		 ).
                   5108: 		 '</td>';
1.71      ng       5109: 	    $studentTable.='<td valign="top">';
1.382     albertel 5110: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5111: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5112: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5113: 					     undef,'both',\%form);
1.71      ng       5114: 	    } else {
1.382     albertel 5115: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5116: 		$companswer =~ s|<form(.*?)>||g;
                   5117: 		$companswer =~ s|</form>||g;
1.71      ng       5118: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5119: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5120: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5121: #		}
1.116     ng       5122: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5123: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5124: 	    }
                   5125: 
1.257     albertel 5126: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5127: 
1.257     albertel 5128: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5129: 		if ($record{'version'} eq '') {
1.485     albertel 5130: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5131: 		} else {
1.116     ng       5132: 		    my %responseType = ();
                   5133: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5134: 			my @responseIds =$curRes->responseIds($partid);
                   5135: 			my @responseType =$curRes->responseType($partid);
                   5136: 			my %responseIds;
                   5137: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5138: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5139: 			}
                   5140: 			$responseType{$partid} = \%responseIds;
1.116     ng       5141: 		    }
1.148     albertel 5142: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5143: 
1.71      ng       5144: 		}
1.257     albertel 5145: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5146: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5147:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5148: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5149: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5150:5): 									'','.submission',undef,
                   5151:5):                                                                         $usec,$identifier);
1.71      ng       5152:  
                   5153: 	    }
1.103     albertel 5154: 	    if (&canmodify($usec)) {
1.585     bisitz   5155:             $studentTable.=&gradeBox_start();
1.103     albertel 5156: 		foreach my $partid (@{$parts}) {
                   5157: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5158: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5159: 		    $question++;
                   5160: 		}
1.585     bisitz   5161:             $studentTable.=&gradeBox_end();
1.196     albertel 5162: 		$prob++;
1.71      ng       5163: 	    }
                   5164: 	    $studentTable.='</td></tr>';
1.68      ng       5165: 
1.103     albertel 5166: 	}
1.68      ng       5167:         $curRes = $iterator->next();
                   5168:     }
                   5169: 
1.589     bisitz   5170:     $studentTable.=
                   5171:         '</table>'."\n".
                   5172:         '<input type="button" value="'.&mt('Save').'" '.
                   5173:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5174:         '</form>'."\n";
1.324     albertel 5175:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       5176:     $request->print($studentTable);
                   5177: 
                   5178:     return '';
1.119     ng       5179: }
                   5180: 
                   5181: sub displaySubByDates {
1.148     albertel 5182:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5183:     my $isCODE=0;
1.335     albertel 5184:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5185:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5186:     my $studentTable=&Apache::loncommon::start_data_table().
                   5187: 	&Apache::loncommon::start_data_table_header_row().
                   5188: 	'<th>'.&mt('Date/Time').'</th>'.
                   5189: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5190:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5191: 	'<th>'.&mt('Submission').'</th>'.
                   5192: 	'<th>'.&mt('Status').'</th>'.
                   5193: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5194:     my ($version);
                   5195:     my %mark;
1.148     albertel 5196:     my %orders;
1.119     ng       5197:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5198:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5199: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5200:     }
1.335     albertel 5201: 
                   5202:     my $interaction;
1.525     raeburn  5203:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5204:5):     my (%lastrndseed,%lasttype);
1.119     ng       5205:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5206: 	my $timestamp = 
                   5207: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5208: 	if (exists($$record{$version.':resource.0.version'})) {
                   5209: 	    $interaction = $$record{$version.':resource.0.version'};
                   5210: 	}
1.596.2.12.2.  (raeburn 5211:):         if ($isTask && $env{'form.previousversion'}) {
                   5212:):             next unless ($interaction == $env{'form.previousversion'});
                   5213:):         }
1.335     albertel 5214: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5215: 		             : "$version:resource");
1.467     albertel 5216: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5217: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5218: 	if ($isCODE) {
                   5219: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5220: 	}
1.596.2.12.2.  (raeburn 5221:):         if ($isTask) {
                   5222:):             $studentTable.='<td>'.$interaction.'</td>';
                   5223:):         }
1.119     ng       5224: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5225: 	my @displaySub = ();
                   5226: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5227:             my ($hidden,$type);
                   5228:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5229:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5230:                 $hidden = 1;
                   5231:             }
1.335     albertel 5232: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   5233: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5234: 	    
1.122     ng       5235: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5236: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5237: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5238: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5239: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5240:                     
1.335     albertel 5241: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5242: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5243:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5244:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5245:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5246:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5247:                                    .'</span>'
                   5248:                                    .' <b>';
1.596     raeburn  5249:                     if ($hidden) {
                   5250:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5251:                     } else {
1.596.2.2  raeburn  5252:                         my ($trial,$rndseed,$newvariation);
                   5253:                         if ($type eq 'randomizetry') {
                   5254:                             $trial = $$record{"$where.$partid.tries"};
                   5255:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5256:                         }
1.596     raeburn  5257: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5258: 			    $displaySub[0].=&mt('Trial not counted');
                   5259: 		        } else {
                   5260: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5261: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5262:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5263:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5264:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5265:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5266:                                 }
                   5267:                             }
1.596.2.12.2.  4(raebur 5268:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5269:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5270: 		        }
                   5271: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5272:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5273: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5274: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5275: 			    $orders{$partid}->{$responseId}=
                   5276: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5277:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5278: 		        }
1.596.2.2  raeburn  5279: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5280: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5281: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5282:                     }
1.147     albertel 5283: 		}
                   5284: 	    }
1.335     albertel 5285: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5286: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5287: 				    $$record{"$where.$partid.checkedin"},
                   5288: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5289: 					'<br />';
1.335     albertel 5290: 	    }
                   5291: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5292: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5293: 		    lc($$record{"$where.$partid.award"}).' '.
                   5294: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5295: 		    '<br />';
                   5296: 	    }
1.335     albertel 5297: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5298: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5299: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5300: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5301: 		$displaySub[2].=
                   5302: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5303: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5304: 	    }
                   5305: 	}
                   5306: 	# needed because old essay regrader has not parts info
                   5307: 	if (exists $$record{"$version:resource.regrader"}) {
                   5308: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5309: 	}
                   5310: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5311: 	if ($displaySub[2]) {
1.467     albertel 5312: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5313: 	}
1.467     albertel 5314: 	$studentTable.='&nbsp;</td>'.
                   5315: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5316:     }
1.467     albertel 5317:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5318:     return $studentTable;
1.71      ng       5319: }
                   5320: 
                   5321: sub updateGradeByPage {
                   5322:     my ($request) = shift;
                   5323: 
1.257     albertel 5324:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5325:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5326:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5327:     my $pageTitle = $env{'form.page'};
1.103     albertel 5328:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5329:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5330:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5331:     if (!&canmodify($usec)) {
1.526     raeburn  5332: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 5333: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 5334: 	return;
                   5335:     }
1.398     albertel 5336:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5337:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5338: 	'</h3>'."\n";
1.70      ng       5339: 
1.68      ng       5340:     $request->print($result);
                   5341: 
1.582     raeburn  5342: 
1.132     bowersj2 5343:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5344:     unless (ref($navmap)) {
                   5345:         $request->print(&navmap_errormsg());
                   5346:         return;
                   5347:     }
1.257     albertel 5348:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5349:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5350:     if (!$map) {
1.527     raeburn  5351: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 5352: 	my ($symb)=&get_symb($request);
                   5353: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5354: 	return; 
                   5355:     }
1.71      ng       5356:     my $iterator = $navmap->getIterator($map->map_start(),
                   5357: 					$map->map_finish());
1.70      ng       5358: 
1.484     albertel 5359:     my $studentTable=
                   5360: 	&Apache::loncommon::start_data_table().
                   5361: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5362: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5363: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5364: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5365: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5366: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5367: 
                   5368:     $iterator->next(); # skip the first BEGIN_MAP
                   5369:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5370:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5371:     while ($depth > 0) {
1.71      ng       5372:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5373:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5374: 
1.385     albertel 5375:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5376: 	    my $parts = $curRes->parts();
1.71      ng       5377:             my $title = $curRes->compTitle();
                   5378: 	    my $symbx = $curRes->symb();
1.484     albertel 5379: 	    $studentTable.=
                   5380: 		&Apache::loncommon::start_data_table_row().
                   5381: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5382: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5383:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5384: 		.')').'</td>';
1.71      ng       5385: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5386: 
                   5387: 	    my %newrecord=();
                   5388: 	    my @displayPts=();
1.269     raeburn  5389:             my %aggregate = ();
                   5390:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5391:5):             if ($env{'form.HIDE'.$prob}) {
                   5392:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5393:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5394:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5395:5):                 $hideflag += $numchgs;
                   5396:5):             }
1.71      ng       5397: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5398: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5399: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5400: 
1.257     albertel 5401: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5402: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5403: 		my $partial = $newpts/$wgt;
                   5404: 		my $score;
                   5405: 		if ($partial > 0) {
                   5406: 		    $score = 'correct_by_override';
1.125     ng       5407: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5408: 		    $score = 'incorrect_by_override';
                   5409: 		}
1.257     albertel 5410: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5411: 		if ($dropMenu eq 'excused') {
1.71      ng       5412: 		    $partial = '';
                   5413: 		    $score = 'excused';
1.125     ng       5414: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5415: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5416: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5417: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5418: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5419: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5420: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5421: 		    $changeflag++;
                   5422: 		    $newpts = '';
1.269     raeburn  5423:                     
                   5424:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5425:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5426:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5427:                     if ($aggtries > 0) {
                   5428:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5429:                         $aggregateflag = 1;
                   5430:                     }
1.71      ng       5431: 		}
1.324     albertel 5432: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5433: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5434: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5435: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5436: 		    '&nbsp;<br />';
1.526     raeburn  5437: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5438: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5439: 		    '&nbsp;<br />';
1.71      ng       5440: 		$question++;
1.380     albertel 5441: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5442: 
1.71      ng       5443: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5444: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5445: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5446: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5447: 
                   5448: 		$changeflag++;
                   5449: 	    }
                   5450: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5451: 		my %record = 
                   5452: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5453: 					     $udom,$uname);
                   5454: 
                   5455: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5456: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5457: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5458: 		    $newrecord{'resource.CODE'} = '';
                   5459: 		}
1.257     albertel 5460: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5461: 					$udom,$uname);
1.382     albertel 5462: 		%record = &Apache::lonnet::restore($symbx,
                   5463: 						   $env{'request.course.id'},
                   5464: 						   $udom,$uname);
1.380     albertel 5465: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5466: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5467: 	    }
1.380     albertel 5468: 	    
1.269     raeburn  5469:             if ($aggregateflag) {
                   5470:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5471:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5472:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5473:             }
1.125     ng       5474: 
1.71      ng       5475: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5476: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5477: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5478: 
1.196     albertel 5479: 	    $prob++;
1.68      ng       5480: 	}
1.71      ng       5481:         $curRes = $iterator->next();
1.68      ng       5482:     }
1.98      albertel 5483: 
1.484     albertel 5484:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 5485:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  5486:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5487: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5488:5): 		  $changeflag).'<br />');
                   5489:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5490:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5491:5):                      $hideflag).'<br />');
                   5492:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5493: 
1.70      ng       5494:     return '';
                   5495: }
                   5496: 
1.72      ng       5497: #-------- end of section for handling grading by page/sequence ---------
                   5498: #
                   5499: #-------------------------------------------------------------------
                   5500: 
1.581     www      5501: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5502: #
                   5503: #------ start of section for handling grading by page/sequence ---------
                   5504: 
1.423     albertel 5505: =pod
                   5506: 
                   5507: =head1 Bubble sheet grading routines
                   5508: 
1.424     albertel 5509:   For this documentation:
                   5510: 
                   5511:    'scanline' refers to the full line of characters
                   5512:    from the file that we are parsing that represents one entire sheet
                   5513: 
                   5514:    'bubble line' refers to the data
1.596.2.6  raeburn  5515:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5516: 
                   5517: 
1.596.2.6  raeburn  5518: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5519: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5520: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5521: one of the predefined configurations for what each scanline looks
                   5522: like.
                   5523: 
                   5524: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5525: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5526: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5527:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5528: invalid student/employee ID
1.424     albertel 5529: 
                   5530: If the CODE option is used that determines the randomization of the
1.556     weissno  5531: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5532: username:domain.
                   5533: 
                   5534: During the validation phase the instructor can choose to skip scanlines. 
                   5535: 
1.596.2.6  raeburn  5536: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5537: 
                   5538:   scantron_original_filename (unmodified original file)
                   5539:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5540:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5541: 
                   5542: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5543: correction information that isn't representable in the bubblesheet
1.424     albertel 5544: file (see &scantron_getfile() for more information)
                   5545: 
                   5546: After all scanlines are either valid, marked as valid or skipped, then
                   5547: foreach line foreach problem in the picked sequence, an ssi request is
                   5548: made that simulates a user submitting their selected letter(s) against
                   5549: the homework problem.
1.423     albertel 5550: 
                   5551: =over 4
                   5552: 
                   5553: 
                   5554: 
                   5555: =item defaultFormData
                   5556: 
                   5557:   Returns html hidden inputs used to hold context/default values.
                   5558: 
                   5559:  Arguments:
                   5560:   $symb - $symb of the current resource 
                   5561: 
                   5562: =cut
1.422     foxr     5563: 
1.81      albertel 5564: sub defaultFormData {
1.324     albertel 5565:     my ($symb)=@_;
1.447     foxr     5566:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5567:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5568:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5569: }
                   5570: 
1.447     foxr     5571: 
1.423     albertel 5572: =pod 
                   5573: 
                   5574: =item getSequenceDropDown
                   5575: 
                   5576:    Return html dropdown of possible sequences to grade
                   5577:  
                   5578:  Arguments:
1.582     raeburn  5579:    $symb - $symb of the current resource
                   5580:    $map_error - ref to scalar which will container error if
                   5581:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5582: 
                   5583: =cut
1.422     foxr     5584: 
1.75      albertel 5585: sub getSequenceDropDown {
1.582     raeburn  5586:     my ($symb,$map_error)=@_;
1.75      albertel 5587:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5588:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5589:     if (ref($map_error)) {
                   5590:         return if ($$map_error);
                   5591:     }
1.137     albertel 5592:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5593:     my $ctr=0;
                   5594:     foreach (@$titles) {
                   5595: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5596: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5597: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5598: 	    '>'.$showtitle.'</option>'."\n";
                   5599: 	$ctr++;
                   5600:     }
                   5601:     $result.= '</select>';
                   5602:     return $result;
                   5603: }
                   5604: 
1.495     albertel 5605: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5606:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5607: 
                   5608: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5609: 
1.509     raeburn  5610: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5611:                                    # matchresponse or rankresponse, where 
                   5612:                                    # an individual response can have multiple 
                   5613:                                    # lines
1.503     raeburn  5614: 
                   5615: my %responsetype_per_response;     # responsetype for each response
                   5616: 
1.596.2.12.2.  6(raebur 5617:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5618:3):                                    # numbered response. Needed when randomorder
                   5619:3):                                    # or randompick are in use. Key is ID, value 
                   5620:3):                                    # is response number.
                   5621:3): 
1.495     albertel 5622: # Save and restore the bubble lines array to the form env.
                   5623: 
                   5624: 
                   5625: sub save_bubble_lines {
                   5626:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5627: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5628: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5629: 	    $first_bubble_line{$line};
1.503     raeburn  5630:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5631:             $subdivided_bubble_lines{$line};
                   5632:         $env{"form.scantron.responsetype.$line"} =
                   5633:             $responsetype_per_response{$line};
1.495     albertel 5634:     }
1.596.2.12.2.  6(raebur 5635:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5636:3):         my $line = $masterseq_id_responsenum{$resid};
                   5637:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5638:3):     }
1.495     albertel 5639: }
                   5640: 
                   5641: 
                   5642: sub restore_bubble_lines {
                   5643:     my $line = 0;
                   5644:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5645:3):     %masterseq_id_responsenum = ();
1.495     albertel 5646:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5647: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5648: 	$bubble_lines_per_response{$line} = $value;
                   5649: 	$first_bubble_line{$line}  =
                   5650: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5651:         $subdivided_bubble_lines{$line} =
                   5652:             $env{"form.scantron.sub_bubblelines.$line"};
                   5653:         $responsetype_per_response{$line} =
                   5654:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5655:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5656:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5657: 	$line++;
                   5658:     }
                   5659: }
                   5660: 
1.423     albertel 5661: =pod 
                   5662: 
                   5663: =item scantron_filenames
                   5664: 
                   5665:    Returns a list of the scantron files in the current course 
                   5666: 
                   5667: =cut
1.422     foxr     5668: 
1.202     albertel 5669: sub scantron_filenames {
1.257     albertel 5670:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5671:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5672:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5673:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5674:):                                                         $cname,$getpropath);
1.202     albertel 5675:     my @possiblenames;
1.596.2.12.2.  (raeburn 5676:):     if (ref($dirlist) eq 'ARRAY') {
                   5677:):         foreach my $filename (sort(@{$dirlist})) {
                   5678:): 	    ($filename)=split(/&/,$filename);
                   5679:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5680:): 	    $filename=~s/^scantron_orig_//;
                   5681:): 	    push(@possiblenames,$filename);
                   5682:):         }
1.202     albertel 5683:     }
                   5684:     return @possiblenames;
                   5685: }
                   5686: 
1.423     albertel 5687: =pod 
                   5688: 
                   5689: =item scantron_uploads
                   5690: 
                   5691:    Returns  html drop-down list of scantron files in current course.
                   5692: 
                   5693:  Arguments:
                   5694:    $file2grade - filename to set as selected in the dropdown
                   5695: 
                   5696: =cut
1.422     foxr     5697: 
1.202     albertel 5698: sub scantron_uploads {
1.209     ng       5699:     my ($file2grade) = @_;
1.202     albertel 5700:     my $result=	'<select name="scantron_selectfile">';
                   5701:     $result.="<option></option>";
                   5702:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5703: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5704:     }
                   5705:     $result.="</select>";
                   5706:     return $result;
                   5707: }
                   5708: 
1.423     albertel 5709: =pod 
                   5710: 
                   5711: =item scantron_scantab
                   5712: 
                   5713:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5714:   file.
                   5715: 
                   5716: =cut
1.422     foxr     5717: 
1.82      albertel 5718: sub scantron_scantab {
                   5719:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5720:     $result.='<option></option>'."\n";
1.596.2.12.2.  1.2.3(ra 5721:eb-19):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5722:     if (@lines > 0) {
                   5723:         foreach my $line (@lines) {
                   5724:             next if (($line =~ /^\#/) || ($line eq ''));
                   5725: 	    my ($name,$descrip)=split(/:/,$line);
                   5726: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5727:         }
1.82      albertel 5728:     }
                   5729:     $result.='</select>'."\n";
1.518     raeburn  5730:     return $result;
                   5731: }
                   5732: 
1.423     albertel 5733: =pod 
                   5734: 
                   5735: =item scantron_CODElist
                   5736: 
                   5737:   Returns html drop down of the saved CODE lists from current course,
                   5738:   generated from earlier printings.
                   5739: 
                   5740: =cut
1.422     foxr     5741: 
1.186     albertel 5742: sub scantron_CODElist {
1.257     albertel 5743:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5744:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5745:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5746:     my $namechoice='<option></option>';
1.225     albertel 5747:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5748: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5749: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5750: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5751:     }
                   5752:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5753:     return $namechoice;
                   5754: }
                   5755: 
1.423     albertel 5756: =pod 
                   5757: 
                   5758: =item scantron_CODEunique
                   5759: 
                   5760:   Returns the html for "Each CODE to be used once" radio.
                   5761: 
                   5762: =cut
1.422     foxr     5763: 
1.186     albertel 5764: sub scantron_CODEunique {
1.532     bisitz   5765:     my $result='<span class="LC_nobreak">
1.272     albertel 5766:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5767:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5768:                 </span>
1.532     bisitz   5769:                 <span class="LC_nobreak">
1.272     albertel 5770:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5771:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5772:                 </span>';
1.186     albertel 5773:     return $result;
                   5774: }
1.423     albertel 5775: 
                   5776: =pod 
                   5777: 
                   5778: =item scantron_selectphase
                   5779: 
1.596.2.6  raeburn  5780:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5781:   Allows for - starting a grading run.
1.424     albertel 5782:              - downloading existing scan data (original, corrected
1.423     albertel 5783:                                                 or skipped info)
                   5784: 
                   5785:              - uploading new scan data
                   5786: 
                   5787:  Arguments:
                   5788:   $r          - The Apache request object
                   5789:   $file2grade - name of the file that contain the scanned data to score
                   5790: 
                   5791: =cut
1.186     albertel 5792: 
1.75      albertel 5793: sub scantron_selectphase {
1.209     ng       5794:     my ($r,$file2grade) = @_;
1.324     albertel 5795:     my ($symb)=&get_symb($r);
1.75      albertel 5796:     if (!$symb) {return '';}
1.582     raeburn  5797:     my $map_error;
                   5798:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5799:     if ($map_error) {
                   5800:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5801:         return;
                   5802:     }
1.324     albertel 5803:     my $default_form_data=&defaultFormData($symb);
                   5804:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5805:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5806:     my $format_selector=&scantron_scantab();
1.186     albertel 5807:     my $CODE_selector=&scantron_CODElist();
                   5808:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5809:     my $result;
1.422     foxr     5810: 
1.513     foxr     5811:     $ssi_error = 0;
                   5812: 
1.596.2.4  raeburn  5813:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5814:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5815: 
                   5816:         # Chunk of form to prompt for a scantron file upload.
                   5817: 
                   5818:         $r->print('
1.596.2.12.2.  1.2.3(ra 5819:eb-19):     <br />');
1.596.2.4  raeburn  5820:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5821:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  6(raebur 5822:6):     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5823:6):     &js_escape(\$alertmsg);
          1.2.3(ra 5824:eb-19):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   5825:eb-19):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  5826:     function checkUpload(formname) {
                   5827:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 5828:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  5829:             return false;
                   5830:         }
                   5831:         formname.submit();
1.596.2.12.2.  1.2.3(ra 5832:eb-19):     }'."\n".$formatjs));
                   5833:eb-19):     $r->print('
1.596.2.4  raeburn  5834:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5835:                 '.$default_form_data.'
                   5836:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5837:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5838:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  1.2.3(ra 5839:eb-19):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5840:eb-19):               '.&Apache::loncommon::start_data_table_header_row().'
                   5841:eb-19):                 <th>
                   5842:eb-19):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5843:eb-19):                 </th>
                   5844:eb-19):               '.&Apache::loncommon::end_data_table_header_row().'
                   5845:eb-19):               '.&Apache::loncommon::start_data_table_row().'
                   5846:eb-19):             <td>
                   5847:eb-19):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   5848:eb-19):     if ($formatoptions) {
                   5849:eb-19):         $r->print('</td>
                   5850:eb-19):                  '.&Apache::loncommon::end_data_table_row().'
                   5851:eb-19):                  '.&Apache::loncommon::start_data_table_row().'
                   5852:eb-19):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   5853:eb-19):                  </td>
                   5854:eb-19):                  '.&Apache::loncommon::end_data_table_row().'
                   5855:eb-19):                  '.&Apache::loncommon::start_data_table_row().'
                   5856:eb-19):                  <td>'
                   5857:eb-19):         );
                   5858:eb-19):     } else {
                   5859:eb-19):         $r->print(' <br />');
1.596.2.4  raeburn  5860:     }
1.596.2.12.2.  1.2.3(ra 5861:eb-19):     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5862:eb-19):               </td>
                   5863:eb-19):              '.&Apache::loncommon::end_data_table_row().'
                   5864:eb-19):              '.&Apache::loncommon::end_data_table().'
                   5865:eb-19):              </form>'
                   5866:eb-19):     );
1.596.2.4  raeburn  5867: 
1.596.2.12.2.  1.2.4(ra 5868:eb-19):     }
                   5869:eb-19): 
1.422     foxr     5870:     # Chunk of form to prompt for a file to grade and how:
                   5871: 
1.489     albertel 5872:     $result.= '
                   5873:     <br />
                   5874:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5875:     <input type="hidden" name="command" value="scantron_warning" />
                   5876:     '.$default_form_data.'
                   5877:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5878:        '.&Apache::loncommon::start_data_table_header_row().'
                   5879:             <th colspan="2">
1.492     albertel 5880:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5881:             </th>
                   5882:        '.&Apache::loncommon::end_data_table_header_row().'
                   5883:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5884:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5885:        '.&Apache::loncommon::end_data_table_row().'
                   5886:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5887:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5888:        '.&Apache::loncommon::end_data_table_row().'
                   5889:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5890:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5891:        '.&Apache::loncommon::end_data_table_row().'
                   5892:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5893:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5894:        '.&Apache::loncommon::end_data_table_row().'
                   5895:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5896:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5897:        '.&Apache::loncommon::end_data_table_row().'
                   5898:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5899: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5900:             <td>
1.492     albertel 5901: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5902:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5903:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5904: 	    </td>
1.489     albertel 5905:        '.&Apache::loncommon::end_data_table_row().'
                   5906:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5907:             <td colspan="2">
1.572     www      5908:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5909:             </td>
1.489     albertel 5910:        '.&Apache::loncommon::end_data_table_row().'
                   5911:     '.&Apache::loncommon::end_data_table().'
                   5912:     </form>
                   5913: ';
1.162     albertel 5914:    
                   5915:     $r->print($result);
                   5916: 
1.422     foxr     5917:     # Chunk of the form that prompts to view a scoring office file,
                   5918:     # corrected file, skipped records in a file.
                   5919: 
1.489     albertel 5920:     $r->print('
                   5921:    <br />
                   5922:    <form action="/adm/grades" name="scantron_download">
                   5923:      '.$default_form_data.'
                   5924:      <input type="hidden" name="command" value="scantron_download" />
                   5925:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5926:        '.&Apache::loncommon::start_data_table_header_row().'
                   5927:               <th>
1.492     albertel 5928:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5929:               </th>
                   5930:        '.&Apache::loncommon::end_data_table_header_row().'
                   5931:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5932:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5933:                 <br />
1.492     albertel 5934:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5935:        '.&Apache::loncommon::end_data_table_row().'
                   5936:      '.&Apache::loncommon::end_data_table().'
                   5937:    </form>
                   5938:    <br />
                   5939: ');
1.162     albertel 5940: 
1.457     banghart 5941:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5942: 
1.596.2.12.2.  8(raebur 5943:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5944:              $default_form_data."\n".
                   5945:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5946:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5947:              '<th colspan="2">
1.572     www      5948:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5949:              '</th>'."\n".
                   5950:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5951:               &Apache::loncommon::start_data_table_row()."\n".
                   5952:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5953:               '<td> '.$sequence_selector.' </td>'.
                   5954:               &Apache::loncommon::end_data_table_row()."\n".
                   5955:               &Apache::loncommon::start_data_table_row()."\n".
                   5956:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5957:               '<td> '.$file_selector.' </td>'."\n".
                   5958:               &Apache::loncommon::end_data_table_row()."\n".
                   5959:               &Apache::loncommon::start_data_table_row()."\n".
                   5960:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5961:               '<td> '.$format_selector.' </td>'."\n".
                   5962:               &Apache::loncommon::end_data_table_row()."\n".
                   5963:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5964:               '<td> '.&mt('Options').' </td>'."\n".
                   5965:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5966:               &Apache::loncommon::end_data_table_row()."\n".
                   5967:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5968:               '<td colspan="2">'."\n".
                   5969:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5970:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5971:               '</td>'."\n".
                   5972:               &Apache::loncommon::end_data_table_row()."\n".
                   5973:               &Apache::loncommon::end_data_table()."\n".
                   5974:               '</form><br />');
1.457     banghart 5975:     $r->print($grading_menu_button);
1.523     raeburn  5976:     return;
1.75      albertel 5977: }
                   5978: 
1.423     albertel 5979: =pod 
                   5980: 
                   5981: =item username_to_idmap
                   5982: 
1.556     weissno  5983:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5984:     student username:domain.
                   5985: 
                   5986:   Arguments:
                   5987: 
                   5988:     $classlist - reference to the class list hash. This is a hash
                   5989:                  keyed by student name:domain  whose elements are references
1.424     albertel 5990:                  to arrays containing various chunks of information
1.423     albertel 5991:                  about the student. (See loncoursedata for more info).
                   5992: 
                   5993:   Returns
                   5994:     %idmap - the constructed hash
                   5995: 
                   5996: =cut
                   5997: 
1.82      albertel 5998: sub username_to_idmap {
                   5999:     my ($classlist)= @_;
                   6000:     my %idmap;
                   6001:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6002:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6003:5):         unless ($id eq '') {
                   6004:5):             if (!exists($idmap{$id})) {
                   6005:5):                 $idmap{$id} = $student;
                   6006:5):             } else {
                   6007:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6008:5):                 if ($status eq 'Active') {
                   6009:5):                     $idmap{$id} = $student;
                   6010:5):                 }
                   6011:5):             }
                   6012:5):         }
1.82      albertel 6013:     }
                   6014:     return %idmap;
                   6015: }
1.423     albertel 6016: 
                   6017: =pod
                   6018: 
1.424     albertel 6019: =item scantron_fixup_scanline
1.423     albertel 6020: 
                   6021:    Process a requested correction to a scanline.
                   6022: 
                   6023:   Arguments:
1.596.2.12.2.  1.2.3(ra 6024:eb-19):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6025:     $scan_data         - hash of correction information 
                   6026:                           (see &scantron_getfile())
                   6027:     $line              - existing scanline
                   6028:     $whichline         - line number of the passed in scanline
                   6029:     $field             - type of change to process 
                   6030:                          (either 
1.573     bisitz   6031:                           'ID'     -> correct the student/employee ID
1.423     albertel 6032:                           'CODE'   -> correct the CODE
                   6033:                           'answer' -> fixup the submitted answers)
                   6034:     
                   6035:    $args               - hash of additional info,
                   6036:                           - 'ID' 
                   6037:                                'newid' -> studentID to use in replacement
1.424     albertel 6038:                                           of existing one
1.423     albertel 6039:                           - 'CODE' 
                   6040:                                'CODE_ignore_dup' - set to true if duplicates
                   6041:                                                    should be ignored.
                   6042: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6043:                                         if the existing unfound code should
1.423     albertel 6044:                                         be used as is
                   6045:                           - 'answer'
                   6046:                                'response' - new answer or 'none' if blank
                   6047:                                'question' - the bubble line to change
1.503     raeburn  6048:                                'questionnum' - the question identifier,
                   6049:                                                may include subquestion. 
1.423     albertel 6050: 
                   6051:   Returns:
                   6052:     $line - the modified scanline
                   6053: 
                   6054:   Side effects: 
                   6055:     $scan_data - may be updated
                   6056: 
                   6057: =cut
                   6058: 
1.82      albertel 6059: 
1.157     albertel 6060: sub scantron_fixup_scanline {
                   6061:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6062:     if ($field eq 'ID') {
                   6063: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6064: 	    return ($line,1,'New value too large');
1.157     albertel 6065: 	}
                   6066: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6067: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6068: 				     $args->{'newid'});
                   6069: 	}
                   6070: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6071: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6072: 	if ($args->{'newid'}=~/^\s*$/) {
                   6073: 	    &scan_data($scan_data,"$whichline.user",
                   6074: 		       $args->{'username'}.':'.$args->{'domain'});
                   6075: 	}
1.186     albertel 6076:     } elsif ($field eq 'CODE') {
1.192     albertel 6077: 	if ($args->{'CODE_ignore_dup'}) {
                   6078: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6079: 	}
                   6080: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6081: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6082: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6083: 		return ($line,1,'New CODE value too large');
                   6084: 	    }
                   6085: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6086: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6087: 	    }
                   6088: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6089: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6090: 	}
1.157     albertel 6091:     } elsif ($field eq 'answer') {
1.497     foxr     6092: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6093: 	my $off=$scantron_config->{'Qoff'};
                   6094: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6095: 	my $answer=${off}x$length;
                   6096: 	if ($args->{'response'} eq 'none') {
                   6097: 	    &scan_data($scan_data,
1.503     raeburn  6098: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6099: 	} else {
                   6100: 	    if ($on eq 'letter') {
                   6101: 		my @alphabet=('A'..'Z');
                   6102: 		$answer=$alphabet[$args->{'response'}];
                   6103: 	    } elsif ($on eq 'number') {
                   6104: 		$answer=$args->{'response'}+1;
                   6105: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6106: 	    } else {
1.497     foxr     6107: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6108: 	    }
1.497     foxr     6109: 	    &scan_data($scan_data,
1.503     raeburn  6110: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6111: 	}
1.497     foxr     6112: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6113: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6114:     }
                   6115:     return $line;
                   6116: }
1.423     albertel 6117: 
                   6118: =pod
                   6119: 
                   6120: =item scan_data
                   6121: 
                   6122:     Edit or look up  an item in the scan_data hash.
                   6123: 
                   6124:   Arguments:
                   6125:     $scan_data  - The hash (see scantron_getfile)
                   6126:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6127:                   scantronfilename_key).
1.423     albertel 6128:     $data        - New value of the hash entry.
                   6129:     $delete      - If true, the entry is removed from the hash.
                   6130: 
                   6131:   Returns:
                   6132:     The new value of the hash table field (undefined if deleted).
                   6133: 
                   6134: =cut
                   6135: 
                   6136: 
1.157     albertel 6137: sub scan_data {
                   6138:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6139:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6140:     if (defined($value)) {
                   6141: 	$scan_data->{$filename.'_'.$key} = $value;
                   6142:     }
                   6143:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6144:     return $scan_data->{$filename.'_'.$key};
                   6145: }
1.423     albertel 6146: 
1.495     albertel 6147: # ----- These first few routines are general use routines.----
                   6148: 
                   6149: # Return the number of occurences of a pattern in a string.
                   6150: 
                   6151: sub occurence_count {
                   6152:     my ($string, $pattern) = @_;
                   6153: 
                   6154:     my @matches = ($string =~ /$pattern/g);
                   6155: 
                   6156:     return scalar(@matches);
                   6157: }
                   6158: 
                   6159: 
                   6160: # Take a string known to have digits and convert all the
                   6161: # digits into letters in the range J,A..I.
                   6162: 
                   6163: sub digits_to_letters {
                   6164:     my ($input) = @_;
                   6165: 
                   6166:     my @alphabet = ('J', 'A'..'I');
                   6167: 
                   6168:     my @input    = split(//, $input);
                   6169:     my $output ='';
                   6170:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6171: 	if ($input[$i] =~ /\d/) {
                   6172: 	    $output .= $alphabet[$input[$i]];
                   6173: 	} else {
                   6174: 	    $output .= $input[$i];
                   6175: 	}
                   6176:     }
                   6177:     return $output;
                   6178: }
                   6179: 
1.423     albertel 6180: =pod 
                   6181: 
                   6182: =item scantron_parse_scanline
                   6183: 
                   6184:   Decodes a scanline from the selected scantron file
                   6185: 
                   6186:  Arguments:
                   6187:     line             - The text of the scantron file line to process
                   6188:     whichline        - Line number
                   6189:     scantron_config  - Hash describing the format of the scantron lines.
                   6190:     scan_data        - Hash of extra information about the scanline
                   6191:                        (see scantron_getfile for more information)
                   6192:     just_header      - True if should not process question answers but only
                   6193:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6194:3):     randomorder      - True if randomorder in use
                   6195:3):     randompick       - True if randompick in use
                   6196:3):     sequence         - Exam folder URL
                   6197:3):     master_seq       - Ref to array containing symbs in exam folder
                   6198:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6199:3):                        (corresponding values are resource objects)
                   6200:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6201:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6202:3):                        are refs to an array of resource objects, ordered
                   6203:3):                        according to order used for CODE, when randomorder
                   6204:3):                        and or randompick are in use.
                   6205:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6206:3):                        for current line to question number used for same question
                   6207:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6208:3):     startline        - Ref to hash where key is question number (0 is first)
                   6209:3):                        and value is number of first bubble line for current 
                   6210:3):                        student or code-based randompick and/or randomorder.
                   6211:3):     totalref         - Ref of scalar used to score total number of bubble
                   6212:3):                        lines needed for responses in a scan line (used when
                   6213:3):                        randompick in use. 
                   6214:3): 
1.423     albertel 6215:  Returns:
                   6216:    Hash containing the result of parsing the scanline
                   6217: 
                   6218:    Keys are all proceeded by the string 'scantron.'
                   6219: 
                   6220:        CODE    - the CODE in use for this scanline
                   6221:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6222:                  by the operator
                   6223:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6224:                             CODEs were selected, but the usage has been
                   6225:                             forced by the operator
1.556     weissno  6226:        ID  - student/employee ID
1.423     albertel 6227:        PaperID - if used, the ID number printed on the sheet when the 
                   6228:                  paper was scanned
                   6229:        FirstName - first name from the sheet
                   6230:        LastName  - last name from the sheet
                   6231: 
                   6232:      if just_header was not true these key may also exist
                   6233: 
1.447     foxr     6234:        missingerror - a list of bubble ranges that are considered to be answers
                   6235:                       to a single question that don't have any bubbles filled in.
                   6236:                       Of the form questionnumber:firstbubblenumber:count.
                   6237:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6238:                       to a single question that have more than one bubble filled in.
                   6239:                       Of the form questionnumber::firstbubblenumber:count
                   6240:    
                   6241:                 In the above, count is the number of bubble responses in the
                   6242:                 input line needed to represent the possible answers to the question.
                   6243:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6244:                 per line would have count = 2.
                   6245: 
1.423     albertel 6246:        maxquest     - the number of the last bubble line that was parsed
                   6247: 
                   6248:        (<number> starts at 1)
                   6249:        <number>.answer - zero or more letters representing the selected
                   6250:                          letters from the scanline for the bubble line 
                   6251:                          <number>.
                   6252:                          if blank there was either no bubble or there where
                   6253:                          multiple bubbles, (consult the keys missingerror and
                   6254:                          doubleerror if this is an error condition)
                   6255: 
                   6256: =cut
                   6257: 
1.82      albertel 6258: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6259:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6260:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6261:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6262: 
1.82      albertel 6263:     my %record;
1.596.2.12.2.  6(raebur 6264:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6265:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6266: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6267: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6268: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6269: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6270: 	    $record{'scantron.CODE'}=substr($data,
                   6271: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6272: 					    $$scantron_config{'CODElength'});
1.191     albertel 6273: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6274: 		$record{'scantron.useCODE'}=1;
                   6275: 	    }
1.192     albertel 6276: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6277: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6278: 	    }
1.82      albertel 6279: 	} else {
                   6280: 	    #FIXME interpret first N questions
                   6281: 	}
                   6282:     }
1.83      albertel 6283:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6284: 				  $$scantron_config{'IDlength'});
1.157     albertel 6285:     $record{'scantron.PaperID'}=
                   6286: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6287: 	       $$scantron_config{'PaperIDlength'});
                   6288:     $record{'scantron.FirstName'}=
                   6289: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6290: 	       $$scantron_config{'FirstNamelength'});
                   6291:     $record{'scantron.LastName'}=
                   6292: 	substr($data,$$scantron_config{'LastName'}-1,
                   6293: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6294:     if ($just_header) { return \%record; }
1.194     albertel 6295: 
1.82      albertel 6296:     my @alphabet=('A'..'Z');
                   6297:     my $questnum=0;
1.447     foxr     6298:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6299: 
1.596.2.12.2.  6(raebur 6300:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6301:3):     if ($randompick || $randomorder) {
                   6302:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6303:3):                                          $master_seq,$symb_to_resource,
                   6304:3):                                          $partids_by_symb,$orderedforcode,
                   6305:3):                                          $respnumlookup,$startline);
                   6306:3):         if ($total) {
                   6307:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6308:3):         }
                   6309:3):         if (ref($totalref)) {
                   6310:3):             $$totalref = $total;
                   6311:3):         }
                   6312:3):     }
                   6313:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6314:     chomp($questions);		# Get rid of any trailing \n.
                   6315:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6316:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6317:3):         my $answers_needed;
                   6318:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6319:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6320:3):         } else {
                   6321:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6322:3):         }
1.503     raeburn  6323:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6324:                              || 1;
                   6325:         $questnum++;
                   6326:         my $quest_id = $questnum;
                   6327:         my $currentquest = substr($questions,0,$answer_length);
                   6328:         $questions       = substr($questions,$answer_length);
                   6329:         if (length($currentquest) < $answer_length) { next; }
                   6330: 
1.596.2.12.2.  6(raebur 6331:3):         my $subdivided;
                   6332:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6333:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6334:3):         } else {
                   6335:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6336:3):         }
                   6337:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6338:             my $subquestnum = 1;
                   6339:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6340:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6341:             foreach my $subans (@subanswers_needed) {
                   6342:                 my $subans_length =
                   6343:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6344:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6345:                 $subquestions   = substr($subquestions,$subans_length);
                   6346:                 $quest_id = "$questnum.$subquestnum";
                   6347:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6348:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6349:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6350:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6351:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6352:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6353:                 } else {
                   6354:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6355:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6356:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6357:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6358:                 }
                   6359:                 $subquestnum ++;
                   6360:             }
                   6361:         } else {
                   6362:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6363:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6364:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6365:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6366:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6367:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6368:             } else {
                   6369:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6370:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6371:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6372:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6373:             }
                   6374:         }
                   6375:     }
                   6376:     $record{'scantron.maxquest'}=$questnum;
                   6377:     return \%record;
                   6378: }
1.447     foxr     6379: 
1.596.2.12.2.  6(raebur 6380:3): sub get_master_seq {
                   6381:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6382:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6383:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6384:3):     my $resource_error;
                   6385:3):     foreach my $resource (@{$resources}) {
                   6386:3):         my $ressymb;
                   6387:3):         if (ref($resource)) {
                   6388:3):             $ressymb = $resource->symb();
                   6389:3):             push(@{$master_seq},$ressymb);
                   6390:3):             $symb_to_resource->{$ressymb} = $resource;
                   6391:3):         } else {
                   6392:3):             $resource_error = 1;
                   6393:3):             last;
                   6394:3):         }
                   6395:3):     }
                   6396:3):     return $resource_error;
                   6397:3): }
                   6398:3): 
                   6399:3): sub get_respnum_lookups {
                   6400:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6401:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6402:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6403:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6404:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6405:3):                    (ref($startline) eq 'HASH'));
                   6406:3):     my ($user,$scancode);
                   6407:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6408:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6409:3):         $scancode = $record->{'scantron.CODE'};
                   6410:3):     } else {
                   6411:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6412:3):     }
                   6413:3):     my @mapresources =
                   6414:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6415:3):                      $orderedforcode);
                   6416:3):     my $total = 0;
                   6417:3):     my $count = 0;
                   6418:3):     foreach my $resource (@mapresources) {
                   6419:3):         my $id = $resource->id();
                   6420:3):         my $symb = $resource->symb();
                   6421:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6422:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6423:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6424:3):                 if ($respnum ne '') {
                   6425:3):                     $respnumlookup->{$count} = $respnum;
                   6426:3):                     $startline->{$count} = $total;
                   6427:3):                     $total += $bubble_lines_per_response{$respnum};
                   6428:3):                     $count ++;
                   6429:3):                 }
                   6430:3):             }
                   6431:3):         }
                   6432:3):     }
                   6433:3):     return $total;
                   6434:3): }
                   6435:3): 
1.503     raeburn  6436: sub scantron_validator_lettnum {
                   6437:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6438:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6439:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6440: 
                   6441:     # Qon 'letter' implies for each slot in currquest we have:
                   6442:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6443:     #    about anything else (esp. a value of Qoff) for missing
                   6444:     #    bubbles.
                   6445:     #
                   6446:     # Qon 'number' implies each slot gives a digit that indexes the
                   6447:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6448:     #    and * or ? for double bubbles on a single line.
                   6449:     #
1.447     foxr     6450: 
1.503     raeburn  6451:     my $matchon;
                   6452:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6453:         $matchon = '[A-Z]';
                   6454:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6455:         $matchon = '\d';
                   6456:     }
                   6457:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6458:3):     my $responsenum = $questnum-1;
                   6459:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6460:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6461:3):     }
                   6462:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6463:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6464:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6465:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6466:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6467:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6468:         my @singlelines = split('',$currquest);
                   6469:         foreach my $entry (@singlelines) {
                   6470:             $occurrences = &occurence_count($entry,$matchon);
                   6471:             if ($occurrences > 1) {
                   6472:                 last;
                   6473:             }
1.596.2.12.2.  6(raebur 6474:3):         }
1.503     raeburn  6475:     } else {
                   6476:         $occurrences = &occurence_count($currquest,$matchon); 
                   6477:     }
                   6478:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6479:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6480:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6481:             my $bubble = substr($currquest,$ans,1);
                   6482:             if ($bubble =~ /$matchon/ ) {
                   6483:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6484:                     if ($bubble == 0) {
                   6485:                         $bubble = 10; 
                   6486:                     }
                   6487:                     $record->{"scantron.$ansnum.answer"} = 
                   6488:                         $alphabet->[$bubble-1];
                   6489:                 } else {
                   6490:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6491:                 }
                   6492:             } else {
                   6493:                 $record->{"scantron.$ansnum.answer"}='';
                   6494:             }
                   6495:             $ansnum++;
                   6496:         }
                   6497:     } elsif (!defined($currquest)
                   6498:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6499:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6500:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6501:             $record->{"scantron.$ansnum.answer"}='';
                   6502:             $ansnum++;
                   6503:         }
                   6504:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6505:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6506:         }
                   6507:     } else {
                   6508:         if ($$scantron_config{'Qon'} eq 'number') {
                   6509:             $currquest = &digits_to_letters($currquest);            
                   6510:         }
                   6511:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6512:             my $bubble = substr($currquest,$ans,1);
                   6513:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6514:             $ansnum++;
                   6515:         }
                   6516:     }
                   6517:     return $ansnum;
                   6518: }
1.447     foxr     6519: 
1.503     raeburn  6520: sub scantron_validator_positional {
                   6521:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6522:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6523:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6524: 
1.503     raeburn  6525:     # Otherwise there's a positional notation;
                   6526:     # each bubble line requires Qlength items, and there are filled in
                   6527:     # bubbles for each case where there 'Qon' characters.
                   6528:     #
1.447     foxr     6529: 
1.503     raeburn  6530:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6531: 
1.503     raeburn  6532:     # If the split only gives us one element.. the full length of the
                   6533:     # answer string, no bubbles are filled in:
1.447     foxr     6534: 
1.507     raeburn  6535:     if ($answers_needed eq '') {
                   6536:         return;
                   6537:     }
                   6538: 
1.503     raeburn  6539:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6540:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6541:             $record->{"scantron.$ansnum.answer"}='';
                   6542:             $ansnum++;
                   6543:         }
                   6544:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6545:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6546:         }
                   6547:     } elsif (scalar(@array) == 2) {
                   6548:         my $location = length($array[0]);
                   6549:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6550:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6551:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6552:             if ($ans eq $line_num) {
                   6553:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6554:             } else {
                   6555:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6556:             }
                   6557:             $ansnum++;
                   6558:          }
                   6559:     } else {
                   6560:         #  If there's more than one instance of a bubble character
                   6561:         #  That's a double bubble; with positional notation we can
                   6562:         #  record all the bubbles filled in as well as the
                   6563:         #  fact this response consists of multiple bubbles.
                   6564:         #
1.596.2.12.2.  6(raebur 6565:3):         my $responsenum = $questnum-1;
                   6566:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6567:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6568:3):         }
                   6569:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6570:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6571:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6572:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6573:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6574:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6575:             my $doubleerror = 0;
                   6576:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6577:                    (!$doubleerror)) {
                   6578:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6579:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6580:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6581:                if (length(@currarray) > 2) {
                   6582:                    $doubleerror = 1;
                   6583:                } 
                   6584:             }
                   6585:             if ($doubleerror) {
                   6586:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6587:             }
                   6588:         } else {
                   6589:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6590:         }
                   6591:         my $item = $ansnum;
                   6592:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6593:             $record->{"scantron.$item.answer"} = '';
                   6594:             $item ++;
                   6595:         }
1.447     foxr     6596: 
1.503     raeburn  6597:         my @ans=@array;
                   6598:         my $i=0;
                   6599:         my $increment = 0;
                   6600:         while ($#ans) {
                   6601:             $i+=length($ans[0]) + $increment;
                   6602:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6603:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6604:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6605:             shift(@ans);
                   6606:             $increment = 1;
                   6607:         }
                   6608:         $ansnum += $answers_needed;
1.82      albertel 6609:     }
1.503     raeburn  6610:     return $ansnum;
1.82      albertel 6611: }
                   6612: 
1.423     albertel 6613: =pod
                   6614: 
                   6615: =item scantron_add_delay
                   6616: 
                   6617:    Adds an error message that occurred during the grading phase to a
                   6618:    queue of messages to be shown after grading pass is complete
                   6619: 
                   6620:  Arguments:
1.424     albertel 6621:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6622:    $scanline    - the scanline that caused the error
                   6623:    $errormesage - the error message
                   6624:    $errorcode   - a numeric code for the error
                   6625: 
                   6626:  Side Effects:
1.424     albertel 6627:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6628: 
                   6629: =cut
                   6630: 
1.82      albertel 6631: sub scantron_add_delay {
1.140     albertel 6632:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6633:     push(@$delayqueue,
                   6634: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6635: 	  'ecode' => $errorcode }
                   6636: 	 );
1.82      albertel 6637: }
                   6638: 
1.423     albertel 6639: =pod
                   6640: 
                   6641: =item scantron_find_student
                   6642: 
1.424     albertel 6643:    Finds the username for the current scanline
                   6644: 
                   6645:   Arguments:
                   6646:    $scantron_record - hash result from scantron_parse_scanline
                   6647:    $scan_data       - hash of correction information 
                   6648:                       (see &scantron_getfile() form more information)
                   6649:    $idmap           - hash from &username_to_idmap()
                   6650:    $line            - number of current scanline
                   6651:  
                   6652:   Returns:
                   6653:    Either 'username:domain' or undef if unknown
                   6654: 
1.423     albertel 6655: =cut
                   6656: 
1.82      albertel 6657: sub scantron_find_student {
1.157     albertel 6658:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6659:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6660:     if ($scanID =~ /^\s*$/) {
                   6661:  	return &scan_data($scan_data,"$line.user");
                   6662:     }
1.83      albertel 6663:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6664:  	if (lc($id) eq lc($scanID)) {
                   6665:  	    return $$idmap{$id};
                   6666:  	}
1.83      albertel 6667:     }
                   6668:     return undef;
                   6669: }
                   6670: 
1.423     albertel 6671: =pod
                   6672: 
                   6673: =item scantron_filter
                   6674: 
1.424     albertel 6675:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6676:    hidden resources was selected
                   6677: 
1.423     albertel 6678: =cut
                   6679: 
1.83      albertel 6680: sub scantron_filter {
                   6681:     my ($curres)=@_;
1.331     albertel 6682: 
                   6683:     if (ref($curres) && $curres->is_problem()) {
                   6684: 	# if the user has asked to not have either hidden
                   6685: 	# or 'randomout' controlled resources to be graded
                   6686: 	# don't include them
                   6687: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6688: 	    && $curres->randomout) {
                   6689: 	    return 0;
                   6690: 	}
1.83      albertel 6691: 	return 1;
                   6692:     }
                   6693:     return 0;
1.82      albertel 6694: }
                   6695: 
1.423     albertel 6696: =pod
                   6697: 
                   6698: =item scantron_process_corrections
                   6699: 
1.424     albertel 6700:    Gets correction information out of submitted form data and corrects
                   6701:    the scanline
                   6702: 
1.423     albertel 6703: =cut
                   6704: 
1.157     albertel 6705: sub scantron_process_corrections {
                   6706:     my ($r) = @_;
1.596.2.12.2.  1.2.3(ra 6707:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6708:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6709:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6710:     my $which=$env{'form.scantron_line'};
1.200     albertel 6711:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6712:     my ($skip,$err,$errmsg);
1.257     albertel 6713:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6714: 	$skip=1;
1.257     albertel 6715:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6716: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6717: 	    $env{'form.scantron_domain'};
1.157     albertel 6718: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6719: 	($line,$err,$errmsg)=
                   6720: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6721: 				     'ID',{'newid'=>$newid,
1.257     albertel 6722: 				    'username'=>$env{'form.scantron_username'},
                   6723: 				    'domain'=>$env{'form.scantron_domain'}});
                   6724:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6725: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6726: 	my $newCODE;
1.192     albertel 6727: 	my %args;
1.190     albertel 6728: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6729: 	    $newCODE='use_unfound';
1.190     albertel 6730: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6731: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6732: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6733: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6734: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6735: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6736: 	}
1.257     albertel 6737: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6738: 	    $args{'CODE_ignore_dup'}=1;
                   6739: 	}
                   6740: 	$args{'CODE'}=$newCODE;
1.186     albertel 6741: 	($line,$err,$errmsg)=
                   6742: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6743: 				     'CODE',\%args);
1.257     albertel 6744:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6745: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6746: 	    ($line,$err,$errmsg)=
                   6747: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6748: 					 $which,'answer',
                   6749: 					 { 'question'=>$question,
1.503     raeburn  6750: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6751:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6752: 	    if ($err) { last; }
                   6753: 	}
                   6754:     }
                   6755:     if ($err) {
1.596.2.12.2.  0(raebur 6756:3): 	$r->print(
                   6757:3):             '<p class="LC_error">'
                   6758:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6759:3):                 $errmsg)
          1(raebur 6760:3):            .'</p>');
1.157     albertel 6761:     } else {
1.200     albertel 6762: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6763: 	&scantron_putfile($scanlines,$scan_data);
                   6764:     }
                   6765: }
                   6766: 
1.423     albertel 6767: =pod
                   6768: 
                   6769: =item reset_skipping_status
                   6770: 
1.424     albertel 6771:    Forgets the current set of remember skipped scanlines (and thus
                   6772:    reverts back to considering all lines in the
                   6773:    scantron_skipped_<filename> file)
                   6774: 
1.423     albertel 6775: =cut
                   6776: 
1.200     albertel 6777: sub reset_skipping_status {
                   6778:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6779:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6780:     &scantron_putfile(undef,$scan_data);
                   6781: }
                   6782: 
1.423     albertel 6783: =pod
                   6784: 
                   6785: =item start_skipping
                   6786: 
1.424     albertel 6787:    Marks a scanline to be skipped. 
                   6788: 
1.423     albertel 6789: =cut
                   6790: 
1.376     albertel 6791: sub start_skipping {
1.200     albertel 6792:     my ($scan_data,$i)=@_;
                   6793:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6794:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6795: 	$remembered{$i}=2;
                   6796:     } else {
                   6797: 	$remembered{$i}=1;
                   6798:     }
1.200     albertel 6799:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6800: }
                   6801: 
1.423     albertel 6802: =pod
                   6803: 
                   6804: =item should_be_skipped
                   6805: 
1.424     albertel 6806:    Checks whether a scanline should be skipped.
                   6807: 
1.423     albertel 6808: =cut
                   6809: 
1.200     albertel 6810: sub should_be_skipped {
1.376     albertel 6811:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6812:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6813: 	# not redoing old skips
1.376     albertel 6814: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6815: 	return 0;
                   6816:     }
                   6817:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6818: 
                   6819:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6820: 	return 0;
                   6821:     }
1.200     albertel 6822:     return 1;
                   6823: }
                   6824: 
1.423     albertel 6825: =pod
                   6826: 
                   6827: =item remember_current_skipped
                   6828: 
1.424     albertel 6829:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6830:    file and remembers them into scan_data for later use.
                   6831: 
1.423     albertel 6832: =cut
                   6833: 
1.200     albertel 6834: sub remember_current_skipped {
                   6835:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6836:     my %to_remember;
                   6837:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6838: 	if ($scanlines->{'skipped'}[$i]) {
                   6839: 	    $to_remember{$i}=1;
                   6840: 	}
                   6841:     }
1.376     albertel 6842: 
1.200     albertel 6843:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6844:     &scantron_putfile(undef,$scan_data);
                   6845: }
                   6846: 
1.423     albertel 6847: =pod
                   6848: 
                   6849: =item check_for_error
                   6850: 
1.424     albertel 6851:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  6852:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6853:     something went wrong.
                   6854: 
1.423     albertel 6855: =cut
                   6856: 
1.200     albertel 6857: sub check_for_error {
                   6858:     my ($r,$result)=@_;
                   6859:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6860: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6861:     }
                   6862: }
1.157     albertel 6863: 
1.423     albertel 6864: =pod
                   6865: 
                   6866: =item scantron_warning_screen
                   6867: 
1.424     albertel 6868:    Interstitial screen to make sure the operator has selected the
                   6869:    correct options before we start the validation phase.
                   6870: 
1.423     albertel 6871: =cut
                   6872: 
1.203     albertel 6873: sub scantron_warning_screen {
                   6874:     my ($button_text)=@_;
1.257     albertel 6875:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  1.2.3(ra 6876:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6877:     my $CODElist;
1.284     albertel 6878:     if ($scantron_config{'CODElocation'} &&
                   6879: 	$scantron_config{'CODEstart'} &&
                   6880: 	$scantron_config{'CODElength'}) {
                   6881: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 6882:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6883: 	$CODElist=
1.492     albertel 6884: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6885: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6886:     }
1.596.2.12.2.  (raeburn 6887:):     my $lastbubblepoints;
                   6888:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6889:):         $lastbubblepoints =
                   6890:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6891:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6892:):     }
1.492     albertel 6893:     return ('
1.203     albertel 6894: <p>
1.492     albertel 6895: <span class="LC_warning">
1.596.2.12.2.  6(raebur 6896:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6897: </p>
                   6898: <table>
1.492     albertel 6899: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6900: <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 6901:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 6902: </table>
                   6903: <br />
1.596.2.12.2.  2(raebur 6904:2): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
                   6905:2): <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
1.203     albertel 6906: 
                   6907: <br />
1.492     albertel 6908: ');
1.203     albertel 6909: }
                   6910: 
1.423     albertel 6911: =pod
                   6912: 
                   6913: =item scantron_do_warning
                   6914: 
1.424     albertel 6915:    Check if the operator has picked something for all required
                   6916:    fields. Error out if something is missing.
                   6917: 
1.423     albertel 6918: =cut
                   6919: 
1.203     albertel 6920: sub scantron_do_warning {
                   6921:     my ($r)=@_;
1.324     albertel 6922:     my ($symb)=&get_symb($r);
1.203     albertel 6923:     if (!$symb) {return '';}
1.324     albertel 6924:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6925:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6926:     if ( $env{'form.selectpage'} eq '' ||
                   6927: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6928: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  6929: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6930: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6931: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6932: 	} 
1.257     albertel 6933: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  6934: 	    $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 6935: 	} 
1.257     albertel 6936: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  6937: 	    $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 6938: 	} 
                   6939:     } else {
1.265     www      6940: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.596.2.12.2.  (raeburn 6941:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6942: 	$r->print('
1.596.2.12.2.  (raeburn 6943:): '.$warning.$bubbledbyhand.'
1.492     albertel 6944: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6945: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6946: ');
1.237     albertel 6947:     }
1.352     albertel 6948:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6949:     return '';
                   6950: }
                   6951: 
1.423     albertel 6952: =pod
                   6953: 
                   6954: =item scantron_form_start
                   6955: 
1.424     albertel 6956:     html hidden input for remembering all selected grading options
                   6957: 
1.423     albertel 6958: =cut
                   6959: 
1.203     albertel 6960: sub scantron_form_start {
                   6961:     my ($max_bubble)=@_;
                   6962:     my $result= <<SCANTRONFORM;
                   6963: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6964:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6965:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6966:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6967:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6968:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6969:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6970:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6971:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6972:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6973: SCANTRONFORM
1.447     foxr     6974: 
                   6975:   my $line = 0;
                   6976:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6977:        my $chunk =
                   6978: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6979:        $chunk .=
                   6980: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6981:        $chunk .= 
                   6982:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6983:        $chunk .=
                   6984:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 6985:3):        $chunk .=
                   6986:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6987:        $result .= $chunk;
                   6988:        $line++;
1.596.2.12.2.  6(raebur 6989:3):     }
1.203     albertel 6990:     return $result;
                   6991: }
                   6992: 
1.423     albertel 6993: =pod
                   6994: 
                   6995: =item scantron_validate_file
                   6996: 
1.596.2.6  raeburn  6997:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6998: 
                   6999:     Also processes any necessary information resets that need to
                   7000:     occur before validation begins (ignore previous corrections,
                   7001:     restarting the skipped records processing)
                   7002: 
1.423     albertel 7003: =cut
                   7004: 
1.157     albertel 7005: sub scantron_validate_file {
                   7006:     my ($r) = @_;
1.324     albertel 7007:     my ($symb)=&get_symb($r);
1.157     albertel 7008:     if (!$symb) {return '';}
1.324     albertel 7009:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7010:     
1.596.2.12.2.  0(raebur 7011:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7012:     # them when doing the corrections reset
1.257     albertel 7013:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7014: 	&reset_skipping_status();
                   7015:     }
1.257     albertel 7016:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7017: 	&remember_current_skipped();
1.257     albertel 7018: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7019:     }
                   7020: 
1.257     albertel 7021:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7022: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7023: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7024: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7025: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7026:     }
1.200     albertel 7027: 
1.257     albertel 7028:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7029: 	&scantron_process_corrections($r);
                   7030:     }
1.503     raeburn  7031:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7032:     #get the student pick code ready
                   7033:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7034:     my $nav_error;
1.596.2.12.2.  1.2.3(ra 7035:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7036:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7037:     if ($nav_error) {
                   7038:         $r->print(&navmap_errormsg());
                   7039:         return '';
                   7040:     }
1.203     albertel 7041:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7042:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7043:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7044:):     }
1.157     albertel 7045:     $r->print($result);
                   7046:     
1.334     albertel 7047:     my @validate_phases=( 'sequence',
                   7048: 			  'ID',
1.157     albertel 7049: 			  'CODE',
                   7050: 			  'doublebubble',
                   7051: 			  'missingbubbles');
1.257     albertel 7052:     if (!$env{'form.validatepass'}) {
                   7053: 	$env{'form.validatepass'} = 0;
1.157     albertel 7054:     }
1.257     albertel 7055:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7056: 
1.448     foxr     7057: 
1.157     albertel 7058:     my $stop=0;
                   7059:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7060: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7061: 	$r->rflush();
1.596.2.12.2.  6(raebur 7062:3): 
1.157     albertel 7063: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7064: 	{
                   7065: 	    no strict 'refs';
                   7066: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7067: 	}
                   7068:     }
                   7069:     if (!$stop) {
1.203     albertel 7070: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  7071: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7072:                   $warning.
                   7073:                   &mt('Perform verification for each student after storage of submissions?').
                   7074:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7075:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7076:                   ('&nbsp;'x3).'<label>'.
                   7077:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7078:                   '</label></span><br />'.
                   7079:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      7080:                   &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  7081:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7082:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7083:     } else {
                   7084: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7085: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7086:     }
                   7087:     if ($stop) {
1.334     albertel 7088: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7089: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7090: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7091: 
1.492     albertel 7092: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 7093: 	} else {
1.503     raeburn  7094:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7095: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7096:             } else {
1.539     riegler  7097:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7098:             }
1.492     albertel 7099: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7100: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7101: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7102: 	}
1.157     albertel 7103:     }
1.352     albertel 7104:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 7105:     return '';
                   7106: }
                   7107: 
1.423     albertel 7108: 
                   7109: =pod
                   7110: 
                   7111: =item scantron_remove_file
                   7112: 
1.596.2.6  raeburn  7113:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7114:    scantron_original_<filename> is never removed
                   7115: 
                   7116: 
1.423     albertel 7117: =cut
                   7118: 
1.200     albertel 7119: sub scantron_remove_file {
1.192     albertel 7120:     my ($which)=@_;
1.257     albertel 7121:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7122:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7123:     my $file='scantron_';
1.200     albertel 7124:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7125: 	$file.=$which.'_';
1.192     albertel 7126:     } else {
                   7127: 	return 'refused';
                   7128:     }
1.257     albertel 7129:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7130:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7131: }
                   7132: 
1.423     albertel 7133: 
                   7134: =pod
                   7135: 
                   7136: =item scantron_remove_scan_data
                   7137: 
1.596.2.6  raeburn  7138:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7139:    data file.  (In the case that both the are doing skipped records we need
                   7140:    to remember the old skipped lines for the time being so that element
                   7141:    persists for a while.)
                   7142: 
1.423     albertel 7143: =cut
                   7144: 
1.200     albertel 7145: sub scantron_remove_scan_data {
1.257     albertel 7146:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7147:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7148:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7149:     my @todelete;
1.257     albertel 7150:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7151:     foreach my $key (@keys) {
                   7152: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7153: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7154: 		$key=~/remember_skipping/) {
                   7155: 		next;
                   7156: 	    }
1.192     albertel 7157: 	    push(@todelete,$key);
                   7158: 	}
                   7159:     }
1.200     albertel 7160:     my $result;
1.192     albertel 7161:     if (@todelete) {
1.491     albertel 7162: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7163: 				       \@todelete,$cdom,$cname);
                   7164:     } else {
                   7165: 	$result = 'ok';
1.192     albertel 7166:     }
                   7167:     return $result;
                   7168: }
                   7169: 
1.423     albertel 7170: 
                   7171: =pod
                   7172: 
                   7173: =item scantron_getfile
                   7174: 
1.596.2.6  raeburn  7175:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7176:     the scan_data hash
                   7177:   
                   7178:   Arguments:
                   7179:     None
                   7180: 
                   7181:   Returns:
                   7182:     2 hash references
                   7183: 
                   7184:      - first one has 
                   7185:          orig      -
                   7186:          corrected -
                   7187:          skipped   -  each of which points to an array ref of the specified
                   7188:                       file broken up into individual lines
                   7189:          count     - number of scanlines
                   7190:  
                   7191:      - second is the scan_data hash possible keys are
1.425     albertel 7192:        ($number refers to scanline numbered $number and thus the key affects
                   7193:         only that scanline
                   7194:         $bubline refers to the specific bubble line element and the aspects
                   7195:         refers to that specific bubble line element)
                   7196: 
                   7197:        $number.user - username:domain to use
                   7198:        $number.CODE_ignore_dup 
                   7199:                     - ignore the duplicate CODE error 
                   7200:        $number.useCODE
                   7201:                     - use the CODE in the scanline as is
                   7202:        $number.no_bubble.$bubline
                   7203:                     - it is valid that there is no bubbled in bubble
                   7204:                       at $number $bubline
                   7205:        remember_skipping
                   7206:                     - a frozen hash containing keys of $number and values
                   7207:                       of either 
                   7208:                         1 - we are on a 'do skipped records pass' and plan
                   7209:                             on processing this line
                   7210:                         2 - we are on a 'do skipped records pass' and this
                   7211:                             scanline has been marked to skip yet again
1.424     albertel 7212: 
1.423     albertel 7213: =cut
                   7214: 
1.157     albertel 7215: sub scantron_getfile {
1.200     albertel 7216:     #FIXME really would prefer a scantron directory
1.257     albertel 7217:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7218:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7219:     my $lines;
                   7220:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7221: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7222:     my %scanlines;
                   7223:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7224:     my $temp=$scanlines{'orig'};
                   7225:     $scanlines{'count'}=$#$temp;
                   7226: 
                   7227:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7228: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7229:     if ($lines eq '-1') {
                   7230: 	$scanlines{'corrected'}=[];
                   7231:     } else {
                   7232: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7233:     }
                   7234:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7235: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7236:     if ($lines eq '-1') {
                   7237: 	$scanlines{'skipped'}=[];
                   7238:     } else {
                   7239: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7240:     }
1.175     albertel 7241:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7242:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7243:     my %scan_data = @tmp;
                   7244:     return (\%scanlines,\%scan_data);
                   7245: }
                   7246: 
1.423     albertel 7247: =pod
                   7248: 
                   7249: =item lonnet_putfile
                   7250: 
1.424     albertel 7251:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7252: 
                   7253:  Arguments:
                   7254:    $contents - data to store
                   7255:    $filename - filename to store $contents into
                   7256: 
                   7257:  Returns:
                   7258:    result value from &Apache::lonnet::finishuserfileupload
                   7259: 
1.423     albertel 7260: =cut
                   7261: 
1.157     albertel 7262: sub lonnet_putfile {
                   7263:     my ($contents,$filename)=@_;
1.257     albertel 7264:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7265:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7266:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7267:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7268: 
                   7269: }
                   7270: 
1.423     albertel 7271: =pod
                   7272: 
                   7273: =item scantron_putfile
                   7274: 
1.596.2.6  raeburn  7275:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7276:     scan_data hash. (Does not modify the original version only the
                   7277:     corrected and skipped versions.
                   7278: 
                   7279:  Arguments:
                   7280:     $scanlines - hash ref that looks like the first return value from
                   7281:                  &scantron_getfile()
                   7282:     $scan_data - hash ref that looks like the second return value from
                   7283:                  &scantron_getfile()
                   7284: 
1.423     albertel 7285: =cut
                   7286: 
1.157     albertel 7287: sub scantron_putfile {
                   7288:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7289:     #FIXME really would prefer a scantron directory
1.257     albertel 7290:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7291:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7292:     if ($scanlines) {
                   7293: 	my $prefix='scantron_';
1.157     albertel 7294: # no need to update orig, shouldn't change
                   7295: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7296: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7297: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7298: 			$prefix.'corrected_'.
1.257     albertel 7299: 			$env{'form.scantron_selectfile'});
1.200     albertel 7300: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7301: 			$prefix.'skipped_'.
1.257     albertel 7302: 			$env{'form.scantron_selectfile'});
1.200     albertel 7303:     }
1.175     albertel 7304:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7305: }
                   7306: 
1.423     albertel 7307: =pod
                   7308: 
                   7309: =item scantron_get_line
                   7310: 
1.424     albertel 7311:    Returns the correct version of the scanline
                   7312: 
                   7313:  Arguments:
                   7314:     $scanlines - hash ref that looks like the first return value from
                   7315:                  &scantron_getfile()
                   7316:     $scan_data - hash ref that looks like the second return value from
                   7317:                  &scantron_getfile()
                   7318:     $i         - number of the requested line (starts at 0)
                   7319: 
                   7320:  Returns:
                   7321:    A scanline, (either the original or the corrected one if it
                   7322:    exists), or undef if the requested scanline should be
                   7323:    skipped. (Either because it's an skipped scanline, or it's an
                   7324:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7325:    pass.
                   7326: 
1.423     albertel 7327: =cut
                   7328: 
1.157     albertel 7329: sub scantron_get_line {
1.200     albertel 7330:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7331:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7332:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7333:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7334:     return $scanlines->{'orig'}[$i]; 
                   7335: }
                   7336: 
1.423     albertel 7337: =pod
                   7338: 
                   7339: =item scantron_todo_count
                   7340: 
1.424     albertel 7341:     Counts the number of scanlines that need processing.
                   7342: 
                   7343:  Arguments:
                   7344:     $scanlines - hash ref that looks like the first return value from
                   7345:                  &scantron_getfile()
                   7346:     $scan_data - hash ref that looks like the second return value from
                   7347:                  &scantron_getfile()
                   7348: 
                   7349:  Returns:
                   7350:     $count - number of scanlines to process
                   7351: 
1.423     albertel 7352: =cut
                   7353: 
1.200     albertel 7354: sub get_todo_count {
                   7355:     my ($scanlines,$scan_data)=@_;
                   7356:     my $count=0;
                   7357:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7358: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7359: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7360: 	$count++;
                   7361:     }
                   7362:     return $count;
                   7363: }
                   7364: 
1.423     albertel 7365: =pod
                   7366: 
                   7367: =item scantron_put_line
                   7368: 
1.596.2.6  raeburn  7369:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7370:     data file.
                   7371: 
                   7372:  Arguments:
                   7373:     $scanlines - hash ref that looks like the first return value from
                   7374:                  &scantron_getfile()
                   7375:     $scan_data - hash ref that looks like the second return value from
                   7376:                  &scantron_getfile()
                   7377:     $i         - line number to update
                   7378:     $newline   - contents of the updated scanline
                   7379:     $skip      - if true make the line for skipping and update the
                   7380:                  'skipped' file
                   7381: 
1.423     albertel 7382: =cut
                   7383: 
1.157     albertel 7384: sub scantron_put_line {
1.200     albertel 7385:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7386:     if ($skip) {
                   7387: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7388: 	&start_skipping($scan_data,$i);
1.157     albertel 7389: 	return;
                   7390:     }
                   7391:     $scanlines->{'corrected'}[$i]=$newline;
                   7392: }
                   7393: 
1.423     albertel 7394: =pod
                   7395: 
                   7396: =item scantron_clear_skip
                   7397: 
1.424     albertel 7398:    Remove a line from the 'skipped' file
                   7399: 
                   7400:  Arguments:
                   7401:     $scanlines - hash ref that looks like the first return value from
                   7402:                  &scantron_getfile()
                   7403:     $scan_data - hash ref that looks like the second return value from
                   7404:                  &scantron_getfile()
                   7405:     $i         - line number to update
                   7406: 
1.423     albertel 7407: =cut
                   7408: 
1.376     albertel 7409: sub scantron_clear_skip {
                   7410:     my ($scanlines,$scan_data,$i)=@_;
                   7411:     if (exists($scanlines->{'skipped'}[$i])) {
                   7412: 	undef($scanlines->{'skipped'}[$i]);
                   7413: 	return 1;
                   7414:     }
                   7415:     return 0;
                   7416: }
                   7417: 
1.423     albertel 7418: =pod
                   7419: 
                   7420: =item scantron_filter_not_exam
                   7421: 
1.424     albertel 7422:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7423:    filter out resources that are not marked as 'exam' mode
                   7424: 
1.423     albertel 7425: =cut
                   7426: 
1.334     albertel 7427: sub scantron_filter_not_exam {
                   7428:     my ($curres)=@_;
                   7429:     
                   7430:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7431: 	# if the user has asked to not have either hidden
                   7432: 	# or 'randomout' controlled resources to be graded
                   7433: 	# don't include them
                   7434: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7435: 	    && $curres->randomout) {
                   7436: 	    return 0;
                   7437: 	}
                   7438: 	return 1;
                   7439:     }
                   7440:     return 0;
                   7441: }
                   7442: 
1.423     albertel 7443: =pod
                   7444: 
                   7445: =item scantron_validate_sequence
                   7446: 
1.424     albertel 7447:     Validates the selected sequence, checking for resource that are
                   7448:     not set to exam mode.
                   7449: 
1.423     albertel 7450: =cut
                   7451: 
1.334     albertel 7452: sub scantron_validate_sequence {
                   7453:     my ($r,$currentphase) = @_;
                   7454: 
                   7455:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7456:     unless (ref($navmap)) {
                   7457:         $r->print(&navmap_errormsg());
                   7458:         return (1,$currentphase);
                   7459:     }
1.334     albertel 7460:     my (undef,undef,$sequence)=
                   7461: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7462: 
                   7463:     my $map=$navmap->getResourceByUrl($sequence);
                   7464: 
                   7465:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7466:                                     value="ignore" />');
                   7467:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7468: 	my @resources=
                   7469: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7470: 	if (@resources) {
1.596.2.12.2.  0(raebur 7471:2): 	    $r->print('<p class="LC_warning">'
                   7472:2):                .&mt('Some resources in the sequence currently are not set to'
                   7473:2):                    .' exam mode. Grading these resources currently may not'
                   7474:2):                    .' work correctly.')
                   7475:2):                .'</p>'
                   7476:2):             );
1.334     albertel 7477: 	    return (1,$currentphase);
                   7478: 	}
                   7479:     }
                   7480: 
                   7481:     return (0,$currentphase+1);
                   7482: }
                   7483: 
1.423     albertel 7484: 
                   7485: 
1.157     albertel 7486: sub scantron_validate_ID {
                   7487:     my ($r,$currentphase) = @_;
                   7488:     
                   7489:     #get student info
                   7490:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7491:     my %idmap=&username_to_idmap($classlist);
                   7492: 
                   7493:     #get scantron line setup
1.596.2.12.2.  1.2.3(ra 7494:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7495:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7496: 
                   7497:     my $nav_error;
1.596.2.12.2.  (raeburn 7498:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7499:     if ($nav_error) {
                   7500:         $r->print(&navmap_errormsg());
                   7501:         return(1,$currentphase);
                   7502:     }
1.157     albertel 7503: 
                   7504:     my %found=('ids'=>{},'usernames'=>{});
                   7505:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7506: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7507: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7508: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7509: 						 $scan_data);
                   7510: 	my $id=$$scan_record{'scantron.ID'};
                   7511: 	my $found;
                   7512: 	foreach my $checkid (keys(%idmap)) {
                   7513: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7514: 	}
                   7515: 	if ($found) {
                   7516: 	    my $username=$idmap{$found};
                   7517: 	    if ($found{'ids'}{$found}) {
                   7518: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7519: 					 $line,'duplicateID',$found);
1.194     albertel 7520: 		return(1,$currentphase);
1.157     albertel 7521: 	    } elsif ($found{'usernames'}{$username}) {
                   7522: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7523: 					 $line,'duplicateID',$username);
1.194     albertel 7524: 		return(1,$currentphase);
1.157     albertel 7525: 	    }
1.186     albertel 7526: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7527: 	    $found{'ids'}{$found}++;
                   7528: 	    $found{'usernames'}{$username}++;
                   7529: 	} else {
                   7530: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7531: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7532: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7533: 		    &scantron_get_correction($r,$i,$scan_record,
                   7534: 					     \%scantron_config,
                   7535: 					     $line,'duplicateID',$username);
1.194     albertel 7536: 		    return(1,$currentphase);
1.157     albertel 7537: 		} elsif (!defined($username)) {
                   7538: 		    &scantron_get_correction($r,$i,$scan_record,
                   7539: 					     \%scantron_config,
                   7540: 					     $line,'incorrectID');
1.194     albertel 7541: 		    return(1,$currentphase);
1.157     albertel 7542: 		}
                   7543: 		$found{'usernames'}{$username}++;
                   7544: 	    } else {
                   7545: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7546: 					 $line,'incorrectID');
1.194     albertel 7547: 		return(1,$currentphase);
1.157     albertel 7548: 	    }
                   7549: 	}
                   7550:     }
                   7551: 
                   7552:     return (0,$currentphase+1);
                   7553: }
                   7554: 
1.423     albertel 7555: 
1.157     albertel 7556: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7557:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7558:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7559: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7560: #to show both the current line and the previous one and allow skipping
                   7561: #the previous one or the current one
                   7562: 
1.333     albertel 7563:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7564:         $r->print(
                   7565:             '<p class="LC_warning">'
                   7566:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7567:                 "<b>$error</b>",
                   7568:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7569:            ."</p> \n");
1.157     albertel 7570:     } else {
1.596.2.6  raeburn  7571:         $r->print(
                   7572:             '<p class="LC_warning">'
                   7573:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7574:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7575:            ."</p> \n");
                   7576:     }
                   7577:     my $message =
                   7578:         '<p>'
                   7579:        .&mt('The ID on the form is [_1]',
                   7580:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7581:        .'<br />'
1.596.2.12  raeburn  7582:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7583:             $$scan_record{'scantron.LastName'},
                   7584:             $$scan_record{'scantron.FirstName'})
                   7585:        .'</p>';
1.242     albertel 7586: 
1.157     albertel 7587:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7588:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7589:                            # Array populated for doublebubble or
                   7590:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7591:                            # to validate radio button checking   
                   7592: 
1.157     albertel 7593:     if ($error =~ /ID$/) {
1.186     albertel 7594: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7595: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7596: 		      "</p>\n");
1.157     albertel 7597: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7598: 	    $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 7599: 	}
1.242     albertel 7600: 	$r->print($message);
1.492     albertel 7601: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7602: 	$r->print("\n<ul><li> ");
                   7603: 	#FIXME it would be nice if this sent back the user ID and
                   7604: 	#could do partial userID matches
                   7605: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7606: 				       'scantron_username','scantron_domain'));
                   7607: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7608:3): 	$r->print("\n:\n".
1.257     albertel 7609: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7610: 
                   7611: 	$r->print('</li>');
1.186     albertel 7612:     } elsif ($error =~ /CODE$/) {
                   7613: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7614: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7615: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7616: 	    $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 7617: 	}
1.596.2.6  raeburn  7618:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7619:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7620:                  ."</p>\n");
1.242     albertel 7621: 	$r->print($message);
1.596.2.6  raeburn  7622: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7623: 	$r->print("\n<br /> ");
1.194     albertel 7624: 	my $i=0;
1.273     albertel 7625: 	if ($error eq 'incorrectCODE' 
                   7626: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7627: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7628: 	    if ($closest > 0) {
                   7629: 		foreach my $testcode (@{$closest}) {
                   7630: 		    my $checked='';
1.569     bisitz   7631: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7632: 		    $r->print("
                   7633:    <label>
1.569     bisitz   7634:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7635:        ".&mt("Use the similar CODE [_1] instead.",
                   7636: 	    "<b><tt>".$testcode."</tt></b>")."
                   7637:     </label>
                   7638:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7639: 		    $r->print("\n<br />");
                   7640: 		    $i++;
                   7641: 		}
1.194     albertel 7642: 	    }
                   7643: 	}
1.273     albertel 7644: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7645: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7646: 	    $r->print("
                   7647:     <label>
1.569     bisitz   7648:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7649:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7650: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7651:     </label>");
1.273     albertel 7652: 	    $r->print("\n<br />");
                   7653: 	}
1.194     albertel 7654: 
1.188     albertel 7655: 	$r->print(<<ENDSCRIPT);
                   7656: <script type="text/javascript">
                   7657: function change_radio(field) {
1.190     albertel 7658:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7659:     var i;
                   7660:     for (i=0;i<slct.length;i++) {
                   7661:         if (slct[i].value==field) { slct[i].checked=true; }
                   7662:     }
                   7663: }
                   7664: </script>
                   7665: ENDSCRIPT
1.187     albertel 7666: 	my $href="/adm/pickcode?".
1.359     www      7667: 	   "form=".&escape("scantronupload").
                   7668: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7669: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7670: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7671: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7672: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7673: 	    $r->print("
                   7674:     <label>
                   7675:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7676:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7677: 	     "<a target='_blank' href='$href'>","</a>")."
                   7678:     </label> 
1.558     bisitz   7679:     ".&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 7680: 	    $r->print("\n<br />");
                   7681: 	}
1.492     albertel 7682: 	$r->print("
                   7683:     <label>
                   7684:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7685:        ".&mt("Use [_1] as the CODE.",
                   7686: 	     "</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 7687: 	$r->print("\n<br /><br />");
1.157     albertel 7688:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7689: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7690: 
                   7691: 	# The form field scantron_questions is acutally a list of line numbers.
                   7692: 	# represented by this form so:
                   7693: 
1.596.2.12.2.  6(raebur 7694:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7695:3):                                                 $respnumlookup,$startline);
1.497     foxr     7696: 
1.157     albertel 7697: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7698: 		  $line_list.'" />');
1.242     albertel 7699: 	$r->print($message);
1.492     albertel 7700: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7701: 	foreach my $question (@{$arg}) {
1.503     raeburn  7702: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7703:3):                                                    $scan_record, $error,
                   7704:3):                                                    $randomorder,$randompick,
                   7705:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7706:             push(@lines_to_correct,@linenums);
1.157     albertel 7707: 	}
1.503     raeburn  7708:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7709:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7710: 	$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 7711: 	$r->print($message);
1.492     albertel 7712: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7713: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7714: 
1.503     raeburn  7715: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7716: 	# a list of question numbers. Therefore:
                   7717: 	#
                   7718: 	
1.596.2.12.2.  6(raebur 7719:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7720:3):                                                 $respnumlookup,$startline);
1.497     foxr     7721: 
1.157     albertel 7722: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7723: 		  $line_list.'" />');
1.157     albertel 7724: 	foreach my $question (@{$arg}) {
1.503     raeburn  7725: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7726:3):                                                    $scan_record, $error,
                   7727:3):                                                    $randomorder,$randompick,
                   7728:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7729:             push(@lines_to_correct,@linenums);
1.157     albertel 7730: 	}
1.503     raeburn  7731:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7732:     } else {
                   7733: 	$r->print("\n<ul>");
                   7734:     }
                   7735:     $r->print("\n</li></ul>");
1.497     foxr     7736: }
                   7737: 
1.503     raeburn  7738: sub verify_bubbles_checked {
                   7739:     my (@ansnums) = @_;
                   7740:     my $ansnumstr = join('","',@ansnums);
                   7741:     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 7742:6):     &js_escape(\$warning);
1.503     raeburn  7743:     my $output = (<<ENDSCRIPT);
                   7744: <script type="text/javascript">
                   7745: function verify_bubble_radio(form) {
                   7746:     var ansnumArray = new Array ("$ansnumstr");
                   7747:     var need_bubble_count = 0;
                   7748:     for (var i=0; i<ansnumArray.length; i++) {
                   7749:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7750:             var bubble_picked = 0; 
                   7751:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7752:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7753:                     bubble_picked = 1;
                   7754:                 }
                   7755:             }
                   7756:             if (bubble_picked == 0) {
                   7757:                 need_bubble_count ++;
                   7758:             }
                   7759:         }
                   7760:     }
                   7761:     if (need_bubble_count) {
                   7762:         alert("$warning");
                   7763:         return;
                   7764:     }
                   7765:     form.submit(); 
                   7766: }
                   7767: </script>
                   7768: ENDSCRIPT
                   7769:     return $output;
                   7770: }
                   7771: 
1.497     foxr     7772: =pod
                   7773: 
                   7774: =item  questions_to_line_list
1.157     albertel 7775: 
1.497     foxr     7776: Converts a list of questions into a string of comma separated
                   7777: line numbers in the answer sheet used by the questions.  This is
                   7778: used to fill in the scantron_questions form field.
                   7779: 
                   7780:   Arguments:
                   7781:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7782:3):      randomorder  - True if randomorder in use.
                   7783:3):      randompick   - True if randompick in use.
                   7784:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7785:3):                      for current line to question number used for same question
                   7786:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7787:3):      startline    - Reference to hash where key is question number (0 is first)
                   7788:3):                     and key is number of first bubble line for current student
                   7789:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7790: 
                   7791: =cut
                   7792: 
                   7793: 
                   7794: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7795:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7796:     my @lines;
                   7797: 
1.503     raeburn  7798:     foreach my $item (@{$questions}) {
                   7799:         my $question = $item;
                   7800:         my ($first,$count,$last);
                   7801:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7802:             $question = $1;
                   7803:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7804:3):             my $responsenum = $question-1;
                   7805:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7806:3):                 $responsenum = $respnumlookup->{$question-1};
                   7807:3):                 if (ref($startline) eq 'HASH') {
                   7808:3):                     $first = $startline->{$question-1} + 1;
                   7809:3):                 }
                   7810:3):             } else {
                   7811:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7812:3):             }
          7(raebur 7813:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7814:             my $subcount = 1;
                   7815:             while ($subcount<$subquestion) {
                   7816:                 $first += $subans[$subcount-1];
                   7817:                 $subcount ++;
                   7818:             }
                   7819:             $count = $subans[$subquestion-1];
                   7820:         } else {
1.596.2.12.2.  7(raebur 7821:3):             my $responsenum = $question-1;
                   7822:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7823:3):                 $responsenum = $respnumlookup->{$question-1};
                   7824:3):                 if (ref($startline) eq 'HASH') {
                   7825:3):                     $first = $startline->{$question-1} + 1;
                   7826:3):                 }
                   7827:3):             } else {
                   7828:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7829:3):             }
                   7830:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7831:         }
1.506     raeburn  7832:         $last = $first+$count-1;
1.503     raeburn  7833:         push(@lines, ($first..$last));
1.497     foxr     7834:     }
                   7835:     return join(',', @lines);
                   7836: }
                   7837: 
                   7838: =pod 
                   7839: 
                   7840: =item prompt_for_corrections
                   7841: 
                   7842: Prompts for a potentially multiline correction to the
                   7843: user's bubbling (factors out common code from scantron_get_correction
                   7844: for multi and missing bubble cases).
                   7845: 
                   7846:  Arguments:
                   7847:    $r           - Apache request object.
                   7848:    $question    - The question number to prompt for.
                   7849:    $scan_config - The scantron file configuration hash.
                   7850:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7851:    $error       - Type of error
1.596.2.12.2.  7(raebur 7852:3):    $randomorder - True if randomorder in use.
                   7853:3):    $randompick  - True if randompick in use.
                   7854:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7855:3):                     for current line to question number used for same question
                   7856:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   7857:3):    $startline   - Reference to hash where key is question number (0 is first)
                   7858:3):                   and value is number of first bubble line for current student
                   7859:3):                   or code-based randompick and/or randomorder.
1.497     foxr     7860: 
                   7861:  Implicit inputs:
                   7862:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7863:                                   Numbered from 0 (but question numbers are from
                   7864:                                   1.
                   7865:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7866:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7867:                                   type problems render as separate sub-questions, 
1.503     raeburn  7868:                                   in exam mode. This hash contains a 
                   7869:                                   comma-separated list of the lines per 
                   7870:                                   sub-question.
1.510     raeburn  7871:    %responsetype_per_response   - essayresponse, formularesponse,
                   7872:                                   stringresponse, imageresponse, reactionresponse,
                   7873:                                   and organicresponse type problem parts can have
1.503     raeburn  7874:                                   multiple lines per response if the weight
                   7875:                                   assigned exceeds 10.  In this case, only
                   7876:                                   one bubble per line is permitted, but more 
                   7877:                                   than one line might contain bubbles, e.g.
                   7878:                                   bubbling of: line 1 - J, line 2 - J, 
                   7879:                                   line 3 - B would assign 22 points.  
1.497     foxr     7880: 
                   7881: =cut
                   7882: 
                   7883: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 7884:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7885:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7886:     my ($current_line,$lines);
                   7887:     my @linenums;
                   7888:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 7889:3):     my ($first,$responsenum);
1.503     raeburn  7890:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7891:         $question = $1;
                   7892:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 7893:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7894:3):             $responsenum = $respnumlookup->{$question-1};
                   7895:3):             if (ref($startline) eq 'HASH') {
                   7896:3):                 $first = $startline->{$question-1};
                   7897:3):             }
                   7898:3):         } else {
                   7899:3):             $responsenum = $question-1;
          7(raebur 7900:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 7901:3):         }
                   7902:3):         $current_line = $first + 1 ;
                   7903:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7904:         my $subcount = 1;
                   7905:         while ($subcount<$subquestion) {
                   7906:             $current_line += $subans[$subcount-1];
                   7907:             $subcount ++;
                   7908:         }
                   7909:         $lines = $subans[$subquestion-1];
                   7910:     } else {
1.596.2.12.2.  6(raebur 7911:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7912:3):             $responsenum = $respnumlookup->{$question-1};
                   7913:3):             if (ref($startline) eq 'HASH') {
                   7914:3):                 $first = $startline->{$question-1};
                   7915:3):             }
                   7916:3):         } else {
                   7917:3):             $responsenum = $question-1;
                   7918:3):             $first = $first_bubble_line{$responsenum};
                   7919:3):         }
                   7920:3):         $current_line = $first + 1;
                   7921:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7922:     }
1.497     foxr     7923:     if ($lines > 1) {
1.503     raeburn  7924:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 7925:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7926:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7927:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7928:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7929:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7930:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 7931: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  7932:         } else {
                   7933:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7934:         }
1.497     foxr     7935:     }
                   7936:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7937:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 7938:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7939: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7940:         push(@linenums,$current_line);
1.497     foxr     7941: 	$current_line++;
                   7942:     }
                   7943:     if ($lines > 1) {
                   7944: 	$r->print("<hr /><br />");
                   7945:     }
1.503     raeburn  7946:     return @linenums;
1.157     albertel 7947: }
1.423     albertel 7948: 
                   7949: =pod
                   7950: 
                   7951: =item scantron_bubble_selector
                   7952:   
                   7953:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7954:    possibly showing the existing the selected bubbles if known
1.423     albertel 7955: 
                   7956:  Arguments:
                   7957:     $r           - Apache request object
1.596.2.12.2.  1.2.3(ra 7958:eb-19):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     7959:     $line        - Number of the line being displayed.
1.503     raeburn  7960:     $questionnum - Question number (may include subquestion)
                   7961:     $error       - Type of error.
1.497     foxr     7962:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7963: 
                   7964: =cut
                   7965: 
1.157     albertel 7966: sub scantron_bubble_selector {
1.503     raeburn  7967:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7968:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7969: 
                   7970:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 7971:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   7972:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7973:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7974:):             $max=$$scan_config{'BubblesPerRow'};
                   7975:):             if (($scmode eq 'number') && ($max > 10)) {
                   7976:):                 $max = 10;
                   7977:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   7978:):                 $max = 26;
                   7979:):             }
                   7980:):         } else {
                   7981:):             $max = 10;
                   7982:):         }
                   7983:):     }
1.274     albertel 7984: 
1.157     albertel 7985:     my @alphabet=('A'..'Z');
1.503     raeburn  7986:     $r->print(&Apache::loncommon::start_data_table().
                   7987:               &Apache::loncommon::start_data_table_row());
                   7988:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7989:     for (my $i=0;$i<$max+1;$i++) {
                   7990: 	$r->print("\n".'<td align="center">');
                   7991: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7992: 	else { $r->print('&nbsp;'); }
                   7993: 	$r->print('</td>');
                   7994:     }
1.503     raeburn  7995:     $r->print(&Apache::loncommon::end_data_table_row().
                   7996:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7997:     for (my $i=0;$i<$max;$i++) {
                   7998: 	$r->print("\n".
                   7999: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8000: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8001:     }
1.503     raeburn  8002:     my $nobub_checked = ' ';
                   8003:     if ($error eq 'missingbubble') {
                   8004:         $nobub_checked = ' checked = "checked" ';
                   8005:     }
                   8006:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8007: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8008:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8009:               $line.'" value="'.$questionnum.'" /></td>');
                   8010:     $r->print(&Apache::loncommon::end_data_table_row().
                   8011:               &Apache::loncommon::end_data_table());
1.157     albertel 8012: }
                   8013: 
1.423     albertel 8014: =pod
                   8015: 
                   8016: =item num_matches
                   8017: 
1.424     albertel 8018:    Counts the number of characters that are the same between the two arguments.
                   8019: 
                   8020:  Arguments:
                   8021:    $orig - CODE from the scanline
                   8022:    $code - CODE to match against
                   8023: 
                   8024:  Returns:
                   8025:    $count - integer count of the number of same characters between the
                   8026:             two arguments
                   8027: 
1.423     albertel 8028: =cut
                   8029: 
1.194     albertel 8030: sub num_matches {
                   8031:     my ($orig,$code) = @_;
                   8032:     my @code=split(//,$code);
                   8033:     my @orig=split(//,$orig);
                   8034:     my $same=0;
                   8035:     for (my $i=0;$i<scalar(@code);$i++) {
                   8036: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8037:     }
                   8038:     return $same;
                   8039: }
                   8040: 
1.423     albertel 8041: =pod
                   8042: 
                   8043: =item scantron_get_closely_matching_CODEs
                   8044: 
1.424     albertel 8045:    Cycles through all CODEs and finds the set that has the greatest
                   8046:    number of same characters as the provided CODE
                   8047: 
                   8048:  Arguments:
                   8049:    $allcodes - hash ref returned by &get_codes()
                   8050:    $CODE     - CODE from the current scanline
                   8051: 
                   8052:  Returns:
                   8053:    2 element list
                   8054:     - first elements is number of how closely matching the best fit is 
                   8055:       (5 means best set has 5 matching characters)
                   8056:     - second element is an arrary ref containing the set of valid CODEs
                   8057:       that best fit the passed in CODE
                   8058: 
1.423     albertel 8059: =cut
                   8060: 
1.194     albertel 8061: sub scantron_get_closely_matching_CODEs {
                   8062:     my ($allcodes,$CODE)=@_;
                   8063:     my @CODEs;
                   8064:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8065: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8066:     }
                   8067: 
                   8068:     return ($#CODEs,$CODEs[-1]);
                   8069: }
                   8070: 
1.423     albertel 8071: =pod
                   8072: 
                   8073: =item get_codes
                   8074: 
1.424     albertel 8075:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8076:    set of remembered CODEs.
                   8077: 
                   8078:  Arguments:
                   8079:   $old_name - name of the set of remembered CODEs
                   8080:   $cdom     - domain of the course
                   8081:   $cnum     - internal course name
                   8082: 
                   8083:  Returns:
                   8084:   %allcodes - keys are the valid CODEs, values are all 1
                   8085: 
1.423     albertel 8086: =cut
                   8087: 
1.194     albertel 8088: sub get_codes {
1.280     foxr     8089:     my ($old_name, $cdom, $cnum) = @_;
                   8090:     if (!$old_name) {
                   8091: 	$old_name=$env{'form.scantron_CODElist'};
                   8092:     }
                   8093:     if (!$cdom) {
                   8094: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8095:     }
                   8096:     if (!$cnum) {
                   8097: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8098:     }
1.278     albertel 8099:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8100: 				    $cdom,$cnum);
                   8101:     my %allcodes;
                   8102:     if ($result{"type\0$old_name"} eq 'number') {
                   8103: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8104:     } else {
                   8105: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8106:     }
1.194     albertel 8107:     return %allcodes;
                   8108: }
                   8109: 
1.423     albertel 8110: =pod
                   8111: 
                   8112: =item scantron_validate_CODE
                   8113: 
1.424     albertel 8114:    Validates all scanlines in the selected file to not have any
                   8115:    invalid or underspecified CODEs and that none of the codes are
                   8116:    duplicated if this was requested.
                   8117: 
1.423     albertel 8118: =cut
                   8119: 
1.157     albertel 8120: sub scantron_validate_CODE {
                   8121:     my ($r,$currentphase) = @_;
1.596.2.12.2.  1.2.3(ra 8122:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8123:     if ($scantron_config{'CODElocation'} &&
                   8124: 	$scantron_config{'CODEstart'} &&
                   8125: 	$scantron_config{'CODElength'}) {
1.257     albertel 8126: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8127: 	    &FIXME_blow_up()
                   8128: 	}
                   8129:     } else {
                   8130: 	return (0,$currentphase+1);
                   8131:     }
                   8132:     
                   8133:     my %usedCODEs;
                   8134: 
1.194     albertel 8135:     my %allcodes=&get_codes();
1.186     albertel 8136: 
1.582     raeburn  8137:     my $nav_error;
1.596.2.12.2.  (raeburn 8138:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8139:     if ($nav_error) {
                   8140:         $r->print(&navmap_errormsg());
                   8141:         return(1,$currentphase);
                   8142:     }
1.447     foxr     8143: 
1.186     albertel 8144:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8145:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8146: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8147: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8148: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8149: 						 $scan_data);
                   8150: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8151: 	my $error=0;
1.224     albertel 8152: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8153: 	    &scantron_get_correction($r,$i,$scan_record,
                   8154: 				     \%scantron_config,
                   8155: 				     $line,'incorrectCODE',\%allcodes);
                   8156: 	    return(1,$currentphase);
                   8157: 	}
1.221     albertel 8158: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8159: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8160: 	    &scantron_get_correction($r,$i,$scan_record,
                   8161: 				     \%scantron_config,
1.194     albertel 8162: 				     $line,'incorrectCODE',\%allcodes);
                   8163: 	    return(1,$currentphase);
1.186     albertel 8164: 	}
1.214     albertel 8165: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8166: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8167: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8168: 	    &scantron_get_correction($r,$i,$scan_record,
                   8169: 				     \%scantron_config,
1.194     albertel 8170: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8171: 	    return(1,$currentphase);
1.186     albertel 8172: 	}
1.524     raeburn  8173: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8174:     }
1.157     albertel 8175:     return (0,$currentphase+1);
                   8176: }
                   8177: 
1.423     albertel 8178: =pod
                   8179: 
                   8180: =item scantron_validate_doublebubble
                   8181: 
1.424     albertel 8182:    Validates all scanlines in the selected file to not have any
                   8183:    bubble lines with multiple bubbles marked.
                   8184: 
1.423     albertel 8185: =cut
                   8186: 
1.157     albertel 8187: sub scantron_validate_doublebubble {
                   8188:     my ($r,$currentphase) = @_;
                   8189:     #get student info
                   8190:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8191:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8192:3):     my (undef,undef,$sequence)=
                   8193:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8194: 
                   8195:     #get scantron line setup
1.596.2.12.2.  1.2.3(ra 8196:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8197:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8198:3): 
                   8199:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8200:3):     unless (ref($navmap)) {
                   8201:3):         $r->print(&navmap_errormsg());
                   8202:3):         return(1,$currentphase);
                   8203:3):     }
                   8204:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8205:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8206:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8207:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8208:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8209:3): 
1.583     raeburn  8210:     my $nav_error;
1.596.2.12.2.  6(raebur 8211:3):     if (ref($map)) {
                   8212:3):         $randomorder = $map->randomorder();
                   8213:3):         $randompick = $map->randompick();
                   8214:3):         if ($randomorder || $randompick) {
                   8215:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8216:3):             if ($nav_error) {
                   8217:3):                 $r->print(&navmap_errormsg());
                   8218:3):                 return(1,$currentphase);
                   8219:3):             }
                   8220:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8221:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8222:3):         }
                   8223:3):     } else {
                   8224:3):         $r->print(&navmap_errormsg());
                   8225:3):         return(1,$currentphase);
                   8226:3):     }
                   8227:3): 
          (raeburn 8228:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8229:     if ($nav_error) {
                   8230:         $r->print(&navmap_errormsg());
                   8231:         return(1,$currentphase);
                   8232:     }
1.447     foxr     8233: 
1.157     albertel 8234:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8235: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8236: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8237: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8238:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8239:3):                                                  $randompick,$sequence,\@master_seq,
                   8240:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8241:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8242: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8243: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8244: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8245:3): 				 $$scan_record{'scantron.doubleerror'},
                   8246:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8247:     	return (1,$currentphase);
                   8248:     }
                   8249:     return (0,$currentphase+1);
                   8250: }
                   8251: 
1.423     albertel 8252: 
1.503     raeburn  8253: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8254:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8255:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8256: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8257: 	&restore_bubble_lines();
1.257     albertel 8258: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8259:     }
1.330     albertel 8260: 
1.447     foxr     8261:     my (undef, undef, $sequence) =
1.257     albertel 8262: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8263: 
1.447     foxr     8264:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8265:     unless (ref($navmap)) {
                   8266:         if (ref($nav_error)) {
                   8267:             $$nav_error = 1;
                   8268:         }
1.591     raeburn  8269:         return;
1.582     raeburn  8270:     }
1.191     albertel 8271:     my $map=$navmap->getResourceByUrl($sequence);
                   8272:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8273:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8274: 
                   8275:     &Apache::lonxml::clear_problem_counter();
                   8276: 
1.557     raeburn  8277:     my $uname       = $env{'user.name'};
                   8278:     my $udom        = $env{'user.domain'};
1.435     foxr     8279:     my $cid         = $env{'request.course.id'};
                   8280:     my $total_lines = 0;
                   8281:     %bubble_lines_per_response = ();
1.447     foxr     8282:     %first_bubble_line         = ();
1.503     raeburn  8283:     %subdivided_bubble_lines   = ();
                   8284:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8285:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8286: 
1.447     foxr     8287:     my $response_number = 0;
                   8288:     my $bubble_line     = 0;
1.191     albertel 8289:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8290:3):         my $resid = $resource->id();
          (raeburn 8291:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8292:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8293:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8294: 	    foreach my $part_id (@{$parts}) {
                   8295:                 my $lines;
                   8296: 
                   8297: 	        # TODO - make this a persistent hash not an array.
                   8298: 
                   8299:                 # optionresponse, matchresponse and rankresponse type items 
                   8300:                 # render as separate sub-questions in exam mode.
                   8301:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8302:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8303:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8304:                     my ($numbub,$numshown);
                   8305:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8306:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8307:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8308:                         }
                   8309:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8310:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8311:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8312:                         }
                   8313:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8314:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8315:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8316:                         }
                   8317:                     }
                   8318:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8319:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8320:                     }
1.596.2.12.2.  (raeburn 8321:):                     my $bubbles_per_row =
                   8322:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8323:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8324:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8325:                         $inner_bubble_lines++;
                   8326:                     }
                   8327:                     for (my $i=0; $i<$numshown; $i++) {
                   8328:                         $subdivided_bubble_lines{$response_number} .= 
                   8329:                             $inner_bubble_lines.',';
                   8330:                     }
                   8331:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8332:                     $lines = $numshown * $inner_bubble_lines;
                   8333:                 } else {
                   8334:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8335:):                 }
1.542     raeburn  8336: 
                   8337:                 $first_bubble_line{$response_number} = $bubble_line;
                   8338: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8339:                 $responsetype_per_response{$response_number} = 
                   8340:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8341:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8342: 	        $response_number++;
                   8343: 
                   8344: 	        $bubble_line +=  $lines;
                   8345: 	        $total_lines +=  $lines;
                   8346: 	    }
                   8347:         }
                   8348:     }
1.552     raeburn  8349:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8350: 
                   8351:     &save_bubble_lines();
                   8352:     $env{'form.scantron_maxbubble'} =
                   8353: 	$total_lines;
                   8354:     return $env{'form.scantron_maxbubble'};
                   8355: }
1.523     raeburn  8356: 
1.596.2.12.2.  (raeburn 8357:): sub bubblesheet_bubbles_per_row {
                   8358:):     my ($scantron_config) = @_;
                   8359:):     my $bubbles_per_row;
                   8360:):     if (ref($scantron_config) eq 'HASH') {
                   8361:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8362:):     }
                   8363:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8364:):         $bubbles_per_row = 10;
                   8365:):     }
                   8366:):     return $bubbles_per_row;
                   8367:): }
                   8368:): 
1.157     albertel 8369: sub scantron_validate_missingbubbles {
                   8370:     my ($r,$currentphase) = @_;
                   8371:     #get student info
                   8372:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8373:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8374:3):     my (undef,undef,$sequence)=
                   8375:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8376: 
                   8377:     #get scantron line setup
1.596.2.12.2.  1.2.3(ra 8378:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8379:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8380:3): 
                   8381:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8382:3):     unless (ref($navmap)) {
                   8383:3):         $r->print(&navmap_errormsg());
                   8384:3):         return(1,$currentphase);
                   8385:3):     }
                   8386:3): 
                   8387:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8388:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8389:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8390:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8391:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8392:3): 
1.582     raeburn  8393:     my $nav_error;
1.596.2.12.2.  6(raebur 8394:3):     if (ref($map)) {
                   8395:3):         $randomorder = $map->randomorder();
                   8396:3):         $randompick = $map->randompick();
          7(raebur 8397:3):         if ($randomorder || $randompick) {
                   8398:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8399:3):             if ($nav_error) {
                   8400:3):                 $r->print(&navmap_errormsg());
                   8401:3):                 return(1,$currentphase);
                   8402:3):             }
                   8403:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8404:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8405:3):         }
          6(raebur 8406:3):     } else {
                   8407:3):         $r->print(&navmap_errormsg());
          7(raebur 8408:3):         return(1,$currentphase);
          6(raebur 8409:3):     }
                   8410:3): 
                   8411:3): 
          (raeburn 8412:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8413:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8414:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8415:         return(1,$currentphase);
                   8416:     }
1.596.2.12.2.  6(raebur 8417:3): 
1.157     albertel 8418:     if (!$max_bubble) { $max_bubble=2**31; }
                   8419:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8420: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8421: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8422:3):         my $scan_record =
                   8423:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8424:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8425:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8426:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8427: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8428: 	my @to_correct;
1.470     foxr     8429: 	
                   8430: 	# Probably here's where the error is...
                   8431: 
1.157     albertel 8432: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8433:             my $lastbubble;
                   8434:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8435:3):                 my $question = $1;
                   8436:3):                 my $subquestion = $2;
                   8437:3):                 my ($first,$responsenum);
                   8438:3):                 if ($randomorder || $randompick) {
                   8439:3):                     $responsenum = $respnumlookup{$question-1};
                   8440:3):                     $first = $startline{$question-1};
                   8441:3):                 } else {
                   8442:3):                     $responsenum = $question-1;
                   8443:3):                     $first = $first_bubble_line{$responsenum};
                   8444:3):                 }
                   8445:3):                 if (!defined($first)) { next; }
          7(raebur 8446:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8447:3):                 my $subcount = 1;
                   8448:3):                 while ($subcount<$subquestion) {
                   8449:3):                     $first += $subans[$subcount-1];
                   8450:3):                     $subcount ++;
                   8451:3):                 }
                   8452:3):                 my $count = $subans[$subquestion-1];
                   8453:3):                 $lastbubble = $first + $count;
1.505     raeburn  8454:             } else {
1.596.2.12.2.  6(raebur 8455:3):                 my ($first,$responsenum);
                   8456:3):                 if ($randomorder || $randompick) {
                   8457:3):                     $responsenum = $respnumlookup{$missing-1};
                   8458:3):                     $first = $startline{$missing-1};
                   8459:3):                 } else {
                   8460:3):                     $responsenum = $missing-1;
                   8461:3):                     $first = $first_bubble_line{$responsenum};
                   8462:3):                 }
                   8463:3):                 if (!defined($first)) { next; }
                   8464:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8465:             }
                   8466:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8467: 	    push(@to_correct,$missing);
                   8468: 	}
                   8469: 	if (@to_correct) {
                   8470: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8471:3): 				     $line,'missingbubble',\@to_correct,
                   8472:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8473:3):                                      \%startline);
1.157     albertel 8474: 	    return (1,$currentphase);
                   8475: 	}
                   8476: 
                   8477:     }
                   8478:     return (0,$currentphase+1);
                   8479: }
                   8480: 
1.596.2.12.2.  (raeburn 8481:): sub hand_bubble_option {
                   8482:):     my (undef, undef, $sequence) =
                   8483:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8484:):     return if ($sequence eq '');
                   8485:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8486:):     unless (ref($navmap)) {
                   8487:):         return;
                   8488:):     }
                   8489:):     my $needs_hand_bubbles;
                   8490:):     my $map=$navmap->getResourceByUrl($sequence);
                   8491:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8492:):     foreach my $res (@resources) {
                   8493:):         if (ref($res)) {
                   8494:):             if ($res->is_problem()) {
                   8495:):                 my $partlist = $res->parts();
                   8496:):                 foreach my $part (@{ $partlist }) {
                   8497:):                     my @types = $res->responseType($part);
                   8498:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8499:):                         $needs_hand_bubbles = 1;
                   8500:):                         last;
                   8501:):                     }
                   8502:):                 }
                   8503:):             }
                   8504:):         }
                   8505:):     }
                   8506:):     if ($needs_hand_bubbles) {
          1.2.3(ra 8507:eb-19):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8508:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8509:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8510:):                &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 />').
                   8511:):                '<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 8512:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8513:):     }
                   8514:):     return;
                   8515:): }
1.423     albertel 8516: 
1.82      albertel 8517: sub scantron_process_students {
1.75      albertel 8518:     my ($r) = @_;
1.513     foxr     8519: 
1.257     albertel 8520:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 8521:     my ($symb)=&get_symb($r);
1.513     foxr     8522:     if (!$symb) {
                   8523: 	return '';
                   8524:     }
1.324     albertel 8525:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8526: 
1.596.2.12.2.  1.2.3(ra 8527:eb-19):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8528:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8529:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8530:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8531:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8532:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8533:     unless (ref($navmap)) {
                   8534:         $r->print(&navmap_errormsg());
                   8535:         return '';
1.596.2.12.2.  6(raebur 8536:3):     }
1.83      albertel 8537:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8538:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8539:3):         %grader_randomlists_by_symb);
          1(raebur 8540:2):     if (ref($map)) {
                   8541:2):         $randomorder = $map->randomorder();
          6(raebur 8542:3):         $randompick = $map->randompick();
                   8543:3):     } else {
                   8544:3):         $r->print(&navmap_errormsg());
                   8545:3):         return '';
          1(raebur 8546:2):     }
          6(raebur 8547:3):     my $nav_error;
1.83      albertel 8548:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8549:3):     if ($randomorder || $randompick) {
                   8550:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8551:3):         if ($nav_error) {
                   8552:3):             $r->print(&navmap_errormsg());
                   8553:3):             return '';
1.586     raeburn  8554:         }
                   8555:     }
1.596.2.12.2.  6(raebur 8556:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8557:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8558: 
1.554     raeburn  8559:     my ($uname,$udom);
1.82      albertel 8560:     my $result= <<SCANTRONFORM;
1.81      albertel 8561: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8562:   <input type="hidden" name="command" value="scantron_configphase" />
                   8563:   $default_form_data
                   8564: SCANTRONFORM
1.82      albertel 8565:     $r->print($result);
                   8566: 
                   8567:     my @delayqueue;
1.542     raeburn  8568:     my (%completedstudents,%scandata);
1.140     albertel 8569:     
1.520     www      8570:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8571:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8572:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.140     albertel 8573:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8574: 					  'Processing first student');
1.542     raeburn  8575:     $r->print('<br />');
1.140     albertel 8576:     my $start=&Time::HiRes::time();
1.158     albertel 8577:     my $i=-1;
1.542     raeburn  8578:     my $started;
1.447     foxr     8579: 
1.596.2.12.2.  (raeburn 8580:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8581:     if ($nav_error) {
                   8582:         $r->print(&navmap_errormsg());
                   8583:         return '';
                   8584:     }
                   8585: 
1.513     foxr     8586:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8587:     # the user and return.
                   8588: 
                   8589:     if ($ssi_error) {
                   8590: 	$r->print("</form>");
                   8591: 	&ssi_print_error($r);
                   8592: 	$r->print(&show_grading_menu_form($symb));
1.520     www      8593:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8594: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8595:     }
1.447     foxr     8596: 
1.596.2.12.2.  1.2.3(ra 8597:eb-19):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8598:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8599:3):     my %orderedforcode;
1.542     raeburn  8600: 
1.157     albertel 8601:     while ($i<$scanlines->{'count'}) {
                   8602:  	($uname,$udom)=('','');
                   8603:  	$i++;
1.200     albertel 8604:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8605:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8606: 	if ($started) {
                   8607: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8608: 						     'last student');
                   8609: 	}
                   8610: 	$started=1;
1.596.2.12.2.  6(raebur 8611:3):         my %respnumlookup = ();
                   8612:3):         my %startline = ();
                   8613:3):         my $total;
1.157     albertel 8614:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8615:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8616:3):                                                  $randompick,$sequence,\@master_seq,
                   8617:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8618:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8619:3):                                                  \$total);
1.157     albertel 8620:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8621:  					      \%idmap,$i)) {
                   8622:   	    &scantron_add_delay(\@delayqueue,$line,
                   8623:  				'Unable to find a student that matches',1);
                   8624:  	    next;
                   8625:   	}
                   8626:  	if (exists $completedstudents{$uname}) {
                   8627:  	    &scantron_add_delay(\@delayqueue,$line,
                   8628:  				'Student '.$uname.' has multiple sheets',2);
                   8629:  	    next;
                   8630:  	}
1.596.2.12.2.  1(raebur 8631:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8632:2):         my $user = $uname.':'.$usec;
1.157     albertel 8633:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8634: 
1.596.2.12.2.  1(raebur 8635:2):         my $scancode;
                   8636:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8637:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8638:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8639:2):         } else {
                   8640:2):             $scancode = '';
                   8641:2):         }
                   8642:2): 
                   8643:2):         my @mapresources = @resources;
          6(raebur 8644:3):         if ($randomorder || $randompick) {
          1(raebur 8645:2):             @mapresources =
          6(raebur 8646:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8647:3):                              \%orderedforcode);
          1(raebur 8648:2):         }
1.586     raeburn  8649:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8650:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8651:             my $ressymb;
                   8652:             if (ref($resource)) {
                   8653:                 $ressymb = $resource->symb();
                   8654:             } else {
                   8655:                 $res_error = 1;
                   8656:                 last;
                   8657:             }
1.557     raeburn  8658:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8659:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 8660:7):                 my $currcode;
                   8661:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8662:7):                     $currcode = $scancode;
                   8663:7):                 }
1.557     raeburn  8664:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8665:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 8666:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   8667:7):                                               $currcode);
1.557     raeburn  8668:                 $partids_by_symb{$ressymb} = $parts;
                   8669:             } else {
                   8670:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8671:             }
1.554     raeburn  8672:         }
                   8673: 
1.586     raeburn  8674:         if ($res_error) {
                   8675:             &scantron_add_delay(\@delayqueue,$line,
                   8676:                                 'An error occurred while grading student '.$uname,2);
                   8677:             next;
                   8678:         }
                   8679: 
1.330     albertel 8680: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8681:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8682: 
                   8683: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8684: 	    &scantron_putfile($scanlines,$scan_data);
                   8685: 	}
1.161     albertel 8686: 	
1.542     raeburn  8687:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8688:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8689:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8690:3):                                    \%respnumlookup,\%startline) 
                   8691:3):             eq 'ssi_error') {
1.542     raeburn  8692:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8693:             $r->print("</form>");
                   8694:             &ssi_print_error($r);
                   8695:             $r->print(&show_grading_menu_form($symb));
                   8696:             &Apache::lonnet::remove_lock($lock);
                   8697:             return '';      # Why return ''?  Beats me.
                   8698:         }
1.513     foxr     8699: 
1.596.2.12.2.  6(raebur 8700:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8701:3):             my $parmresult =
                   8702:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8703:3):                                                        '0_examcode',2,$scancode,
                   8704:3):                                                        'string_examcode',$uname,
                   8705:3):                                                        $udom);
                   8706:3):         }
1.140     albertel 8707: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8708:         if ($env{'form.verifyrecord'}) {
                   8709:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8710:3):             if ($randompick) {
                   8711:3):                 if ($total) {
                   8712:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8713:3):                 }
                   8714:3):             }
                   8715:3): 
1.542     raeburn  8716:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8717:             chomp($studentdata);
                   8718:             $studentdata =~ s/\r$//;
                   8719:             my $studentrecord = '';
                   8720:             my $counter = -1;
1.596.2.12.2.  1(raebur 8721:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8722:                 my $ressymb = $resource->symb();
1.542     raeburn  8723:                 ($counter,my $recording) =
                   8724:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8725:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8726:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8727:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8728:                 $studentrecord .= $recording;
                   8729:             }
                   8730:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8731:                 &Apache::lonxml::clear_problem_counter();
                   8732:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8733:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8734:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8735:3):                                            \%respnumlookup,\%startline)
                   8736:3):                     eq 'ssi_error') {
1.554     raeburn  8737:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8738:                     $r->print("</form>");
                   8739:                     &ssi_print_error($r);
                   8740:                     $r->print(&show_grading_menu_form($symb));
                   8741:                     &Apache::lonnet::remove_lock($lock);
                   8742:                     delete($completedstudents{$uname});
                   8743:                     return '';
                   8744:                 }
1.542     raeburn  8745:                 $counter = -1;
                   8746:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8747:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8748:                     my $ressymb = $resource->symb();
1.542     raeburn  8749:                     ($counter,my $recording) =
                   8750:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8751:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8752:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8753:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8754:3):                                                  \%startline);
1.542     raeburn  8755:                     $studentrecord .= $recording;
                   8756:                 }
                   8757:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8758:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8759:                     if ($scancode eq '') {
1.596.2.6  raeburn  8760:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8761:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8762:                     } else {
1.596.2.6  raeburn  8763:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8764:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8765:                     }
                   8766:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8767:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8768:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8769:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8770:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8771:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8772:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8773:                               &Apache::loncommon::end_data_table_row().
                   8774:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8775:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8776:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8777:                               &Apache::loncommon::end_data_table_row().
                   8778:                               &Apache::loncommon::end_data_table().'</p>');
                   8779:                 } else {
                   8780:                     $r->print('<br /><span class="LC_warning">'.
                   8781:                              &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 />'.
                   8782:                              &mt("As a consequence, this user's submission history records two tries.").
                   8783:                                  '</span><br />');
                   8784:                 }
                   8785:             }
                   8786:         }
1.543     raeburn  8787:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8788:     } continue {
1.330     albertel 8789: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8790: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8791:     }
1.140     albertel 8792:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8793:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8794: #    my $lasttime = &Time::HiRes::time()-$start;
                   8795: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8796: 
1.200     albertel 8797:     $r->print("</form>");
1.324     albertel 8798:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8799:     return '';
1.75      albertel 8800: }
1.157     albertel 8801: 
1.557     raeburn  8802: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8803:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8804:):         $bubbles_per_row) = @_;
1.557     raeburn  8805:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8806:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8807:         foreach my $resource (@{$resources}) {
                   8808:             my $ressymb = $resource->symb();
                   8809:             my ($analysis,$parts) =
                   8810:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8811:):                                           $env{'user.name'},$env{'user.domain'},
                   8812:):                                           1,$bubbles_per_row);
1.557     raeburn  8813:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8814:             if (ref($analysis) eq 'HASH') {
                   8815:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8816:                     $grader_randomlists_by_symb->{$ressymb} =
                   8817:                         $analysis->{'parts_withrandomlist'};
                   8818:                 }
                   8819:             }
                   8820:         }
                   8821:     }
                   8822:     return;
                   8823: }
                   8824: 
1.596.2.12.2.  1(raebur 8825:2): =pod
                   8826:2): 
                   8827:2): =item users_order
                   8828:2): 
                   8829:2):   Returns array of resources in current map, ordered based on either CODE,
                   8830:2):   if this is a CODEd exam, or based on student's identity if this is a
                   8831:2):   "NAMEd" exam.
                   8832:2): 
          6(raebur 8833:3):   Should be used when randomorder and/or randompick applied when the 
                   8834:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   8835:3):   for the version of the exam the student received.
          1(raebur 8836:2): 
                   8837:2): =cut
                   8838:2): 
                   8839:2): sub users_order  {
          6(raebur 8840:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 8841:2):     my @mapresources;
          6(raebur 8842:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 8843:2):         return @mapresources;
                   8844:2):     }
          6(raebur 8845:3):     if ($scancode) {
                   8846:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8847:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   8848:3):         } else {
                   8849:3):             $env{'form.CODE'} = $scancode;
                   8850:3):             my $actual_seq =
                   8851:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8852:3):                                                                $master_seq,
                   8853:3):                                                                $user,$scancode,1);
                   8854:3):             if (ref($actual_seq) eq 'ARRAY') {
                   8855:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8856:3):                 if (ref($orderedforcode) eq 'HASH') {
                   8857:3):                     if (@mapresources > 0) {
                   8858:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   8859:3):                     }
                   8860:3):                 }
                   8861:3):             }
                   8862:3):             delete($env{'form.CODE'});
          1(raebur 8863:2):         }
                   8864:2):     } else {
                   8865:2):         my $actual_seq =
                   8866:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8867:2):                                                            $master_seq,
          5(raebur 8868:3):                                                            $user,undef,1);
          1(raebur 8869:2):         if (ref($actual_seq) eq 'ARRAY') {
                   8870:2):             @mapresources =
                   8871:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8872:2):         }
          6(raebur 8873:3):     }
                   8874:3):     return @mapresources;
          1(raebur 8875:2): }
                   8876:2): 
1.542     raeburn  8877: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 8878:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8879:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8880:3):     my $uselookup = 0;
                   8881:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8882:3):         (ref($startline) eq 'HASH')) {
                   8883:3):         $uselookup = 1;
                   8884:3):     }
                   8885:3): 
1.554     raeburn  8886:     if (ref($resources) eq 'ARRAY') {
                   8887:         my $count = 0;
                   8888:         foreach my $resource (@{$resources}) {
                   8889:             my $ressymb = $resource->symb();
                   8890:             my %form = ('submitted'      => 'scantron',
                   8891:                         'grade_target'   => 'grade',
                   8892:                         'grade_username' => $uname,
                   8893:                         'grade_domain'   => $udom,
                   8894:                         'grade_courseid' => $env{'request.course.id'},
                   8895:                         'grade_symb'     => $ressymb,
                   8896:                         'CODE'           => $scancode
                   8897:                        );
1.596.2.12.2.  (raeburn 8898:):             if ($bubbles_per_row ne '') {
                   8899:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8900:):             }
                   8901:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8902:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8903:):             }
1.554     raeburn  8904:             if (ref($parts) eq 'HASH') {
                   8905:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8906:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 8907:3):                         if ($uselookup) {
                   8908:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8909:3):                         } else {
                   8910:3):                             $form{'scantron_questnum_start.'.$part} =
                   8911:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8912:3):                         }
1.554     raeburn  8913:                         $count++;
                   8914:                     }
                   8915:                 }
                   8916:             }
                   8917:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8918:             return 'ssi_error' if ($ssi_error);
                   8919:             last if (&Apache::loncommon::connection_aborted($r));
                   8920:         }
1.542     raeburn  8921:     }
                   8922:     return;
                   8923: }
                   8924: 
1.157     albertel 8925: sub scantron_upload_scantron_data {
                   8926:     my ($r)=@_;
1.565     raeburn  8927:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  1.2.3(ra 8928:eb-19):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  8929:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8930:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8931:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8932: 							  'domainid',
1.565     raeburn  8933: 							  'coursename',$dom);
                   8934:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 8935:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   8936:):     my ($symb) = &get_symb($r,1);
                   8937:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8938:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 8939:6):     &js_escape(\$nofile_alert);
1.579     raeburn  8940:     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 8941:6):     &js_escape(\$nocourseid_alert);
          1.2.3(ra 8942:eb-19):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8943:     function checkUpload(formname) {
                   8944: 	if (formname.upfile.value == "") {
1.579     raeburn  8945: 	    alert("'.$nofile_alert.'");
1.157     albertel 8946: 	    return false;
                   8947: 	}
1.565     raeburn  8948:         if (formname.courseid.value == "") {
1.579     raeburn  8949:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8950:             return false;
                   8951:         }
1.157     albertel 8952: 	formname.submit();
                   8953:     }
1.565     raeburn  8954: 
                   8955:     function ToSyllabus() {
                   8956:         var cdom = '."'$dom'".';
                   8957:         var cnum = document.rules.courseid.value;
                   8958:         if (cdom == "" || cdom == null) {
                   8959:             return;
                   8960:         }
                   8961:         if (cnum == "" || cnum == null) {
                   8962:            return;
                   8963:         }
                   8964:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8965:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8966:         return;
                   8967:     }
                   8968: 
1.596.2.12.2.  1.2.3(ra 8969:eb-19):     '.$formatjs.'
                   8970:eb-19): '));
                   8971:eb-19):     $r->print('
1.596.2.4  raeburn  8972: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8973: 
1.492     albertel 8974: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8975: '.$default_form_data.
                   8976:   &Apache::lonhtmlcommon::start_pick_box().
                   8977:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8978:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8979:   &Apache::lonhtmlcommon::row_closure().
                   8980:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8981:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8982:   &Apache::lonhtmlcommon::row_closure().
                   8983:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8984:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  1.2.3(ra 8985:eb-19):   &Apache::lonhtmlcommon::row_closure());
                   8986:eb-19):     if ($formatoptions) {
                   8987:eb-19):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   8988:eb-19):                   &Apache::lonhtmlcommon::row_closure());
                   8989:eb-19):     }
                   8990:eb-19):     $r->print(
1.565     raeburn  8991:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8992:   '<input type="file" name="upfile" size="50" />'.
                   8993:   &Apache::lonhtmlcommon::row_closure(1).
                   8994:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8995: 
1.492     albertel 8996: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8997: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8998: </form>
1.492     albertel 8999: ');
1.157     albertel 9000:     return '';
                   9001: }
                   9002: 
1.596.2.12.2.  1.2.3(ra 9003:eb-19): sub scantron_upload_dataformat {
                   9004:eb-19):     my ($dom) = @_;
                   9005:eb-19):     my ($formatoptions,$formattitle,$formatjs);
                   9006:eb-19):     $formatjs = <<'END';
                   9007:eb-19): function toggleScantab(form) {
                   9008:eb-19):    return;
                   9009:eb-19): }
                   9010:eb-19): END
                   9011:eb-19):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9012:eb-19):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9013:eb-19):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9014:eb-19):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9015:eb-19):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9016:eb-19):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9017:eb-19):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9018:eb-19):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9019:eb-19):                             my ($onclick,$formatextra,$singleline);
                   9020:eb-19):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9021:eb-19):                             my $count = 0;
                   9022:eb-19):                             foreach my $line (@lines) {
                   9023:eb-19):                                 next if ($line =~ /^#/);
                   9024:eb-19):                                 $singleline = $line;
                   9025:eb-19):                                 $count ++;
                   9026:eb-19):                             }
                   9027:eb-19):                             if ($count > 1) {
                   9028:eb-19):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9029:eb-19):                                                '<span class="LC_nobreak">'.
                   9030:eb-19):                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9031:eb-19):                                                &scantron_scantab().'</span></div>';
                   9032:eb-19):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9033:eb-19):                                 $formatjs = <<"END";
                   9034:eb-19): function toggleScantab(form) {
                   9035:eb-19):     var divid = 'bubbletype';
                   9036:eb-19):     if (document.getElementById(divid)) {
                   9037:eb-19):         var radioname = 'fileformat';
                   9038:eb-19):         var num = form.elements[radioname].length;
                   9039:eb-19):         if (num) {
                   9040:eb-19):             for (var i=0; i<num; i++) {
                   9041:eb-19):                 if (form.elements[radioname][i].checked) {
                   9042:eb-19):                     var chosen = form.elements[radioname][i].value;
                   9043:eb-19):                     if (chosen == 'dat') {
                   9044:eb-19):                         document.getElementById(divid).style.display = 'none';
                   9045:eb-19):                     } else if (chosen == 'csv') {
                   9046:eb-19):                         document.getElementById(divid).style.display = 'block';
                   9047:eb-19):                     }
                   9048:eb-19):                 }
                   9049:eb-19):             }
                   9050:eb-19):         }
                   9051:eb-19):     }
                   9052:eb-19):     return;
                   9053:eb-19): }
                   9054:eb-19): 
                   9055:eb-19): END
                   9056:eb-19):                             } elsif ($count == 1) {
                   9057:eb-19):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9058:eb-19):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9059:eb-19):                             }
                   9060:eb-19):                             $formattitle = &mt('File format');
                   9061:eb-19):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9062:eb-19):                                              &mt('Plain Text (no delimiters)').
                   9063:eb-19):                                              '</label>'.('&nbsp;'x2).
                   9064:eb-19):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9065:eb-19):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9066:eb-19):                         }
                   9067:eb-19):                     }
                   9068:eb-19):                 }
                   9069:eb-19):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9070:eb-19):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9071:eb-19):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9072:eb-19):                         $formattitle = &mt('Bubblesheet type');
                   9073:eb-19):                         $formatoptions = &scantron_scantab();
                   9074:eb-19):                     }
                   9075:eb-19):                 }
                   9076:eb-19):             }
                   9077:eb-19):         }
                   9078:eb-19):     }
                   9079:eb-19):     return ($formatoptions,$formattitle,$formatjs);
                   9080:eb-19): }
1.423     albertel 9081: 
1.157     albertel 9082: sub scantron_upload_scantron_data_save {
                   9083:     my($r)=@_;
1.324     albertel 9084:     my ($symb)=&get_symb($r,1);
1.182     albertel 9085:     my $doanotherupload=
                   9086: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9087: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9088: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9089: 	'</form>'."\n";
1.257     albertel 9090:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9091: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9092: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9093: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 9094: 	if ($symb) {
1.324     albertel 9095: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 9096: 	} else {
                   9097: 	    $r->print($doanotherupload);
                   9098: 	}
1.162     albertel 9099: 	return '';
                   9100:     }
1.257     albertel 9101:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9102:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9103:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9104:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9105:3):         $r->print(
                   9106:3):             &Apache::lonhtmlcommon::confirm_success(
                   9107:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9108:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9109:     } else {
1.596.2.12.2.  1.2.3(ra 9110:eb-19):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9111:eb-19):         my $parser;
                   9112:eb-19):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9113:eb-19):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9114:eb-19):                 my $is_csv;
                   9115:eb-19):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9116:eb-19):                 if (@possibles > 1) {
                   9117:eb-19):                     if ($env{'form.fileformat'} eq 'csv') {
                   9118:eb-19):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9119:eb-19):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9120:eb-19):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9121:eb-19):                                     $is_csv = 1;
                   9122:eb-19):                                 }
                   9123:eb-19):                             }
                   9124:eb-19):                         }
                   9125:eb-19):                     }
                   9126:eb-19):                 } elsif (@possibles == 1) {
                   9127:eb-19):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9128:eb-19):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9129:eb-19):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9130:eb-19):                                 $is_csv = 1;
                   9131:eb-19):                             }
                   9132:eb-19):                         }
                   9133:eb-19):                     }
                   9134:eb-19):                 }
                   9135:eb-19):                 if ($is_csv) {
                   9136:eb-19):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9137:eb-19):                 }
                   9138:eb-19):             }
                   9139:eb-19):         }
                   9140:eb-19):         my $result =
                   9141:eb-19):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9142:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9143: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9144:3):             $r->print(
                   9145:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9146:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9147:3):                         (length($env{'form.upfile'})-1),
                   9148:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9149:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9150:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9151:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9152: 	} else {
1.596.2.12.2.  5(raebur 9153:3):             $r->print(
                   9154:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9155:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9156:3):                           $result,
1.568     raeburn  9157: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9158: 	}
                   9159:     }
1.174     albertel 9160:     if ($symb) {
1.209     ng       9161: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 9162:     } else {
1.182     albertel 9163: 	$r->print($doanotherupload);
1.174     albertel 9164:     }
1.157     albertel 9165:     return '';
                   9166: }
                   9167: 
1.567     raeburn  9168: sub validate_uploaded_scantron_file {
                   9169:     my ($cdom,$cname,$fname) = @_;
                   9170:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9171:     my @lines;
                   9172:     if ($scanlines ne '-1') {
                   9173:         @lines=split("\n",$scanlines,-1);
                   9174:     }
                   9175:     my $output;
                   9176:     if (@lines) {
                   9177:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9178:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9179:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9180:         my %idmap = &username_to_idmap($classlist);
                   9181:         foreach my $key (keys(%idmap)) {
                   9182:             my $lckey = lc($key);
                   9183:             $idmap{$lckey} = $idmap{$key};
                   9184:         }
                   9185:         my %unique_formats;
1.596.2.12.2.  1.2.4(ra 9186:eb-19):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9187:         foreach my $line (@formatlines) {
                   9188:             chomp($line);
                   9189:             my @config = split(/:/,$line);
                   9190:             my $idstart = $config[5];
                   9191:             my $idlength = $config[6];
                   9192:             if (($idstart ne '') && ($idlength > 0)) {
                   9193:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9194:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9195:                 } else {
                   9196:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9197:                 }
                   9198:             }
                   9199:         }
                   9200:         foreach my $key (keys(%unique_formats)) {
                   9201:             my ($idstart,$idlength) = split(':',$key);
                   9202:             %{$counts{$key}} = (
                   9203:                                'found'   => 0,
                   9204:                                'total'   => 0,
                   9205:                               );
                   9206:             foreach my $line (@lines) {
                   9207:                 next if ($line =~ /^#/);
                   9208:                 next if ($line =~ /^[\s\cz]*$/);
                   9209:                 my $id = substr($line,$idstart-1,$idlength);
                   9210:                 $id = lc($id);
                   9211:                 if (exists($idmap{$id})) {
                   9212:                     $counts{$key}{'found'} ++;
                   9213:                 }
                   9214:                 $counts{$key}{'total'} ++;
                   9215:             }
                   9216:             if ($counts{$key}{'total'}) {
                   9217:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9218:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9219:                     $max_match_pct = $percent_match;
                   9220:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9221:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9222:                     $max_match_count = $counts{$key}{'total'};
                   9223:                 }
                   9224:             }
                   9225:         }
                   9226:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9227:             my $format_descs;
                   9228:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9229:             for (my $i=0; $i<$numwithformat; $i++) {
                   9230:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9231:                 if ($i<$numwithformat-2) {
                   9232:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9233:                 } elsif ($i==$numwithformat-2) {
                   9234:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9235:                 } elsif ($i==$numwithformat-1) {
                   9236:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9237:                 }
                   9238:             }
                   9239:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9240:3):             $output .= '<br />';
                   9241:3):             if ($found_match_count == $max_match_count) {
                   9242:3):                 # 100% matching entries
                   9243:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9244:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9245:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9246:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9247:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9248:3):                     ' in the file (for the format defined for [_3]).',
                   9249:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9250:3):             } else {
                   9251:3):                 # Not all entries matching? -> Show warning and additional info
                   9252:3):                 $output .=
                   9253:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9254:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9255:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9256:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9257:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9258:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9259:3):                         ' in the file (for the format defined for [_3]).',
                   9260:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9261:3):                     '<p class="LC_info">'.
                   9262:3):                     &mt('A low percentage of matches results from one of the following:').
                   9263:3):                     '</p><ul>'.
                   9264:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9265:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9266:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9267:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9268:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9269:3):                     '</ul>';
                   9270:3):             }
1.567     raeburn  9271:         }
                   9272:     } else {
1.596.2.12.2.  5(raebur 9273:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9274:     }
                   9275:     return $output;
                   9276: }
                   9277: 
1.202     albertel 9278: sub valid_file {
                   9279:     my ($requested_file)=@_;
                   9280:     foreach my $filename (sort(&scantron_filenames())) {
                   9281: 	if ($requested_file eq $filename) { return 1; }
                   9282:     }
                   9283:     return 0;
                   9284: }
                   9285: 
                   9286: sub scantron_download_scantron_data {
                   9287:     my ($r)=@_;
1.596.2.12.2.  (raeburn 9288:):     my ($symb) = &get_symb($r,1);
                   9289:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9290:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9291:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9292:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9293:     if (! &valid_file($file)) {
1.492     albertel 9294: 	$r->print('
1.202     albertel 9295: 	<p>
1.596.2.12.2.  3(raebur 9296:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9297:         </p>
1.492     albertel 9298: ');
1.596.2.12.2.  (raeburn 9299:): 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 9300: 	return;
                   9301:     }
                   9302:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9303:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9304:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9305:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9306:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9307:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9308:     $r->print('
1.202     albertel 9309:     <p>
1.596.2.12.2.  8(raebur 9310:4): 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
1.492     albertel 9311: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9312:     </p>
                   9313:     <p>
1.492     albertel 9314: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9315: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9316:     </p>
                   9317:     <p>
1.492     albertel 9318: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9319: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9320:     </p>
1.492     albertel 9321: ');
1.596.2.12.2.  (raeburn 9322:):     $r->print(&show_grading_menu_form($symb));
1.202     albertel 9323:     return '';
                   9324: }
1.157     albertel 9325: 
1.523     raeburn  9326: sub checkscantron_results {
                   9327:     my ($r) = @_;
                   9328:     my ($symb)=&get_symb($r);
                   9329:     if (!$symb) {return '';}
                   9330:     my $grading_menu_button=&show_grading_menu_form($symb);
                   9331:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  1.2.3(ra 9332:eb-19):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9333:     my $numletts = scalar(keys(%lettdig));
                   9334:     my $cnum = $env{'course.'.$cid.'.num'};
                   9335:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9336:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9337:     my %record;
                   9338:     my %scantron_config =
1.596.2.12.2.  1.2.3(ra 9339:eb-19):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9340:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9341:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9342:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9343:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9344:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9345:     unless (ref($navmap)) {
                   9346:         $r->print(&navmap_errormsg());
                   9347:         return '';
                   9348:     }
1.523     raeburn  9349:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9350:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9351:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9352:2):     if (ref($map)) {
                   9353:2):         $randomorder=$map->randomorder();
          7(raebur 9354:3):         $randompick=$map->randompick();
          1(raebur 9355:2):     }
1.557     raeburn  9356:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9357:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9358:3):     if ($nav_error) {
                   9359:3):         $r->print(&navmap_errormsg());
                   9360:3):         return '';
          1(raebur 9361:2):     }
          (raeburn 9362:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9363:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9364:     my ($uname,$udom);
1.523     raeburn  9365:     my (%scandata,%lastname,%bylast);
                   9366:     $r->print('
                   9367: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9368: 
                   9369:     my @delayqueue;
                   9370:     my %completedstudents;
                   9371: 
1.596.2.12.2.  6(raebur 9372:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9373:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9374:3):     my ($username,$domain,$started);
          (raeburn 9375:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9376:     if ($nav_error) {
                   9377:         $r->print(&navmap_errormsg());
                   9378:         return '';
                   9379:     }
1.523     raeburn  9380: 
                   9381:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9382:                                           'Processing first student');
                   9383:     my $start=&Time::HiRes::time();
                   9384:     my $i=-1;
                   9385: 
                   9386:     while ($i<$scanlines->{'count'}) {
                   9387:         ($username,$domain,$uname)=('','','');
                   9388:         $i++;
                   9389:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9390:         if ($line=~/^[\s\cz]*$/) { next; }
                   9391:         if ($started) {
                   9392:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9393:                                                      'last student');
                   9394:         }
                   9395:         $started=1;
                   9396:         my $scan_record=
                   9397:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9398:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9399:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9400:3):                                               \%idmap,$i)) {
1.523     raeburn  9401:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9402:                                 'Unable to find a student that matches',1);
                   9403:             next;
                   9404:         }
                   9405:         if (exists $completedstudents{$uname}) {
                   9406:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9407:                                 'Student '.$uname.' has multiple sheets',2);
                   9408:             next;
                   9409:         }
                   9410:         my $pid = $scan_record->{'scantron.ID'};
                   9411:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9412:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9413:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9414:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9415:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9416:2): 
                   9417:2):         my $scancode;
                   9418:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9419:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9420:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9421:2):         } else {
                   9422:2):             $scancode = '';
                   9423:2):         }
                   9424:2): 
                   9425:2):         my @mapresources = @resources;
          6(raebur 9426:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9427:3):         my %respnumlookup=();
                   9428:3):         my %startline=();
                   9429:3):         if ($randomorder || $randompick) {
          1(raebur 9430:2):             @mapresources =
          6(raebur 9431:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9432:3):                              \%orderedforcode);
                   9433:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9434:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9435:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9436:3):                                              \%respnumlookup,\%startline);
                   9437:3):             if ($randompick && $total) {
                   9438:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9439:3):             }
          1(raebur 9440:2):         }
          6(raebur 9441:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9442:3):         chomp($scandata{$pid});
                   9443:3):         $scandata{$pid} =~ s/\r$//;
                   9444:3): 
1.523     raeburn  9445:         my $counter = -1;
1.596.2.12.2.  1(raebur 9446:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9447:             my $parts;
1.554     raeburn  9448:             my $ressymb = $resource->symb();
1.557     raeburn  9449:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9450:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9451:7):                 my $currcode;
                   9452:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9453:7):                     $currcode = $scancode;
                   9454:7):                 }
1.557     raeburn  9455:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9456:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9457:):                                               $username,$domain,undef,
          1(raebur 9458:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9459:             } else {
                   9460:                 $parts = $grader_partids_by_symb{$ressymb};
                   9461:             }
1.542     raeburn  9462:             ($counter,my $recording) =
                   9463:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9464:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9465:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9466:3):                                          $randomorder,$randompick,
                   9467:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9468:             $record{$pid} .= $recording;
1.523     raeburn  9469:         }
                   9470:     }
                   9471:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9472:     $r->print('<br />');
                   9473:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9474:     $passed = 0;
                   9475:     $failed = 0;
                   9476:     $numstudents = 0;
                   9477:     foreach my $last (sort(keys(%bylast))) {
                   9478:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9479:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9480:                 my $showscandata = $scandata{$pid};
                   9481:                 my $showrecord = $record{$pid};
                   9482:                 $showscandata =~ s/\s/&nbsp;/g;
                   9483:                 $showrecord =~ s/\s/&nbsp;/g;
                   9484:                 if ($scandata{$pid} eq $record{$pid}) {
                   9485:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9486:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9487: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9488: '</tr>'."\n".
                   9489: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9490:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9491:                     $passed ++;
                   9492:                 } else {
                   9493:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9494:                     $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  9495: '</tr>'."\n".
                   9496: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9497:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9498: '</tr>'."\n";
                   9499:                     $failed ++;
                   9500:                 }
                   9501:                 $numstudents ++;
                   9502:             }
                   9503:         }
                   9504:     }
1.596.2.4  raeburn  9505:     $r->print('<p>'.
1.596.2.8  raeburn  9506:               &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  9507:                   '<b>',
                   9508:                   $numstudents,
                   9509:                   '</b>',
                   9510:                   $env{'form.scantron_maxbubble'}).
                   9511:               '</p>'
                   9512:     );
1.596.2.12.2.  2(raebur 9513:2):     $r->print('<p>'
                   9514:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9515:2):              .'<br />'
                   9516:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9517:2):              .'</p>');
1.523     raeburn  9518:     if ($passed) {
1.572     www      9519:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9520:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9521:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9522:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9523:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9524:                  $okstudents."\n".
                   9525:                  &Apache::loncommon::end_data_table().'<br />');
                   9526:     }
                   9527:     if ($failed) {
1.572     www      9528:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9529:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9530:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9531:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9532:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9533:                  $badstudents."\n".
                   9534:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9535:                  &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  9536:     }
                   9537:     $r->print('</form><br />'.$grading_menu_button);
                   9538:     return;
                   9539: }
                   9540: 
1.542     raeburn  9541: sub verify_scantron_grading {
1.554     raeburn  9542:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9543:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9544:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9545:     my ($record,%expected,%startpos);
                   9546:     return ($counter,$record) if (!ref($resource));
                   9547:     return ($counter,$record) if (!$resource->is_problem());
                   9548:     my $symb = $resource->symb();
1.554     raeburn  9549:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9550:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9551:         $counter ++;
                   9552:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9553:3):         my $respnum = $counter;
                   9554:3):         if ($randomorder || $randompick) {
                   9555:3):             $respnum = $respnumlookup->{$counter};
                   9556:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9557:3):         } else {
                   9558:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9559:3):         }
                   9560:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9561:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9562:             foreach my $item (@sub_lines) {
                   9563:                 $expected{$part_id} += $item;
                   9564:             }
                   9565:         } else {
1.596.2.12.2.  6(raebur 9566:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9567:         }
                   9568:     }
                   9569:     if ($symb) {
                   9570:         my %recorded;
                   9571:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9572:         if ($returnhash{'version'}) {
                   9573:             my %lasthash=();
                   9574:             my $version;
                   9575:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9576:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9577:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9578:                 }
                   9579:             }
                   9580:             foreach my $key (keys(%lasthash)) {
                   9581:                 if ($key =~ /\.scantron$/) {
                   9582:                     my $value = &unescape($lasthash{$key});
                   9583:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9584:                     if ($value eq '') {
                   9585:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9586:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9587:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9588:                             }
                   9589:                         }
                   9590:                     } else {
                   9591:                         my @tocheck;
                   9592:                         my @items = split(//,$value);
                   9593:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9594:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9595:                             if (@items < $expected{$part_id}) {
                   9596:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9597:                                 my @singles = split(//,$fragment);
                   9598:                                 foreach my $pos (@singles) {
                   9599:                                     if ($pos eq ' ') {
                   9600:                                         push(@tocheck,$pos);
                   9601:                                     } else {
                   9602:                                         my $next = shift(@items);
                   9603:                                         push(@tocheck,$next);
                   9604:                                     }
                   9605:                                 }
                   9606:                             } else {
                   9607:                                 @tocheck = @items;
                   9608:                             }
                   9609:                             foreach my $letter (@tocheck) {
                   9610:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9611:                                     if ($letter !~ /^[A-J]$/) {
                   9612:                                         $letter = $scantron_config->{'Qoff'};
                   9613:                                     }
                   9614:                                     $recorded{$part_id} .= $letter;
                   9615:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9616:                                     my $digit;
                   9617:                                     if ($letter !~ /^[A-J]$/) {
                   9618:                                         $digit = $scantron_config->{'Qoff'};
                   9619:                                     } else {
                   9620:                                         $digit = $lettdig->{$letter};
                   9621:                                     }
                   9622:                                     $recorded{$part_id} .= $digit;
                   9623:                                 }
                   9624:                             }
                   9625:                         } else {
                   9626:                             @tocheck = @items;
                   9627:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9628:                                 my $curr_sub = shift(@tocheck);
                   9629:                                 my $digit;
                   9630:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9631:                                     $digit = $lettdig->{$curr_sub}-1;
                   9632:                                 }
                   9633:                                 if ($curr_sub eq 'J') {
                   9634:                                     $digit += scalar($numletts);
                   9635:                                 }
                   9636:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9637:                                     if ($j == $digit) {
                   9638:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9639:                                     } else {
                   9640:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9641:                                     }
                   9642:                                 }
                   9643:                             }
                   9644:                         }
                   9645:                     }
                   9646:                 }
                   9647:             }
                   9648:         }
1.554     raeburn  9649:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9650:             if ($recorded{$part_id} eq '') {
                   9651:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9652:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9653:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9654:                     }
                   9655:                 }
                   9656:             }
                   9657:             $record .= $recorded{$part_id};
                   9658:         }
                   9659:     }
                   9660:     return ($counter,$record);
                   9661: }
                   9662: 
1.75      albertel 9663: #-------- end of section for handling grading scantron forms -------
                   9664: #
                   9665: #-------------------------------------------------------------------
                   9666: 
1.72      ng       9667: #-------------------------- Menu interface -------------------------
                   9668: #
                   9669: #--- Show a Grading Menu button - Calls the next routine ---
                   9670: sub show_grading_menu_form {
1.324     albertel 9671:     my ($symb)=@_;
1.125     ng       9672:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 9673: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 9674: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       9675: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 9676: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       9677: 	'</form>'."\n";
                   9678:     return $result;
                   9679: }
                   9680: 
1.77      ng       9681: # -- Retrieve choices for grading form
                   9682: sub savedState {
                   9683:     my %savedState = ();
1.257     albertel 9684:     if ($env{'form.saveState'}) {
                   9685: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       9686: 	    my ($key,$value) = split(/=/,$_,2);
                   9687: 	    $savedState{$key} = $value;
                   9688: 	}
                   9689:     }
                   9690:     return \%savedState;
                   9691: }
1.76      ng       9692: 
1.596.2.12.2.  (raeburn 9693:): #--- Href with symb and command ---
                   9694:): 
                   9695:): sub href_symb_cmd {
                   9696:):     my ($symb,$cmd)=@_;
                   9697:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9698:): }
                   9699:): 
1.443     banghart 9700: sub grading_menu {
                   9701:     my ($request) = @_;
                   9702:     my ($symb)=&get_symb($request);
                   9703:     if (!$symb) {return '';}
                   9704:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   9705:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   9706: 
1.444     banghart 9707:     $request->print($table);
1.443     banghart 9708:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   9709:                   'handgrade'=>$hdgrade,
                   9710:                   'probTitle'=>$probTitle,
                   9711:                   'command'=>'submit_options',
                   9712:                   'saveState'=>"",
                   9713:                   'gradingMenu'=>1,
                   9714:                   'showgrading'=>"yes");
1.538     schulted 9715:     
                   9716:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9717:     
1.443     banghart 9718:     $fields{'command'} = 'csvform';
1.538     schulted 9719:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9720:     
1.443     banghart 9721:     $fields{'command'} = 'processclicker';
1.538     schulted 9722:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9723:     
1.443     banghart 9724:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9725:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9726:     
                   9727:     my @menu = ({	categorytitle=>'Course Grading',
                   9728:             items =>[
                   9729:                         {	linktext => 'Manual Grading/View Submissions',
                   9730:                     		url => $url1,
                   9731:                     		permission => 'F',
                   9732:                     		icon => 'edit-find-replace.png',
                   9733:                     		linktitle => 'Start the process of hand grading submissions.'
                   9734:                         },
                   9735:                 	    {	linktext => 'Upload Scores',
                   9736:                     		url => $url2,
                   9737:                     		permission => 'F',
                   9738:                     		icon => 'uploadscores.png',
                   9739:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9740:                 	    },
                   9741:                 	    {	linktext => 'Process Clicker',
                   9742:                     		url => $url3,
                   9743:                     		permission => 'F',
                   9744:                     		icon => 'addClickerInfoFile.png',
                   9745:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9746:                 	    },
1.587     raeburn  9747:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9748:                     		url => $url4,
                   9749:                     		permission => 'F',
                   9750:                     		icon => 'stat.png',
1.596.2.4  raeburn  9751:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 9752:                 	    }
                   9753:                     ]
                   9754:             });
                   9755: 
                   9756:     #$fields{'command'} = 'verify';
                   9757:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 9758:     #
                   9759:     # Create the menu
                   9760:     my $Str;
1.444     banghart 9761:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 9762:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9763:     $Str .= '<input type="hidden" name="command" value="" />'.
                   9764:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   9765: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 9766: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 9767: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   9768: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   9769: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9770: 
1.538     schulted 9771:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   9772:     #$menudata->{'jscript'}
1.584     bisitz   9773:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   9774:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 9775:         ' /> '.
                   9776:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   9777:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 9778: 
1.444     banghart 9779:     $Str .="</form>\n";
1.539     riegler  9780:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 9781:     $request->print(<<GRADINGMENUJS);
                   9782: <script type="text/javascript" language="javascript">
                   9783:     function checkChoice(formname,val,cmdx) {
                   9784: 	if (val <= 2) {
                   9785: 	    var cmd = radioSelection(formname.radioChoice);
                   9786: 	    var cmdsave = cmd;
                   9787: 	} else {
                   9788: 	    cmd = cmdx;
                   9789: 	    cmdsave = 'submission';
                   9790: 	}
                   9791: 	formname.command.value = cmd;
                   9792: 	if (val < 5) formname.submit();
                   9793: 	if (val == 5) {
1.458     banghart 9794: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   9795: 	        return false;
                   9796: 	    } else {
                   9797: 	        formname.submit();
                   9798: 	    }
1.445     banghart 9799: 	}
                   9800:     }
1.443     banghart 9801: 
                   9802:     function checkReceiptNo(formname,nospace) {
                   9803: 	var receiptNo = formname.receipt.value;
                   9804: 	var checkOpt = false;
                   9805: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9806: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9807: 	if (checkOpt) {
1.539     riegler  9808: 	    alert("$receiptalert");
1.443     banghart 9809: 	    formname.receipt.value = "";
                   9810: 	    formname.receipt.focus();
                   9811: 	    return false;
                   9812: 	}
                   9813: 	return true;
                   9814:     }
                   9815: </script>
                   9816: GRADINGMENUJS
                   9817:     &commonJSfunctions($request);
                   9818:     return $Str;    
                   9819: }
                   9820: 
                   9821: 
                   9822: #--- Displays the submissions first page -------
                   9823: sub submit_options {
1.72      ng       9824:     my ($request) = @_;
1.324     albertel 9825:     my ($symb)=&get_symb($request);
1.72      ng       9826:     if (!$symb) {return '';}
1.76      ng       9827:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       9828: 
1.539     riegler  9829:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       9830:     $request->print(<<GRADINGMENUJS);
                   9831: <script type="text/javascript" language="javascript">
1.116     ng       9832:     function checkChoice(formname,val,cmdx) {
                   9833: 	if (val <= 2) {
                   9834: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       9835: 	    var cmdsave = cmd;
1.116     ng       9836: 	} else {
                   9837: 	    cmd = cmdx;
1.118     ng       9838: 	    cmdsave = 'submission';
1.116     ng       9839: 	}
                   9840: 	formname.command.value = cmd;
1.118     ng       9841: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 9842: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       9843: 	if (val < 5) formname.submit();
                   9844: 	if (val == 5) {
1.72      ng       9845: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   9846: 	    formname.submit();
                   9847: 	}
1.238     albertel 9848: 	if (val < 7) formname.submit();
1.72      ng       9849:     }
                   9850: 
                   9851:     function checkReceiptNo(formname,nospace) {
                   9852: 	var receiptNo = formname.receipt.value;
                   9853: 	var checkOpt = false;
                   9854: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9855: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9856: 	if (checkOpt) {
1.539     riegler  9857: 	    alert("$receiptalert");
1.72      ng       9858: 	    formname.receipt.value = "";
                   9859: 	    formname.receipt.focus();
                   9860: 	    return false;
                   9861: 	}
                   9862: 	return true;
                   9863:     }
                   9864: </script>
                   9865: GRADINGMENUJS
1.118     ng       9866:     &commonJSfunctions($request);
1.324     albertel 9867:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 9868:     my $result;
1.76      ng       9869:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       9870:     my $savedState = &savedState();
1.118     ng       9871:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       9872:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       9873:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       9874:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       9875: 
1.533     bisitz   9876:     # Preselect sections
                   9877:     my $selsec="";
                   9878:     if (ref($sections)) {
                   9879:         foreach my $section (sort(@$sections)) {
                   9880:             $selsec.='<option value="'.$section.'" '.
                   9881:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   9882:         }
                   9883:     }
                   9884: 
1.72      ng       9885:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 9886: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       9887: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   9888: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       9889: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       9890: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       9891: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       9892: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9893: 
1.472     albertel 9894:     $result.='
1.533     bisitz   9895: <h2>
                   9896:   '.&mt('Grade Current Resource').'
                   9897: </h2>
                   9898: <div>
                   9899:   '.$table.'
                   9900: </div>
                   9901: 
1.537     harmsja  9902: <div class="LC_columnSection">
                   9903:   
1.533     bisitz   9904:     <fieldset>
                   9905:       <legend>
                   9906:        '.&mt('Sections').'
                   9907:       </legend>
                   9908:       <select name="section" multiple="multiple" size="5">'."\n";
                   9909:     $result.= $selsec;
1.401     albertel 9910:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 9911:     $result.='
1.533     bisitz   9912:     </fieldset>
1.537     harmsja  9913:   
1.533     bisitz   9914:     <fieldset>
                   9915:       <legend>
                   9916:         '.&mt('Groups').'
                   9917:       </legend>
                   9918:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9919:     </fieldset>
1.537     harmsja  9920:   
1.533     bisitz   9921:     <fieldset>
                   9922:       <legend>
                   9923:         '.&mt('Access Status').'
                   9924:       </legend>
                   9925:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   9926:     </fieldset>
1.537     harmsja  9927:   
1.533     bisitz   9928:     <fieldset>
                   9929:       <legend>
                   9930:         '.&mt('Submission Status').'
                   9931:       </legend>
                   9932:       <select name="submitonly" size="5">
1.473     albertel 9933: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   9934: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   9935: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   9936: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   9937:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   9938:       </select>
                   9939:     </fieldset>
1.537     harmsja  9940:   
1.533     bisitz   9941: </div>
                   9942: 
                   9943: <br />
                   9944:           <div>
                   9945:             <div>
1.473     albertel 9946:               <label>
                   9947:                 <input type="radio" name="radioChoice" value="submission" '.
                   9948:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   9949:              &mt('Select individual students to grade and view submissions.').'
                   9950: 	      </label> 
                   9951:             </div>
1.533     bisitz   9952:             <div>
1.473     albertel 9953: 	      <label>
                   9954:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   9955:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   9956:                     &mt('Grade all selected students in a grading table.').'
                   9957:               </label>
                   9958:             </div>
1.533     bisitz   9959:             <div>
1.589     bisitz   9960: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9961:             </div>
1.472     albertel 9962:           </div>
1.533     bisitz   9963: 
                   9964: 
1.473     albertel 9965:         <h2>
                   9966:          '.&mt('Grade Complete Folder for One Student').'
                   9967:         </h2>
1.533     bisitz   9968:         <div>
                   9969:             <div>
1.473     albertel 9970:               <label>
                   9971:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   9972: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   9973:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   9974:               </label>
                   9975:             </div>
1.533     bisitz   9976:             <div>
1.589     bisitz   9977: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9978:             </div>
1.472     albertel 9979:         </div>
                   9980:   </form>';
1.499     albertel 9981:     $result .= &show_grading_menu_form($symb);
1.44      ng       9982:     return $result;
1.2       albertel 9983: }
                   9984: 
1.596.2.12.2.  7(raebur 9985:6): sub substatus_options {
                   9986:6):     return &Apache::lonlocal::texthash(
                   9987:6):                                       'yes'       => 'with submissions',
                   9988:6):                                       'queued'    => 'in grading queue',
                   9989:6):                                       'graded'    => 'with ungraded submissions',
                   9990:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 9991:7):                                       'all'       => 'with any status',
                   9992:7):                                       );
          7(raebur 9993:6): }
                   9994:6): 
1.285     albertel 9995: sub reset_perm {
                   9996:     undef(%perm);
                   9997: }
                   9998: 
                   9999: sub init_perm {
                   10000:     &reset_perm();
1.300     albertel 10001:     foreach my $test_perm ('vgr','mgr','opa') {
                   10002: 
                   10003: 	my $scope = $env{'request.course.id'};
                   10004: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10005: 
                   10006: 	    $scope .= '/'.$env{'request.course.sec'};
                   10007: 	    if ( $perm{$test_perm}=
                   10008: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10009: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10010: 	    } else {
                   10011: 		delete($perm{$test_perm});
                   10012: 	    }
1.285     albertel 10013: 	}
                   10014:     }
                   10015: }
                   10016: 
1.596.2.12.2.  (raeburn 10017:): sub init_old_essays {
                   10018:):     my ($symb,$apath,$adom,$aname) = @_;
                   10019:):     if ($symb ne '') {
                   10020:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10021:):         if (keys(%essays) > 0) {
                   10022:):             $old_essays{$symb} = \%essays;
                   10023:):         }
                   10024:):     }
                   10025:):     return;
                   10026:): }
                   10027:): 
                   10028:): sub reset_old_essays {
                   10029:):     undef(%old_essays);
                   10030:): }
                   10031:): 
1.400     www      10032: sub gather_clicker_ids {
1.408     albertel 10033:     my %clicker_ids;
1.400     www      10034: 
                   10035:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10036: 
                   10037:     # Set up a couple variables.
1.407     albertel 10038:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10039:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10040:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10041: 
1.407     albertel 10042:     foreach my $student (keys(%$classlist)) {
1.438     www      10043:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10044:         my $username = $classlist->{$student}->[$username_idx];
                   10045:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10046:         my $clickers =
1.408     albertel 10047: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10048:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10049:             $id=~s/^[\#0]+//;
1.421     www      10050:             $id=~s/[\-\:]//g;
1.407     albertel 10051:             if (exists($clicker_ids{$id})) {
1.408     albertel 10052: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10053:             } else {
1.408     albertel 10054: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10055:             }
                   10056:         }
                   10057:     }
1.407     albertel 10058:     return %clicker_ids;
1.400     www      10059: }
                   10060: 
1.402     www      10061: sub gather_adv_clicker_ids {
1.408     albertel 10062:     my %clicker_ids;
1.402     www      10063:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10064:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10065:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10066:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10067:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10068:             my ($puname,$pudom)=split(/\:/,$person);
                   10069:             my $clickers =
1.408     albertel 10070: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10071:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10072: 		$id=~s/^[\#0]+//;
1.421     www      10073:                 $id=~s/[\-\:]//g;
1.408     albertel 10074: 		if (exists($clicker_ids{$id})) {
                   10075: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10076: 		} else {
                   10077: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10078: 		}
1.405     www      10079:             }
1.402     www      10080:         }
                   10081:     }
1.407     albertel 10082:     return %clicker_ids;
1.402     www      10083: }
                   10084: 
1.413     www      10085: sub clicker_grading_parameters {
                   10086:     return ('gradingmechanism' => 'scalar',
                   10087:             'upfiletype' => 'scalar',
                   10088:             'specificid' => 'scalar',
                   10089:             'pcorrect' => 'scalar',
                   10090:             'pincorrect' => 'scalar');
                   10091: }
                   10092: 
1.400     www      10093: sub process_clicker {
                   10094:     my ($r)=@_;
                   10095:     my ($symb)=&get_symb($r);
                   10096:     if (!$symb) {return '';}
                   10097:     my $result=&checkforfile_js();
                   10098:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   10099:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   10100:     $result.=$table;
                   10101:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   10102:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 10103:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   10104:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  10105:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      10106: # Attempt to restore parameters from last session, set defaults if not present
                   10107:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10108:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10109:                                                  \%Saveable_Parameters);
                   10110:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10111:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10112:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10113:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10114: 
                   10115:     my %checked;
1.521     www      10116:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10117:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10118:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10119:        }
                   10120:     }
                   10121: 
1.400     www      10122:     my $upload=&mt("Upload File");
                   10123:     my $type=&mt("Type");
1.402     www      10124:     my $attendance=&mt("Award points just for participation");
                   10125:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10126:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10127:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10128:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10129:     my $pcorrect=&mt("Percentage points for correct solution");
                   10130:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10131:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10132:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10133:):                                                     'interwrite' => 'interwrite PRS',
                   10134:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10135:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      10136:     $result.=<<ENDUPFORM;
1.402     www      10137: <script type="text/javascript">
                   10138: function sanitycheck() {
                   10139: // Accept only integer percentages
                   10140:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10141:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10142: // Find out grading choice
                   10143:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10144:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10145:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10146:       }
                   10147:    }
                   10148: // By default, new choice equals user selection
                   10149:    newgradingchoice=gradingchoice;
                   10150: // Not good to give more points for false answers than correct ones
                   10151:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10152:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10153:    }
                   10154: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10155:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10156:       document.forms.gradesupload.pcorrect.value=100;
                   10157:       document.forms.gradesupload.pincorrect.value=100;
                   10158:    }
                   10159: // If the values are different, cannot be attendance only
                   10160:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10161:        (gradingchoice=='attendance')) {
                   10162:        newgradingchoice='personnel';
                   10163:    }
                   10164: // Change grading choice to new one
                   10165:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10166:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10167:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10168:       } else {
                   10169:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10170:       }
                   10171:    }
                   10172: // Remember the old state
                   10173:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10174: }
                   10175: </script>
1.400     www      10176: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10177: <input type="hidden" name="symb" value="$symb" />
                   10178: <input type="hidden" name="command" value="processclickerfile" />
                   10179: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10180: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   10181: <input type="file" name="upfile" size="50" />
                   10182: <br /><label>$type: $selectform</label>
1.589     bisitz   10183: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   10184: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10185: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10186: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10187: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10188: <br />&nbsp;&nbsp;&nbsp;
                   10189: <input type="text" name="givenanswer" size="50" />
1.413     www      10190: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   10191: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   10192: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10193: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10194: </form>
                   10195: ENDUPFORM
                   10196:     $result.='</td></tr></table>'."\n".
                   10197:              '</td></tr></table><br /><br />'."\n";
                   10198:     $result.=&show_grading_menu_form($symb);
                   10199:     return $result;
                   10200: }
                   10201: 
                   10202: sub process_clicker_file {
                   10203:     my ($r)=@_;
                   10204:     my ($symb)=&get_symb($r);
                   10205:     if (!$symb) {return '';}
1.413     www      10206: 
                   10207:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10208:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10209:                                               \%Saveable_Parameters);
                   10210: 
1.400     www      10211:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      10212:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10213: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   10214: 	return $result.&show_grading_menu_form($symb);
1.404     www      10215:     }
1.522     www      10216:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10217:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   10218:         return $result.&show_grading_menu_form($symb);
                   10219:     }
1.522     www      10220:     my $foundgiven=0;
1.521     www      10221:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10222:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10223:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10224:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10225:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10226:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10227:         $foundgiven=$#answers+1;
1.521     www      10228:     }
1.407     albertel 10229:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10230:     my %correct_ids;
1.404     www      10231:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10232: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10233:     }
                   10234:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10235: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10236: 	   $correct_id=~tr/a-z/A-Z/;
                   10237: 	   $correct_id=~s/\s//gs;
                   10238: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10239:            $correct_id=~s/[\-\:]//g;
1.414     www      10240:            if ($correct_id) {
                   10241: 	      $correct_ids{$correct_id}='specified';
                   10242:            }
                   10243:         }
1.400     www      10244:     }
1.404     www      10245:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10246: 	$result.=&mt('Score based on attendance only');
1.521     www      10247:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10248:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10249:     } else {
1.408     albertel 10250: 	my $number=0;
1.411     www      10251: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10252: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10253: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10254: 	    if ($correct_ids{$id} eq 'specified') {
                   10255: 		$result.=&mt('specified');
                   10256: 	    } else {
                   10257: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10258: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10259: 	    }
                   10260: 	    $number++;
                   10261: 	}
1.411     www      10262:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10263:3):         if ($number==0) {
                   10264:3):             $result .=
                   10265:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10266:3):                      &mt('No IDs found to determine correct answer'),1);
          1.2.6(ra 10267:eb-19):             return $result.&show_grading_menu_form($symb);
          5(raebur 10268:3):         }
1.404     www      10269:     }
1.405     www      10270:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10271:3):         $result .=
                   10272:3):             &Apache::lonhtmlcommon::confirm_success(
                   10273:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10274:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.405     www      10275:         return $result.&show_grading_menu_form($symb);
                   10276:     }
1.596.2.12.2.  1.2.6(ra 10277:eb-19):     my $mimetype;
                   10278:eb-19):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10279:eb-19):         my $mm = new File::MMagic;
                   10280:eb-19):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10281:eb-19):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10282:eb-19):             $result.= '<p>'.
                   10283:eb-19):                 &Apache::lonhtmlcommon::confirm_success(
                   10284:eb-19):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10285:eb-19):             return $result.&show_grading_menu_form($symb);
                   10286:eb-19):         }
                   10287:eb-19):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10288:eb-19):         $result .= '<p>'.
                   10289:eb-19):             &Apache::lonhtmlcommon::confirm_success(
                   10290:eb-19):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10291:eb-19):         return $result.&show_grading_menu_form($symb);
                   10292:eb-19):     }
1.410     www      10293: 
                   10294: # Were able to get all the info needed, now analyze the file
                   10295: 
1.411     www      10296:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10297:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      10298:     my $heading=&mt('Scanning clicker file');
                   10299:     $result.=(<<ENDHEADER);
                   10300: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   10301: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  10302: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      10303: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10304: <input type="hidden" name="symb" value="$symb" />
                   10305: <input type="hidden" name="command" value="assignclickergrades" />
                   10306: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10307: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      10308: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10309: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10310: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10311: ENDHEADER
1.522     www      10312:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10313:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10314:     } 
1.408     albertel 10315:     my %responses;
                   10316:     my @questiontitles;
1.405     www      10317:     my $errormsg='';
                   10318:     my $number=0;
                   10319:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  1.2.6(ra 10320:eb-19):         if ($mimetype eq 'text/plain') {
                   10321:eb-19):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10322:eb-19):         } elsif ($mimetype eq 'text/html') {
                   10323:eb-19):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10324:eb-19):         }
                   10325:eb-19):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10326:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  1.2.6(ra 10327:eb-19):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10328:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10329:):     }
1.411     www      10330:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10331:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10332:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10333:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10334:              '<br />';
1.522     www      10335:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10336:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   10337:        return $result.&show_grading_menu_form($symb);
                   10338:     } 
1.414     www      10339: # Remember Question Titles
                   10340: # FIXME: Possibly need delimiter other than ":"
                   10341:     for (my $i=0;$i<$number;$i++) {
                   10342:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10343:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10344:     }
1.411     www      10345:     my $correct_count=0;
                   10346:     my $student_count=0;
                   10347:     my $unknown_count=0;
1.414     www      10348: # Match answers with usernames
                   10349: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10350:     foreach my $id (keys(%responses)) {
1.410     www      10351:        if ($correct_ids{$id}) {
1.414     www      10352:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10353:           $correct_count++;
1.410     www      10354:        } elsif ($clicker_ids{$id}) {
1.437     www      10355:           if ($clicker_ids{$id}=~/\,/) {
                   10356: # More than one user with the same clicker!
                   10357:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   10358:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10359:                            "<select name='multi".$id."'>";
                   10360:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10361:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10362:              }
                   10363:              $result.='</select>';
                   10364:              $unknown_count++;
                   10365:           } else {
                   10366: # Good: found one and only one user with the right clicker
                   10367:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10368:              $student_count++;
                   10369:           }
1.410     www      10370:        } else {
1.411     www      10371:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   10372:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10373:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10374:                    "\n".&mt("Domain").": ".
                   10375:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  10376:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10377:           $unknown_count++;
1.410     www      10378:        }
1.405     www      10379:     }
1.412     www      10380:     $result.='<hr />'.
                   10381:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10382:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10383:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10384:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10385:        } elsif ($correct_count>1) {
1.414     www      10386:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10387:        }
                   10388:     }
1.428     www      10389:     if ($number<1) {
                   10390:        $errormsg.="Found no questions.";
                   10391:     }
1.412     www      10392:     if ($errormsg) {
                   10393:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10394:     } else {
                   10395:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10396:     }
                   10397:     $result.='</form></td></tr></table>'."\n".
1.410     www      10398:              '</td></tr></table><br /><br />'."\n";
1.404     www      10399:     return $result.&show_grading_menu_form($symb);
1.400     www      10400: }
                   10401: 
1.405     www      10402: sub iclicker_eval {
1.406     www      10403:     my ($questiontitles,$responses)=@_;
1.405     www      10404:     my $number=0;
                   10405:     my $errormsg='';
                   10406:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10407:         my %components=&Apache::loncommon::record_sep($line);
                   10408:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10409: 	if ($entries[0] eq 'Question') {
                   10410: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10411: 		$$questiontitles[$number]=$entries[$i];
                   10412: 		$number++;
                   10413: 	    }
                   10414: 	}
                   10415: 	if ($entries[0]=~/^\#/) {
                   10416: 	    my $id=$entries[0];
                   10417: 	    my @idresponses;
                   10418: 	    $id=~s/^[\#0]+//;
                   10419: 	    for (my $i=0;$i<$number;$i++) {
                   10420: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10421:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10422: 		push(@idresponses,$entries[$idx]);
                   10423: 	    }
                   10424: 	    $$responses{$id}=join(',',@idresponses);
                   10425: 	}
1.405     www      10426:     }
                   10427:     return ($errormsg,$number);
                   10428: }
                   10429: 
1.596.2.12.2.  1.2.6(ra 10430:eb-19): sub iclickerxml_eval {
                   10431:eb-19):     my ($questiontitles,$responses)=@_;
                   10432:eb-19):     my $number=0;
                   10433:eb-19):     my $errormsg='';
                   10434:eb-19):     my @state;
                   10435:eb-19):     my %respbyid;
                   10436:eb-19):     my $p = HTML::Parser->new
                   10437:eb-19):     (
                   10438:eb-19):         xml_mode => 1,
                   10439:eb-19):         start_h =>
                   10440:eb-19):             [sub {
                   10441:eb-19):                  my ($tagname,$attr) = @_;
                   10442:eb-19):                  push(@state,$tagname);
                   10443:eb-19):                  if ("@state" eq "ssn p") {
                   10444:eb-19):                      my $title = $attr->{qn};
                   10445:eb-19):                      $title =~ s/(^\s+|\s+$)//g;
                   10446:eb-19):                      $questiontitles->[$number]=$title;
                   10447:eb-19):                  } elsif ("@state" eq "ssn p v") {
                   10448:eb-19):                      my $id = $attr->{id};
                   10449:eb-19):                      my $entry = $attr->{ans};
                   10450:eb-19):                      $id=~s/^[\#0]+//;
                   10451:eb-19):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10452:eb-19):                      $respbyid{$id}[$number] = $entry;
                   10453:eb-19):                  }
                   10454:eb-19):             }, "tagname, attr"],
                   10455:eb-19):          end_h =>
                   10456:eb-19):                [sub {
                   10457:eb-19):                    my ($tagname) = @_;
                   10458:eb-19):                    if ("@state" eq "ssn p") {
                   10459:eb-19):                        $number++;
                   10460:eb-19):                    }
                   10461:eb-19):                    pop(@state);
                   10462:eb-19):                 }, "tagname"],
                   10463:eb-19):     );
                   10464:eb-19): 
                   10465:eb-19):     $p->parse($env{'form.upfile'});
                   10466:eb-19):     $p->eof;
                   10467:eb-19):     foreach my $id (keys(%respbyid)) {
                   10468:eb-19):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10469:eb-19):     }
                   10470:eb-19):     return ($errormsg,$number);
                   10471:eb-19): }
                   10472:eb-19): 
1.419     www      10473: sub interwrite_eval {
                   10474:     my ($questiontitles,$responses)=@_;
                   10475:     my $number=0;
                   10476:     my $errormsg='';
1.420     www      10477:     my $skipline=1;
                   10478:     my $questionnumber=0;
                   10479:     my %idresponses=();
1.419     www      10480:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10481:         my %components=&Apache::loncommon::record_sep($line);
                   10482:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10483:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10484:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10485:         next if $skipline;
                   10486:         if ($entries[0]!=$questionnumber) {
                   10487:            $questionnumber=$entries[0];
                   10488:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10489:            $number++;
1.419     www      10490:         }
1.420     www      10491:         my $id=$entries[4];
                   10492:         $id=~s/^[\#0]+//;
1.421     www      10493:         $id=~s/^v\d*\://i;
                   10494:         $id=~s/[\-\:]//g;
1.420     www      10495:         $idresponses{$id}[$number]=$entries[6];
                   10496:     }
1.524     raeburn  10497:     foreach my $id (keys(%idresponses)) {
1.420     www      10498:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10499:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10500:     }
                   10501:     return ($errormsg,$number);
                   10502: }
                   10503: 
1.596.2.12.2.  (raeburn 10504:): sub turning_eval {
                   10505:):     my ($questiontitles,$responses)=@_;
                   10506:):     my $number=0;
                   10507:):     my $errormsg='';
                   10508:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10509:):         my %components=&Apache::loncommon::record_sep($line);
                   10510:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10511:):         if ($#entries>$number) { $number=$#entries; }
                   10512:):         my $id=$entries[0];
                   10513:):         my @idresponses;
                   10514:):         $id=~s/^[\#0]+//;
                   10515:):         unless ($id) { next; }
                   10516:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10517:):             $entries[$idx]=~s/\,/\;/g;
                   10518:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10519:):             push(@idresponses,$entries[$idx]);
                   10520:):         }
                   10521:):         $$responses{$id}=join(',',@idresponses);
                   10522:):     }
                   10523:):     for (my $i=1; $i<=$number; $i++) {
                   10524:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10525:):     }
                   10526:):     return ($errormsg,$number);
                   10527:): }
                   10528:): 
1.414     www      10529: sub assign_clicker_grades {
                   10530:     my ($r)=@_;
                   10531:     my ($symb)=&get_symb($r);
                   10532:     if (!$symb) {return '';}
1.416     www      10533: # See which part we are saving to
1.582     raeburn  10534:     my $res_error;
                   10535:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10536:     if ($res_error) {
                   10537:         return &navmap_errormsg();
                   10538:     }
1.416     www      10539: # FIXME: This should probably look for the first handgradeable part
                   10540:     my $part=$$partlist[0];
                   10541: # Start screen output
1.596.2.10  raeburn  10542:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  10543: 
1.596.2.10  raeburn  10544:     $result .= '<br />'.
                   10545:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  10546:                &Apache::loncommon::start_data_table_header_row().
                   10547:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10548:                &Apache::loncommon::end_data_table_header_row().
                   10549:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      10550: 
1.414     www      10551: # Get correct result
                   10552: # FIXME: Possibly need delimiter other than ":"
                   10553:     my @correct=();
1.415     www      10554:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10555:     my $number=$env{'form.number'};
                   10556:     if ($gradingmechanism ne 'attendance') {
1.414     www      10557:        foreach my $key (keys(%env)) {
                   10558:           if ($key=~/^form\.correct\:/) {
                   10559:              my @input=split(/\,/,$env{$key});
                   10560:              for (my $i=0;$i<=$#input;$i++) {
                   10561:                  if (($correct[$i]) && ($input[$i]) &&
                   10562:                      ($correct[$i] ne $input[$i])) {
                   10563:                     $result.='<br /><span class="LC_warning">'.
                   10564:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10565:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10566:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10567:                     $correct[$i]=$input[$i];
                   10568:                  }
                   10569:              }
                   10570:           }
                   10571:        }
1.415     www      10572:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10573:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10574:              $result.='<br /><span class="LC_error">'.
                   10575:                       &mt('No correct result given for question "[_1]"!',
                   10576:                           $env{'form.question:'.$i}).'</span>';
                   10577:           }
                   10578:        }
1.596.2.4  raeburn  10579:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10580:     }
                   10581: # Start grading
1.415     www      10582:     my $pcorrect=$env{'form.pcorrect'};
                   10583:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10584:     my $storecount=0;
1.596.2.4  raeburn  10585:     my %users=();
1.415     www      10586:     foreach my $key (keys(%env)) {
1.420     www      10587:        my $user='';
1.415     www      10588:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10589:           $user=$1;
                   10590:        }
                   10591:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10592:           my $id=$1;
                   10593:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10594:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10595:           } elsif ($env{'form.multi'.$id}) {
                   10596:              $user=$env{'form.multi'.$id};
1.420     www      10597:           }
                   10598:        }
1.596.2.4  raeburn  10599:        if ($user) {
                   10600:           if ($users{$user}) {
                   10601:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10602:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10603:                       '</span><br />';
                   10604:           }
                   10605:           $users{$user}=1;
1.415     www      10606:           my @answer=split(/\,/,$env{$key});
                   10607:           my $sum=0;
1.522     www      10608:           my $realnumber=$number;
1.415     www      10609:           for (my $i=0;$i<$number;$i++) {
1.576     www      10610:              if  ($correct[$i] eq '-') {
                   10611:                 $realnumber--;
                   10612:              } elsif ($answer[$i]) {
1.415     www      10613:                 if ($gradingmechanism eq 'attendance') {
                   10614:                    $sum+=$pcorrect;
1.576     www      10615:                 } elsif ($correct[$i] eq '*') {
1.522     www      10616:                    $sum+=$pcorrect;
1.415     www      10617:                 } else {
1.596.2.4  raeburn  10618: # We actually grade if correct or not
                   10619:                    my $increment=$pincorrect;
                   10620: # Special case: numerical answer "0"
                   10621:                    if ($correct[$i] eq '0') {
                   10622:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10623:                          $increment=$pcorrect;
                   10624:                       }
                   10625: # General numerical answer, both evaluate to something non-zero
                   10626:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10627:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10628:                          $increment=$pcorrect;
                   10629:                       }
                   10630: # Must be just alphanumeric
                   10631:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10632:                       $increment=$pcorrect;
1.415     www      10633:                    }
1.596.2.4  raeburn  10634:                    $sum+=$increment;
1.415     www      10635:                 }
                   10636:              }
                   10637:           }
1.522     www      10638:           my $ave=$sum/(100*$realnumber);
1.416     www      10639: # Store
                   10640:           my ($username,$domain)=split(/\:/,$user);
                   10641:           my %grades=();
                   10642:           $grades{"resource.$part.solved"}='correct_by_override';
                   10643:           $grades{"resource.$part.awarded"}=$ave;
                   10644:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10645:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10646:                                                  $env{'request.course.id'},
                   10647:                                                  $domain,$username);
                   10648:           if ($returncode ne 'ok') {
                   10649:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10650:           } else {
                   10651:              $storecount++;
                   10652:           }
1.415     www      10653:        }
                   10654:     }
                   10655: # We are done
1.549     hauer    10656:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10657:              '</td>'.
                   10658:              &Apache::loncommon::end_data_table_row().
                   10659:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      10660:     return $result.&show_grading_menu_form($symb);
                   10661: }
                   10662: 
1.582     raeburn  10663: sub navmap_errormsg {
                   10664:     return '<div class="LC_error">'.
                   10665:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10666:            &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  10667:            '</div>';
                   10668: }
                   10669: 
1.596.2.12.2.  (raeburn 10670:): sub startpage {
          1.2.3(ra 10671:eb-19):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
                   10672:eb-19):     my %args;
                   10673:eb-19):     if ($onload) {
                   10674:eb-19):          my %loaditems = (
                   10675:eb-19):                         'onload' => $onload,
                   10676:eb-19):                       );
                   10677:eb-19):          $args{'add_entries'} = \%loaditems;
                   10678:eb-19):     }
          (raeburn 10679:):     if ($nomenu) {
          1.2.3(ra 10680:eb-19):         $args{'only_body'} = 1;
                   10681:eb-19):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
          (raeburn 10682:):     } else {
          1.2.3(ra 10683:eb-19):         $args{'bread_crumbs'} = $crumbs;
                   10684:eb-19):         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
          (raeburn 10685:):     }
                   10686:):     unless ($nodisplayflag) {
                   10687:):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
                   10688:):     }
                   10689:): }
                   10690:): 
1.1       albertel 10691: sub handler {
1.41      ng       10692:     my $request=$_[0];
1.434     albertel 10693:     &reset_caches();
1.596.2.4  raeburn  10694:     if ($request->header_only) {
                   10695:         &Apache::loncommon::content_type($request,'text/html');
                   10696:         $request->send_http_header;
                   10697:         return OK;
1.41      ng       10698:     }
                   10699:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10700: 
1.324     albertel 10701:     my $symb=&get_symb($request,1);
1.160     albertel 10702:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10703:     my $command=$commands[0];
1.447     foxr     10704: 
1.160     albertel 10705:     if ($#commands > 0) {
                   10706: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10707:     }
1.447     foxr     10708: 
1.513     foxr     10709:     $ssi_error = 0;
1.535     raeburn  10710:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  10711:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.12.2.  (raeburn 10712:):                                                     {'bread_crumbs' => $brcrum});
1.324     albertel 10713:     if ($symb eq '' && $command eq '') {
1.257     albertel 10714: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  10715:             &Apache::loncommon::content_type($request,'text/html');
                   10716:             $request->send_http_header;
                   10717:             $request->print($start_page);
1.257     albertel 10718: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   10719: 		($env{'form.codethree'})) {
                   10720: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   10721: 		    $env{'form.codethree'};
1.41      ng       10722: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   10723: 		    &Apache::lonnet::checkin($token);
                   10724: 		if ($tsymb) {
1.137     albertel 10725: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       10726: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     10727: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 10728: 					  ('grade_username' => $tuname,
                   10729: 					   'grade_domain' => $tudom,
                   10730: 					   'grade_courseid' => $tcrsid,
                   10731: 					   'grade_symb' => $tsymb)));
1.41      ng       10732: 		    } else {
1.45      ng       10733: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 10734: 		    }
1.41      ng       10735: 		} else {
1.45      ng       10736: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       10737: 		}
1.14      www      10738: 	    } else {
1.41      ng       10739: 		$request->print(&Apache::lonxml::tokeninputfield());
                   10740: 	    }
1.596.2.4  raeburn  10741:         } elsif ($env{'request.course.id'}) {
                   10742:             &init_perm(); 
                   10743:             if (!%perm) {
                   10744:                 $request->internal_redirect('/adm/quickgrades');
1.596.2.12.2.  3(raebur 10745:3):                 return OK;
1.596.2.4  raeburn  10746:             } else {
                   10747:                 &Apache::loncommon::content_type($request,'text/html');
                   10748:                 $request->send_http_header;
                   10749:                 $request->print($start_page);
                   10750:             }
                   10751:         }
1.41      ng       10752:     } else {
1.596.2.4  raeburn  10753:         &init_perm();
                   10754:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  10755:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10756:                     ($command =~ /^scantronupload/)) {
                   10757:                 # Not in a course.
                   10758:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10759:                 return HTTP_NOT_ACCEPTABLE;
                   10760:             }
1.596.2.4  raeburn  10761:         } elsif (!%perm) {
                   10762:             $request->internal_redirect('/adm/quickgrades');
                   10763:         }
                   10764:         &Apache::loncommon::content_type($request,'text/html');
                   10765:         $request->send_http_header;
1.596.2.12.2.  1.2.3(ra 10766:eb-19):         if (($command eq 'scantron_selectphase' && $perm{'mgr'}) || 
                   10767:eb-19):             (($command eq 'scantronupload') &&
                   10768:eb-19):              (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   10769:eb-19):               &Apache::lonnet::allowed('usc',$env{'request.course.id'})))) {
                   10770:eb-19):             &startpage($request,$symb,[{href=>'/adm/grades', text=>"Grading"}],1,1,
                   10771:eb-19):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   10772:eb-19):         } else {
                   10773:eb-19):             unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
                   10774:eb-19):                 $request->print($start_page); 
                   10775:eb-19):             }
          (raeburn 10776:):         }
1.104     albertel 10777: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.596.2.12.2.  (raeburn 10778:):             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10779:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10780:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10781:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10782:):                                               $env{'form.userdom'});
                   10783:):             }
                   10784:):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10785:):             if ($versionform) {
                   10786:):                 $request->print($versionform);
                   10787:):             }
                   10788:):             $request->print('<br clear="all" />');
1.257     albertel 10789: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.596.2.12.2.  (raeburn 10790:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10791:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10792:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10793:):                                           $env{'form.userdom'},
                   10794:):                                           $env{'form.inhibitmenu'});
                   10795:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10796:):             if ($versionform) {
                   10797:):                 $request->print($versionform);
                   10798:):             }
                   10799:):             $request->print('<br clear="all" />');
                   10800:):             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10801: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       10802: 	    &pickStudentPage($request);
1.103     albertel 10803: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       10804: 	    &displayPage($request);
1.104     albertel 10805: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       10806: 	    &updateGradeByPage($request);
1.104     albertel 10807: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       10808: 	    &processGroup($request);
1.104     albertel 10809: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 10810: 	    $request->print(&grading_menu($request));
                   10811: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   10812: 	    $request->print(&submit_options($request));
1.104     albertel 10813: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       10814: 	    $request->print(&viewgrades($request));
1.104     albertel 10815: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       10816: 	    $request->print(&processHandGrade($request));
1.106     albertel 10817: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       10818: 	    $request->print(&editgrades($request));
1.106     albertel 10819: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       10820: 	    $request->print(&verifyreceipt($request));
1.400     www      10821:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   10822:             $request->print(&process_clicker($request));
                   10823:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   10824:             $request->print(&process_clicker_file($request));
1.414     www      10825:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   10826:             $request->print(&assign_clicker_grades($request));
1.106     albertel 10827: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       10828: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 10829: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       10830: 	    $request->print(&csvupload($request));
1.106     albertel 10831: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       10832: 	    $request->print(&csvuploadmap($request));
1.246     albertel 10833: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10834: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 10835: 		$request->print(&csvuploadoptions($request));
1.41      ng       10836: 	    } else {
1.257     albertel 10837: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10838: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10839: 		} else {
1.257     albertel 10840: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10841: 		}
                   10842: 		$request->print(&csvuploadmap($request));
                   10843: 	    }
1.246     albertel 10844: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10845: 	    $request->print(&csvuploadassign($request));
1.106     albertel 10846: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 10847: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 10848:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10849:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 10850: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   10851: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 10852: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 10853: 	    $request->print(&scantron_process_students($request));
1.157     albertel 10854:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10855:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10856: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 10857:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 10858:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10859:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10860: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 10861:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 10862:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10863: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 10864:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  10865:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   10866:             $request->print(&checkscantron_results($request));     
1.106     albertel 10867: 	} elsif ($command) {
1.562     bisitz   10868: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10869: 	}
1.2       albertel 10870:     }
1.513     foxr     10871:     if ($ssi_error) {
                   10872: 	&ssi_print_error($request);
                   10873:     }
1.353     albertel 10874:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 10875:     &reset_caches();
1.596.2.4  raeburn  10876:     return OK;
1.44      ng       10877: }
                   10878: 
1.1       albertel 10879: 1;
                   10880: 
1.13      albertel 10881: __END__;
1.531     jms      10882: 
                   10883: 
                   10884: =head1 NAME
                   10885: 
                   10886: Apache::grades
                   10887: 
                   10888: =head1 SYNOPSIS
                   10889: 
                   10890: Handles the viewing of grades.
                   10891: 
                   10892: This is part of the LearningOnline Network with CAPA project
                   10893: described at http://www.lon-capa.org.
                   10894: 
                   10895: =head1 OVERVIEW
                   10896: 
                   10897: Do an ssi with retries:
                   10898: While I'd love to factor out this with the vesrion in lonprintout,
                   10899: 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
                   10900: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10901: 
                   10902: At least the logic that drives this has been pulled out into loncommon.
                   10903: 
                   10904: 
                   10905: 
                   10906: ssi_with_retries - Does the server side include of a resource.
                   10907:                      if the ssi call returns an error we'll retry it up to
                   10908:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 10909:4):                      If we still have a problem, no text is appended to the
1.531     jms      10910:                      output and we set some global variables.
                   10911:                      to indicate to the caller an SSI error occurred.  
                   10912:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 10913:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      10914:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10915:                      by informing the user that this happened.
                   10916: 
                   10917: Parameters:
                   10918:   resource   - The resource to include.  This is passed directly, without
                   10919:                interpretation to lonnet::ssi.
                   10920:   form       - The form hash parameters that guide the interpretation of the resource
                   10921:                
                   10922:   retries    - Number of retries allowed before giving up completely.
                   10923: Returns:
                   10924:   On success, returns the rendered resource identified by the resource parameter.
                   10925: Side Effects:
                   10926:   The following global variables can be set:
                   10927:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10928:                               It is up to the caller to initialize this to false
                   10929:                               if desired.
                   10930:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10931:                               of the resource that could not be rendered by the ssi
                   10932:                               call.
                   10933:    ssi_error_message   - The error string fetched from the ssi response
                   10934:                               in the event of an error.
                   10935: 
                   10936: 
                   10937: =head1 HANDLER SUBROUTINE
                   10938: 
                   10939: ssi_with_retries()
                   10940: 
                   10941: =head1 SUBROUTINES
                   10942: 
                   10943: =over
                   10944: 
                   10945: =item scantron_get_correction() : 
                   10946: 
                   10947:    Builds the interface screen to interact with the operator to fix a
                   10948:    specific error condition in a specific scanline
                   10949: 
                   10950:  Arguments:
                   10951:     $r           - Apache request object
                   10952:     $i           - number of the current scanline
                   10953:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  1.2.3(ra 10954:eb-19):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      10955:     $line        - full contents of the current scanline
                   10956:     $error       - error condition, valid values are
                   10957:                    'incorrectCODE', 'duplicateCODE',
                   10958:                    'doublebubble', 'missingbubble',
                   10959:                    'duplicateID', 'incorrectID'
                   10960:     $arg         - extra information needed
                   10961:        For errors:
                   10962:          - duplicateID   - paper number that this studentID was seen before on
                   10963:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10964:                            seen on before
                   10965:          - incorrectCODE - current incorrect CODE 
                   10966:          - doublebubble  - array ref of the bubble lines that have double
                   10967:                            bubble errors
                   10968:          - missingbubble - array ref of the bubble lines that have missing
                   10969:                            bubble errors
                   10970: 
1.596.2.12.2.  6(raebur 10971:3):    $randomorder - True if exam folder has randomorder set
                   10972:3):    $randompick  - True if exam folder has randompick set
                   10973:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10974:3):                      for current line to question number used for same question
                   10975:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   10976:3):    $startline   - Reference to hash where key is question number (0 is first)
                   10977:3):                   and value is number of first bubble line for current student
                   10978:3):                   or code-based randompick and/or randomorder.
                   10979:3): 
                   10980:3): 
1.531     jms      10981: =item  scantron_get_maxbubble() : 
                   10982: 
1.582     raeburn  10983:    Arguments:
                   10984:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10985:                       failure to retrieve a navmap object.
                   10986:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10987:        calling routine should trap the error condition and display the warning
                   10988:        found in &navmap_errormsg().
                   10989: 
1.596.2.12.2.  (raeburn 10990:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   10991:): 
1.531     jms      10992:    Returns the maximum number of bubble lines that are expected to
                   10993:    occur. Does this by walking the selected sequence rendering the
                   10994:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10995:    for what the current value of the problem counter is.
                   10996: 
                   10997:    Caches the results to $env{'form.scantron_maxbubble'},
                   10998:    $env{'form.scantron.bubble_lines.n'}, 
                   10999:    $env{'form.scantron.first_bubble_line.n'} and
                   11000:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11001:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11002:    lines for response n and number of the first bubble line for response n,
                   11003:    and a comma separated list of numbers of bubble lines for sub-questions
                   11004:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11005: 
                   11006: 
                   11007: =item  scantron_validate_missingbubbles() : 
                   11008: 
                   11009:    Validates all scanlines in the selected file to not have any
                   11010:     answers that don't have bubbles that have not been verified
                   11011:     to be bubble free.
                   11012: 
                   11013: =item  scantron_process_students() : 
                   11014: 
1.596.2.6  raeburn  11015:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11016: 
                   11017:    The parsed scanline hash is added to %env 
                   11018: 
                   11019:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11020:    foreach resource , with the form data of
                   11021: 
                   11022: 	'submitted'     =>'scantron' 
                   11023: 	'grade_target'  =>'grade',
                   11024: 	'grade_username'=> username of student
                   11025: 	'grade_domain'  => domain of student
                   11026: 	'grade_courseid'=> of course
                   11027: 	'grade_symb'    => symb of resource to grade
                   11028: 
                   11029:     This triggers a grading pass. The problem grading code takes care
                   11030:     of converting the bubbled letter information (now in %env) into a
                   11031:     valid submission.
                   11032: 
                   11033: =item  scantron_upload_scantron_data() :
                   11034: 
1.596.2.6  raeburn  11035:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11036: 
                   11037: =item  scantron_upload_scantron_data_save() : 
                   11038: 
                   11039:    Adds a provided bubble information data file to the course if user
                   11040:    has the correct privileges to do so. 
                   11041: 
                   11042: =item  valid_file() :
                   11043: 
                   11044:    Validates that the requested bubble data file exists in the course.
                   11045: 
                   11046: =item  scantron_download_scantron_data() : 
                   11047: 
                   11048:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11049:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11050:    course.
                   11051: 
                   11052: =item  scantron_validate_ID() : 
                   11053: 
                   11054:    Validates all scanlines in the selected file to not have any
1.556     weissno  11055:    invalid or underspecified student/employee IDs
1.531     jms      11056: 
1.582     raeburn  11057: =item navmap_errormsg() :
                   11058: 
                   11059:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11060:    Should be called whenever the request to instantiate a navmap object fails.  
                   11061: 
1.531     jms      11062: =back
                   11063: 
                   11064: =cut

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