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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.772   ! raeburn     4: # $Id: grades.pm,v 1.771 2020/08/26 18:13:40 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.752     raeburn    49: use Apache::lontexconvert();
1.170     albertel   50: use String::Similarity;
1.760     raeburn    51: use HTML::Parser();
                     52: use File::MMagic;
1.359     www        53: use LONCAPA;
                     54: 
1.315     bowersj2   55: use POSIX qw(floor);
1.87      www        56: 
1.435     foxr       57: 
1.513     foxr       58: 
1.435     foxr       59: my %perm=();
1.674     raeburn    60: my %old_essays=();
1.447     foxr       61: 
1.513     foxr       62: #  These variables are used to recover from ssi errors
                     63: 
                     64: my $ssi_retries = 5;
                     65: my $ssi_error;
                     66: my $ssi_error_resource;
                     67: my $ssi_error_message;
                     68: 
                     69: 
                     70: sub ssi_with_retries {
                     71:     my ($resource, $retries, %form) = @_;
                     72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     73:     if ($response->is_error) {
                     74: 	$ssi_error          = 1;
                     75: 	$ssi_error_resource = $resource;
                     76: 	$ssi_error_message  = $response->code . " " . $response->message;
                     77:     }
                     78: 
                     79:     return $content;
                     80: 
                     81: }
                     82: #
                     83: #  Prodcuces an ssi retry failure error message to the user:
                     84: #
                     85: 
                     86: sub ssi_print_error {
                     87:     my ($r) = @_;
1.516     raeburn    88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     89:     $r->print('
                     90: <br />
                     91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     92: <p>
                     93: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     95: '.&mt('Error:').' '.$ssi_error_message.'
                     96: </p>
                     97: <p>'.
                     98: &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 />'.
                     99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    100: '</p>');
                    101:     return;
1.513     foxr      102: }
                    103: 
1.44      ng        104: #
1.146     albertel  105: # --- Retrieve the parts from the metadata file.---
1.598     www       106: # Returns an array of everything that the resources stores away
                    107: #
                    108: 
1.44      ng        109: sub getpartlist {
1.582     raeburn   110:     my ($symb,$errorref) = @_;
1.439     albertel  111: 
                    112:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   113:     unless (ref($navmap)) {
                    114:         if (ref($errorref)) { 
                    115:             $$errorref = 'navmap';
                    116:             return;
                    117:         }
                    118:     }
1.439     albertel  119:     my $res      = $navmap->getBySymb($symb);
                    120:     my $partlist = $res->parts();
                    121:     my $url      = $res->src();
1.745     raeburn   122:     my $toolsymb;
                    123:     if ($url =~ /ext\.tool$/) {
                    124:         $toolsymb = $symb;
                    125:     }
                    126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  127: 
1.146     albertel  128:     my @stores;
1.439     albertel  129:     foreach my $part (@{ $partlist }) {
1.146     albertel  130: 	foreach my $key (@metakeys) {
                    131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    132: 	}
                    133:     }
                    134:     return @stores;
1.2       albertel  135: }
                    136: 
1.129     ng        137: #--- Format fullname, username:domain if different for display
                    138: #--- Use anywhere where the student names are listed
                    139: sub nameUserString {
                    140:     my ($type,$fullname,$uname,$udom) = @_;
                    141:     if ($type eq 'header') {
1.485     albertel  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        143:     } else {
1.398     albertel  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        146:     }
                    147: }
                    148: 
1.44      ng        149: #--- Get the partlist and the response type for a given problem. ---
                    150: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       151: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        152: sub response_type {
1.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.392     albertel  168:     my %vPart = 
                    169: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  170:     my (%response_types,%handgrade);
                    171:     foreach my $part (@{ $partlist }) {
1.392     albertel  172: 	next if (%vPart && !exists($vPart{$part}));
                    173: 
1.377     albertel  174: 	my @types = $res->responseType($part);
                    175: 	my @ids = $res->responseIds($part);
                    176: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    177: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    178: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    179: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    180: 				     '.handgrade',$symb);
1.41      ng        181: 	}
                    182:     }
1.377     albertel  183:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        184: }
                    185: 
1.375     albertel  186: sub flatten_responseType {
                    187:     my ($responseType) = @_;
                    188:     my @part_response_id =
                    189: 	map { 
                    190: 	    my $part = $_;
                    191: 	    map {
                    192: 		[$part,$_]
                    193: 		} sort(keys(%{ $responseType->{$part} }));
                    194: 	} sort(keys(%$responseType));
                    195:     return @part_response_id;
                    196: }
                    197: 
1.207     albertel  198: sub get_display_part {
1.324     albertel  199:     my ($partID,$symb)=@_;
1.207     albertel  200:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    201:     if (defined($display) and $display ne '') {
1.577     bisitz    202:         $display.= ' (<span class="LC_internal_info">'
                    203:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  204:     } else {
                    205: 	$display=$partID;
                    206:     }
                    207:     return $display;
                    208: }
1.269     raeburn   209: 
1.434     albertel  210: sub reset_caches {
                    211:     &reset_analyze_cache();
                    212:     &reset_perm();
1.674     raeburn   213:     &reset_old_essays();
1.434     albertel  214: }
                    215: 
                    216: {
                    217:     my %analyze_cache;
1.557     raeburn   218:     my %analyze_cache_formkeys;
1.148     albertel  219: 
1.434     albertel  220:     sub reset_analyze_cache {
                    221: 	undef(%analyze_cache);
1.557     raeburn   222:         undef(%analyze_cache_formkeys);
1.434     albertel  223:     }
                    224: 
                    225:     sub get_analyze {
1.649     raeburn   226: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  227: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   228:         if ($type eq 'randomizetry') {
                    229:             if ($trial ne '') {
                    230:                 $key .= "\0".$trial;
                    231:             }
                    232:         }
1.557     raeburn   233: 	if (exists($analyze_cache{$key})) {
                    234:             my $getupdate = 0;
                    235:             if (ref($add_to_hash) eq 'HASH') {
                    236:                 foreach my $item (keys(%{$add_to_hash})) {
                    237:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    238:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    239:                             $getupdate = 1;
                    240:                             last;
                    241:                         }
                    242:                     } else {
                    243:                         $getupdate = 1;
                    244:                     }
                    245:                 }
                    246:             }
                    247:             if (!$getupdate) {
                    248:                 return $analyze_cache{$key};
                    249:             }
                    250:         }
1.434     albertel  251: 
                    252: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    253: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   254:         my %form = ('grade_target'      => 'analyze',
                    255:                     'grade_domain'      => $udom,
                    256:                     'grade_symb'        => $symb,
                    257:                     'grade_courseid'    =>  $env{'request.course.id'},
                    258:                     'grade_username'    => $uname,
                    259:                     'grade_noincrement' => $no_increment);
1.649     raeburn   260:         if ($bubbles_per_row ne '') {
                    261:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    262:         }
1.640     raeburn   263:         if ($type eq 'randomizetry') {
                    264:             $form{'grade_questiontype'} = $type;
                    265:             if ($rndseed ne '') {
                    266:                 $form{'grade_rndseed'} = $rndseed;
                    267:             }
                    268:         }
1.557     raeburn   269:         if (ref($add_to_hash)) {
                    270:             %form = (%form,%{$add_to_hash});
1.640     raeburn   271:         }
1.557     raeburn   272: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  273: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    274: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   275:         if (ref($add_to_hash) eq 'HASH') {
                    276:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    277:         } else {
                    278:             $analyze_cache_formkeys{$key} = {};
                    279:         }
1.434     albertel  280: 	return $analyze_cache{$key} = \%analyze;
                    281:     }
                    282: 
                    283:     sub get_order {
1.640     raeburn   284: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    285: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  286: 	return $analyze->{"$partid.$respid.shown"};
                    287:     }
                    288: 
                    289:     sub get_radiobutton_correct_foil {
1.640     raeburn   290: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    291: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    292:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   293:         if (ref($foils) eq 'ARRAY') {
                    294: 	    foreach my $foil (@{$foils}) {
                    295: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    296: 		    return $foil;
                    297: 	        }
1.434     albertel  298: 	    }
                    299: 	}
                    300:     }
1.554     raeburn   301: 
                    302:     sub scantron_partids_tograde {
1.741     raeburn   303:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   304:         my (%analysis,@parts);
                    305:         if (ref($resource)) {
                    306:             my $symb = $resource->symb();
1.557     raeburn   307:             my $add_to_form;
                    308:             if ($check_for_randomlist) {
                    309:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    310:             }
1.741     raeburn   311:             if ($scancode) {
                    312:                 if (ref($add_to_form) eq 'HASH') {
                    313:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    314:                 } else {
                    315:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    316:                 }
                    317:             }
1.767     raeburn   318:             my $analyze =
1.649     raeburn   319:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    320:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   321:             if (ref($analyze) eq 'HASH') {
                    322:                 %analysis = %{$analyze};
                    323:             }
                    324:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    325:                 foreach my $part (@{$analysis{'parts'}}) {
                    326:                     my ($id,$respid) = split(/\./,$part);
                    327:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    328:                         push(@parts,$part);
                    329:                     }
                    330:                 }
                    331:             }
                    332:         }
                    333:         return (\%analysis,\@parts);
                    334:     }
                    335: 
1.148     albertel  336: }
1.434     albertel  337: 
1.118     ng        338: #--- Clean response type for display
1.335     albertel  339: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    340: #        response types only.
1.118     ng        341: sub cleanRecord {
1.336     albertel  342:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   343: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  344:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  345:     if ($response =~ /^(option|rank)$/) {
                    346: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     347:         my @answer = %answer;
1.767     raeburn   348:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    350: 	my ($toprow,$bottomrow);
                    351: 	foreach my $foil (@$order) {
                    352: 	    if ($grading{$foil} == 1) {
                    353: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    354: 	    } else {
                    355: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    356: 	    }
1.398     albertel  357: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  358: 	}
                    359: 	return '<blockquote><table border="1">'.
1.466     albertel  360: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    361: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   362: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  363:     } elsif ($response eq 'match') {
                    364: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     365:         my @answer = %answer;
1.767     raeburn   366:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  367: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    368: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    369: 	my ($toprow,$middlerow,$bottomrow);
                    370: 	foreach my $foil (@$order) {
                    371: 	    my $item=shift(@items);
                    372: 	    if ($grading{$foil} == 1) {
                    373: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  374: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  375: 	    } else {
                    376: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  377: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  378: 	    }
1.398     albertel  379: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        380: 	}
1.126     ng        381: 	return '<blockquote><table border="1">'.
1.466     albertel  382: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    383: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  384: 	    $middlerow.'</tr>'.
1.466     albertel  385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   386: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  387:     } elsif ($response eq 'radiobutton') {
                    388: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     389:         my @answer = %answer;
                    390:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  391: 	my ($toprow,$bottomrow);
1.434     albertel  392: 	my $correct = 
1.640     raeburn   393: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  394: 	foreach my $foil (@$order) {
1.148     albertel  395: 	    if (exists($answer{$foil})) {
1.434     albertel  396: 		if ($foil eq $correct) {
1.466     albertel  397: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  398: 		} else {
1.466     albertel  399: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  400: 		}
                    401: 	    } else {
1.466     albertel  402: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  403: 	    }
1.398     albertel  404: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  405: 	}
                    406: 	return '<blockquote><table border="1">'.
1.466     albertel  407: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    408: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   409: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  410:     } elsif ($response eq 'essay') {
1.257     albertel  411: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        412: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  413: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    414: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        415: 
1.257     albertel  416: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    417: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    418: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    419: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    420: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    421: 	    $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        422: 	}
1.751     raeburn   423:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     424: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  425:     } elsif ( $response eq 'organic') {
1.721     bisitz    426:         my $result=&mt('Smile representation: [_1]',
                    427:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  428: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    429: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    430: 	return $result;
1.335     albertel  431:     } elsif ( $response eq 'Task') {
                    432: 	if ( $answer eq 'SUBMITTED') {
                    433: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  434: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  435: 	    return $result;
                    436: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    437: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    438: 			       keys(%{$record}));
                    439: 	    return join('<br />',($version,@matches));
                    440: 			       
                    441: 			       
                    442: 	} else {
                    443: 	    my $result =
                    444: 		'<p>'
                    445: 		.&mt('Overall result: [_1]',
                    446: 		     $record->{$version."resource.$respid.$partid.status"})
                    447: 		.'</p>';
                    448: 	    
                    449: 	    $result .= '<ul>';
                    450: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    451: 			     keys(%{$record}));
                    452: 	    foreach my $grade (sort(@grade)) {
                    453: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    454: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    455: 				     $dim, $record->{$grade}).
                    456: 			  '</li>';
                    457: 	    }
                    458: 	    $result.='</ul>';
                    459: 	    return $result;
                    460: 	}
1.716     bisitz    461:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    462:         # Respect multiple input fields, see Bug #5409
1.440     albertel  463: 	$answer = 
                    464: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    465: 							      $answer);
1.720     kruse     466: 	return $answer;
1.122     ng        467:     }
1.720     kruse     468:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        469: }
                    470: 
                    471: #-- A couple of common js functions
                    472: sub commonJSfunctions {
                    473:     my $request = shift;
1.597     wenzelju  474:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        475:     function radioSelection(radioButton) {
                    476: 	var selection=null;
                    477: 	if (radioButton.length > 1) {
                    478: 	    for (var i=0; i<radioButton.length; i++) {
                    479: 		if (radioButton[i].checked) {
                    480: 		    return radioButton[i].value;
                    481: 		}
                    482: 	    }
                    483: 	} else {
                    484: 	    if (radioButton.checked) return radioButton.value;
                    485: 	}
                    486: 	return selection;
                    487:     }
                    488: 
                    489:     function pullDownSelection(selectOne) {
                    490: 	var selection="";
                    491: 	if (selectOne.length > 1) {
                    492: 	    for (var i=0; i<selectOne.length; i++) {
                    493: 		if (selectOne[i].selected) {
                    494: 		    return selectOne[i].value;
                    495: 		}
                    496: 	    }
                    497: 	} else {
1.138     albertel  498:             // only one value it must be the selected one
                    499: 	    return selectOne.value;
1.118     ng        500: 	}
                    501:     }
                    502: COMMONJSFUNCTIONS
                    503: }
                    504: 
1.44      ng        505: #--- Dumps the class list with usernames,list of sections,
                    506: #--- section, ids and fullnames for each user.
                    507: sub getclasslist {
1.750     raeburn   508:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  509:     my @getsec;
1.450     banghart  510:     my @getgroup;
1.442     banghart  511:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  512:     if (!ref($getsec)) {
                    513: 	if ($getsec ne '' && $getsec ne 'all') {
                    514: 	    @getsec=($getsec);
                    515: 	}
                    516:     } else {
                    517: 	@getsec=@{$getsec};
                    518:     }
                    519:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  520:     if (!ref($getgroup)) {
                    521: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    522: 	    @getgroup=($getgroup);
                    523: 	}
                    524:     } else {
                    525: 	@getgroup=@{$getgroup};
                    526:     }
                    527:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  528: 
1.449     banghart  529:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  530:     # Bail out if we were unable to get the classlist
1.56      matthew   531:     return if (! defined($classlist));
1.449     banghart  532:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   533:     #
                    534:     my %sections;
                    535:     my %fullnames;
1.750     raeburn   536:     my ($cdom,$cnum,$partlist);
                    537:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    538:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    539:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    540:         my $res_error;
                    541:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
                    542:     }
1.205     matthew   543:     foreach my $student (keys(%$classlist)) {
                    544:         my $end      = 
                    545:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    546:         my $start    = 
                    547:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    548:         my $id       = 
                    549:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    550:         my $section  = 
                    551:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    552:         my $fullname = 
                    553:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    554:         my $status   = 
                    555:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  556:         my $group   = 
                    557:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        558: 	# filter students according to status selected
1.750     raeburn   559: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  560: 	    if (!($stu_status =~ $status)) {
1.450     banghart  561: 		delete($classlist->{$student});
1.76      ng        562: 		next;
                    563: 	    }
                    564: 	}
1.450     banghart  565: 	# filter students according to groups selected
1.453     banghart  566: 	my @stu_groups = split(/,/,$group);
1.450     banghart  567: 	if (@getgroup) {
                    568: 	    my $exclude = 1;
1.454     banghart  569: 	    foreach my $grp (@getgroup) {
                    570: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  571: 	            if ($stu_group eq $grp) {
                    572: 	                $exclude = 0;
                    573:     	            } 
1.450     banghart  574: 	        }
1.453     banghart  575:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   576:         	    $exclude = 0;
1.453     banghart  577:         	}
1.450     banghart  578: 	    }
                    579: 	    if ($exclude) {
                    580: 	        delete($classlist->{$student});
1.750     raeburn   581: 		next;
1.450     banghart  582: 	    }
                    583: 	}
1.750     raeburn   584:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    585:             my $udom =
                    586:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    587:             my $uname =
                    588:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    589:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    590:                 if ($submitonly eq 'queued') {
                    591:                     my %queue_status =
                    592:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    593:                                                                 $udom,$uname);
                    594:                     if (!defined($queue_status{'gradingqueue'})) {
                    595:                         delete($classlist->{$student});
                    596:                         next;
                    597:                     }
                    598:                 } else {
                    599:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    600:                     my $submitted = 0;
                    601:                     my $graded = 0;
                    602:                     my $incorrect = 0;
                    603:                     foreach (keys(%status)) {
                    604:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    605:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    606:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    607: 
                    608:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    609:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    610:                             $submitted = 0;
                    611:                         }
                    612:                     }
                    613:                     if (!$submitted && ($submitonly eq 'yes' ||
                    614:                                         $submitonly eq 'incorrect' ||
                    615:                                         $submitonly eq 'graded')) {
                    616:                         delete($classlist->{$student});
                    617:                         next;
                    618:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    619:                         delete($classlist->{$student});
                    620:                         next;
                    621:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    622:                         delete($classlist->{$student});
                    623:                         next;
                    624:                     }
                    625:                 }
                    626:             }
                    627:         }
1.205     matthew   628: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  629: 	if (&canview($section)) {
1.291     albertel  630: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  631: 		$sections{$section}++;
1.450     banghart  632: 		if ($classlist->{$student}) {
                    633: 		    $fullnames{$student}=$fullname;
                    634: 		}
1.103     albertel  635: 	    } else {
1.205     matthew   636: 		delete($classlist->{$student});
1.103     albertel  637: 	    }
                    638: 	} else {
1.205     matthew   639: 	    delete($classlist->{$student});
1.103     albertel  640: 	}
1.44      ng        641:     }
1.56      matthew   642:     my @sections = sort(keys(%sections));
                    643:     return ($classlist,\@sections,\%fullnames);
1.44      ng        644: }
                    645: 
1.103     albertel  646: sub canmodify {
                    647:     my ($sec)=@_;
                    648:     if ($perm{'mgr'}) {
                    649: 	if (!defined($perm{'mgr_section'})) {
                    650: 	    # can modify whole class
                    651: 	    return 1;
                    652: 	} else {
                    653: 	    if ($sec eq $perm{'mgr_section'}) {
                    654: 		#can modify the requested section
                    655: 		return 1;
                    656: 	    } else {
1.763     raeburn   657: 		# can't modify the requested section
1.103     albertel  658: 		return 0;
                    659: 	    }
                    660: 	}
                    661:     }
                    662:     #can't modify
                    663:     return 0;
                    664: }
                    665: 
                    666: sub canview {
                    667:     my ($sec)=@_;
                    668:     if ($perm{'vgr'}) {
                    669: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   670: 	    # can view whole class
1.103     albertel  671: 	    return 1;
                    672: 	} else {
                    673: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   674: 		#can view the requested section
1.103     albertel  675: 		return 1;
                    676: 	    } else {
1.763     raeburn   677: 		# can't view the requested section
1.103     albertel  678: 		return 0;
                    679: 	    }
                    680: 	}
                    681:     }
1.763     raeburn   682:     #can't view
1.103     albertel  683:     return 0;
                    684: }
                    685: 
1.44      ng        686: #--- Retrieve the grade status of a student for all the parts
                    687: sub student_gradeStatus {
1.324     albertel  688:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  689:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        690:     my %partstatus = ();
                    691:     foreach (@$partlist) {
1.128     ng        692: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        693: 	$status              = 'nothing' if ($status eq '');
                    694: 	$partstatus{$_}      = $status;
                    695: 	my $subkey           = "resource.$_.submitted_by";
                    696: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    697:     }
                    698:     return %partstatus;
                    699: }
                    700: 
1.45      ng        701: # hidden form and javascript that calls the form
                    702: # Use by verifyscript and viewgrades
                    703: # Shows a student's view of problem and submission
                    704: sub jscriptNform {
1.324     albertel  705:     my ($symb) = @_;
1.442     banghart  706:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  707:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        708: 	'    function viewOneStudent(user,domain) {'."\n".
                    709: 	'	document.onestudent.student.value = user;'."\n".
                    710: 	'	document.onestudent.userdom.value = domain;'."\n".
                    711: 	'	document.onestudent.submit();'."\n".
                    712: 	'    }'."\n".
1.597     wenzelju  713: 	"\n");
1.45      ng        714:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  715: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  716: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        717: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    718: 	'<input type="hidden" name="student" value="" />'."\n".
                    719: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    720: 	'</form>'."\n";
                    721:     return $jscript;
                    722: }
1.39      ng        723: 
1.447     foxr      724: 
                    725: 
1.315     bowersj2  726: # Given the score (as a number [0-1] and the weight) what is the final
                    727: # point value? This function will round to the nearest tenth, third,
                    728: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  729: sub compute_points {
1.315     bowersj2  730:     my ($score, $weight) = @_;
                    731:     
                    732:     my $tolerance = .00001;
                    733:     my $points = $score * $weight;
                    734: 
                    735:     # Check for nearness to 1/x.
                    736:     my $check_for_nearness = sub {
                    737:         my ($factor) = @_;
                    738:         my $num = ($points * $factor) + $tolerance;
                    739:         my $floored_num = floor($num);
1.316     albertel  740:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  741:             return $floored_num / $factor;
                    742:         }
                    743:         return $points;
                    744:     };
                    745: 
                    746:     $points = $check_for_nearness->(10);
                    747:     $points = $check_for_nearness->(3);
                    748:     $points = $check_for_nearness->(4);
                    749:     
                    750:     return $points;
                    751: }
                    752: 
1.44      ng        753: #------------------ End of general use routines --------------------
1.87      www       754: 
                    755: #
                    756: # Find most similar essay
                    757: #
                    758: 
                    759: sub most_similar {
1.674     raeburn   760:     my ($uname,$udom,$symb,$uessay)=@_;
                    761: 
                    762:     unless ($symb) { return ''; }
                    763: 
                    764:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       765: 
                    766: # ignore spaces and punctuation
                    767: 
                    768:     $uessay=~s/\W+/ /gs;
                    769: 
1.282     www       770: # ignore empty submissions (occuring when only files are sent)
                    771: 
1.598     www       772:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       773: 
1.87      www       774: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       775:     my $limit=0.6;
1.87      www       776:     my $sname='';
                    777:     my $sdom='';
                    778:     my $scrsid='';
                    779:     my $sessay='';
                    780: # go through all essays ...
1.674     raeburn   781:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  782: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       783: # ... except the same student
1.426     albertel  784:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   785: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  786: 	$tessay=~s/\W+/ /gs;
1.87      www       787: # String similarity gives up if not even limit
1.426     albertel  788: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       789: # Found one
1.426     albertel  790: 	if ($tsimilar>$limit) {
                    791: 	    $limit=$tsimilar;
                    792: 	    $sname=$tname;
                    793: 	    $sdom=$tdom;
                    794: 	    $scrsid=$tcrsid;
1.674     raeburn   795: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  796: 	}
1.87      www       797:     }
1.88      www       798:     if ($limit>0.6) {
1.87      www       799:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    800:     } else {
                    801:        return ('','','','',0);
                    802:     }
                    803: }
                    804: 
1.44      ng        805: #-------------------------------------------------------------------
                    806: 
                    807: #------------------------------------ Receipt Verification Routines
1.45      ng        808: #
1.602     www       809: 
                    810: sub initialverifyreceipt {
1.608     www       811:    my ($request,$symb) = @_;
1.602     www       812:    &commonJSfunctions($request);
1.694     bisitz    813:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       814:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    815:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       816:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    817:         '<input type="hidden" name="command" value="verify" />'.
                    818:         "</form>\n";
1.602     www       819: }
                    820: 
1.44      ng        821: #--- Check whether a receipt number is valid.---
                    822: sub verifyreceipt {
1.766     raeburn   823:     my ($request,$symb) = @_;
1.44      ng        824: 
1.257     albertel  825:     my $courseid = $env{'request.course.id'};
1.184     www       826:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  827: 	$env{'form.receipt'};
1.44      ng        828:     $receipt     =~ s/[^\-\d]//g;
                    829: 
1.766     raeburn   830:     my $title =
1.487     albertel  831: 	'<h3><span class="LC_info">'.
1.605     www       832: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    833: 	'</span></h3>'."\n";
1.44      ng        834: 
                    835:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   836:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  837:     
                    838:     my $receiptparts=0;
1.390     albertel  839:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    840: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  841:     my $parts=['0'];
1.582     raeburn   842:     if ($receiptparts) {
                    843:         my $res_error; 
                    844:         ($parts)=&response_type($symb,\$res_error);
                    845:         if ($res_error) {
                    846:             return &navmap_errormsg();
                    847:         } 
                    848:     }
1.486     albertel  849:     
                    850:     my $header = 
                    851: 	&Apache::loncommon::start_data_table().
                    852: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  853: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    854: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    855: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  856:     if ($receiptparts) {
1.487     albertel  857: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  858:     }
                    859:     $header.=
                    860: 	&Apache::loncommon::end_data_table_header_row();
                    861: 
1.294     albertel  862:     foreach (sort 
                    863: 	     {
                    864: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    865: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    866: 		 }
                    867: 		 return $a cmp $b;
                    868: 	     } (keys(%$fullname))) {
1.44      ng        869: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  870: 	foreach my $part (@$parts) {
                    871: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  872: 		$contents.=
                    873: 		    &Apache::loncommon::start_data_table_row().
                    874: 		    '<td>&nbsp;'."\n".
1.177     albertel  875: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  876: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  877: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    878: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    879: 		if ($receiptparts) {
                    880: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    881: 		}
1.486     albertel  882: 		$contents.= 
                    883: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  884: 		
                    885: 		$matches++;
                    886: 	    }
1.44      ng        887: 	}
                    888:     }
                    889:     if ($matches == 0) {
1.584     bisitz    890:         $string = $title
                    891:                  .'<p class="LC_warning">'
                    892:                  .&mt('No match found for the above receipt number.')
                    893:                  .'</p>';
1.44      ng        894:     } else {
1.324     albertel  895: 	$string = &jscriptNform($symb).$title.
1.487     albertel  896: 	    '<p>'.
1.584     bisitz    897: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  898: 	    '</p>'.
1.486     albertel  899: 	    $header.
                    900: 	    $contents.
                    901: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        902:     }
1.614     www       903:     return $string;
1.44      ng        904: }
                    905: 
                    906: #--- This is called by a number of programs.
                    907: #--- Called from the Grading Menu - View/Grade an individual student
                    908: #--- Also called directly when one clicks on the subm button 
                    909: #    on the problem page.
1.30      ng        910: sub listStudents {
1.617     www       911:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  912: 
1.747     raeburn   913:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel  914:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    915:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    916:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  917:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       918:     unless ($submitonly) {
1.766     raeburn   919:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www       920:     }
1.49      albertel  921: 
1.632     www       922:     my $result='';
1.623     www       923:     my $res_error;
                    924:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  925: 
1.736     damieng   926:     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.736     damieng   930:     &js_escape(\%js_lt);
1.597     wenzelju  931:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        932:     function checkSelect(checkBox) {
                    933: 	var ctr=0;
                    934: 	var sense="";
                    935: 	if (checkBox.length > 1) {
                    936: 	    for (var i=0; i<checkBox.length; i++) {
                    937: 		if (checkBox[i].checked) {
                    938: 		    ctr++;
                    939: 		}
                    940: 	    }
1.736     damieng   941: 	    sense = '$js_lt{'multiple'}';
1.110     ng        942: 	} else {
                    943: 	    if (checkBox.checked) {
                    944: 		ctr = 1;
                    945: 	    }
1.736     damieng   946: 	    sense = '$js_lt{'single'}';
1.110     ng        947: 	}
                    948: 	if (ctr == 0) {
1.485     albertel  949: 	    alert(sense);
1.110     ng        950: 	    return false;
                    951: 	}
                    952: 	document.gradesub.submit();
                    953:     }
                    954: 
                    955:     function reLoadList(formname) {
1.112     ng        956: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        957: 	formname.command.value = 'submission';
                    958: 	formname.submit();
                    959:     }
1.45      ng        960: LISTJAVASCRIPT
                    961: 
1.118     ng        962:     &commonJSfunctions($request);
1.41      ng        963:     $request->print($result);
1.39      ng        964: 
1.154     albertel  965:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       966: 	"\n";
1.485     albertel  967: 	
1.561     bisitz    968:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn   969:     unless ($is_tool) {
                    970:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    971:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    972:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    973:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    974:                       .&Apache::lonhtmlcommon::row_closure();
                    975:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    976:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    977:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    978:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    979:                       .&Apache::lonhtmlcommon::row_closure();
                    980:     }
1.485     albertel  981: 
                    982:     my $submission_options;
1.442     banghart  983:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    984:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  985:     $env{'form.Status'} = $saveStatus;
1.745     raeburn   986:     my %optiontext;
                    987:     if ($is_tool) {
                    988:         %optiontext = &Apache::lonlocal::texthash (
                    989:                           lastonly => 'last transaction',
                    990:                           last     => 'last transaction with details',
                    991:                           datesub  => 'all transactions',
                    992:                           all      => 'all transactions with details',
                    993:                       );
                    994:     } else {
                    995:         %optiontext = &Apache::lonlocal::texthash (
                    996:                           lastonly => 'last submission',
                    997:                           last     => 'last submission with details',
                    998:                           datesub  => 'all submissions',
                    999:                           all      => 'all submissions with details',
                   1000:                       );
                   1001:     }
1.485     albertel 1002:     $submission_options.=
1.592     bisitz   1003:         '<span class="LC_nobreak">'.
1.624     www      1004:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1005:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1006:         '<span class="LC_nobreak">'.
                   1007:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1008:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1009:         '<span class="LC_nobreak">'.
1.628     www      1010:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1011:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1012:         '<span class="LC_nobreak">'.
                   1013:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1014:         $optiontext{'all'}.'</label></span>';
                   1015:     my $viewtitle;
                   1016:     if ($is_tool) {
                   1017:         $viewtitle = &mt('View Transactions');
                   1018:     } else {
                   1019:         $viewtitle = &mt('View Submissions');
                   1020:     }
                   1021:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1022:                   .$submission_options
                   1023:                   .&Apache::lonhtmlcommon::row_closure();
                   1024: 
1.745     raeburn  1025:     my $closure;
                   1026:     if (($is_tool) && (exists($env{'form.Status'}))) {
                   1027:         $closure = 1;
                   1028:     }
1.561     bisitz   1029:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1030:                   .'<select name="increment">'
                   1031:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1032:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1033:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1034:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1035:                   .'</select>'
1.745     raeburn  1036:                   .&Apache::lonhtmlcommon::row_closure($closure);
1.485     albertel 1037: 
                   1038:     $gradeTable .= 
1.432     banghart 1039:         &build_section_inputs().
1.45      ng       1040: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1041: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1042: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1043: 
1.618     www      1044:     if (exists($env{'form.Status'})) {
1.561     bisitz   1045: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1046:     } else {
1.745     raeburn  1047:         if ($is_tool) {
                   1048:             $closure = 1;
                   1049:         }
1.561     bisitz   1050:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1051:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1052:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1.745     raeburn  1053:                       .&Apache::lonhtmlcommon::row_closure($closure);
1.124     ng       1054:     }
1.112     ng       1055: 
1.745     raeburn  1056:     unless ($is_tool) {
                   1057:         $closure = 1;
                   1058:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1059:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1060:                       .&Apache::lonhtmlcommon::row_closure($closure);
                   1061:     }
                   1062:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
                   1063:     my $regrademsg;
                   1064:     if ($is_tool) {
                   1065:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   1066:     } else {
                   1067:         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   1068:     }
1.561     bisitz   1069:     $gradeTable .= '<p>'
1.745     raeburn  1070:                   .$regrademsg."\n"
1.561     bisitz   1071:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1072:                   .'</p>';
1.249     albertel 1073: 
                   1074: # checkall buttons
                   1075:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1076:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1077:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1078:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1079:     $gradeTable.=&check_buttons();
1.450     banghart 1080:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1081:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1082: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1083:     my $loop = 0;
                   1084:     while ($loop < 2) {
1.485     albertel 1085: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1086: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1087: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1088: 	    foreach my $part (sort(@$partlist)) {
                   1089: 		my $display_part=
                   1090: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1091: 		$gradeTable.=
                   1092: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1093: 	    }
1.301     albertel 1094: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1095: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1096: 	}
                   1097: 	$loop++;
1.126     ng       1098: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1099:     }
1.474     albertel 1100:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1101: 
1.45      ng       1102:     my $ctr = 0;
1.294     albertel 1103:     foreach my $student (sort 
                   1104: 			 {
                   1105: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1106: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1107: 			     }
                   1108: 			     return $a cmp $b;
                   1109: 			 }
                   1110: 			 (keys(%$fullname))) {
1.41      ng       1111: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1112: 
1.110     ng       1113: 	my %status = ();
1.301     albertel 1114: 
                   1115: 	if ($submitonly eq 'queued') {
                   1116: 	    my %queue_status = 
                   1117: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1118: 							$udom,$uname);
                   1119: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1120: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1121: 	}
                   1122: 
1.618     www      1123: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1124: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1125: 	    my $submitted = 0;
1.164     albertel 1126: 	    my $graded = 0;
1.248     albertel 1127: 	    my $incorrect = 0;
1.110     ng       1128: 	    foreach (keys(%status)) {
1.145     albertel 1129: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1130: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1131: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1132: 		
1.110     ng       1133: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1134: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1135: 		    $submitted = 0;
1.150     albertel 1136: 		    my ($part)=split(/\./,$partid);
1.110     ng       1137: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1138: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1139: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1140: 		}
1.41      ng       1141: 	    }
1.248     albertel 1142: 	    
1.156     albertel 1143: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1144: 				     $submitonly eq 'incorrect' ||
                   1145: 				     $submitonly eq 'graded'));
1.248     albertel 1146: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1147: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1148: 	}
1.34      ng       1149: 
1.45      ng       1150: 	$ctr++;
1.249     albertel 1151: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1152:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1153: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1154: 	    if ($ctr%2 ==1) {
                   1155: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1156: 	    }
1.126     ng       1157: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1158:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1159:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1160: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1161: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1162: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1163: 
1.618     www      1164: 	    if ($submitonly ne 'all') {
1.524     raeburn  1165: 		foreach (sort(keys(%status))) {
1.485     albertel 1166: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1167: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1168: 		}
1.41      ng       1169: 	    }
1.126     ng       1170: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1171: 	    if ($ctr%2 ==0) {
                   1172: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1173: 	    }
1.41      ng       1174: 	}
                   1175:     }
1.110     ng       1176:     if ($ctr%2 ==1) {
1.126     ng       1177: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1178: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1179: 		foreach (@$partlist) {
                   1180: 		    $gradeTable.='<td>&nbsp;</td>';
                   1181: 		}
1.301     albertel 1182: 	    } elsif ($submitonly eq 'queued') {
                   1183: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1184: 	    }
1.474     albertel 1185: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1186:     }
                   1187: 
1.474     albertel 1188:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1189:         '<input type="button" '.
                   1190:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1191:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1192:     if ($ctr == 0) {
1.96      albertel 1193: 	my $num_students=(scalar(keys(%$fullname)));
                   1194: 	if ($num_students eq 0) {
1.485     albertel 1195: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1196: 	} else {
1.171     albertel 1197: 	    my $submissions='submissions';
                   1198: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1199: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1200: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1201: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1202: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1203: 		    $num_students).
                   1204: 		'</span><br />';
1.96      albertel 1205: 	}
1.46      ng       1206:     } elsif ($ctr == 1) {
1.474     albertel 1207: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1208:     }
                   1209:     $request->print($gradeTable);
1.44      ng       1210:     return '';
1.10      ng       1211: }
                   1212: 
1.44      ng       1213: #---- Called from the listStudents routine
1.249     albertel 1214: 
                   1215: sub check_script {
1.766     raeburn  1216:     my ($form,$type) = @_;
                   1217:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1218:     function checkall() {
                   1219:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1220:             ele = document.forms.'.$form.'.elements[i];
                   1221:             if (ele.name == "'.$type.'") {
                   1222:             document.forms.'.$form.'.elements[i].checked=true;
                   1223:                                        }
                   1224:         }
                   1225:     }
                   1226: 
                   1227:     function checksec() {
                   1228:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1229:             ele = document.forms.'.$form.'.elements[i];
                   1230:            string = document.forms.'.$form.'.chksec.value;
                   1231:            if
                   1232:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1233:               document.forms.'.$form.'.elements[i].checked=true;
                   1234:             }
                   1235:         }
                   1236:     }
                   1237: 
                   1238: 
                   1239:     function uncheckall() {
                   1240:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1241:             ele = document.forms.'.$form.'.elements[i];
                   1242:             if (ele.name == "'.$type.'") {
                   1243:             document.forms.'.$form.'.elements[i].checked=false;
                   1244:                                        }
                   1245:         }
                   1246:     }
                   1247: 
1.597     wenzelju 1248: '."\n");
1.249     albertel 1249:     return $chkallscript;
                   1250: }
                   1251: 
                   1252: sub check_buttons {
1.485     albertel 1253:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1254:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1255:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1256:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1257:     return $buttons;
                   1258: }
                   1259: 
1.44      ng       1260: #     Displays the submissions for one student or a group of students
1.34      ng       1261: sub processGroup {
1.766     raeburn  1262:     my ($request,$symb) = @_;
1.41      ng       1263:     my $ctr        = 0;
1.155     albertel 1264:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1265:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1266: 
1.396     banghart 1267:     foreach my $student (@stuchecked) {
                   1268: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1269: 	$env{'form.student'}        = $uname;
                   1270: 	$env{'form.userdom'}        = $udom;
                   1271: 	$env{'form.fullname'}       = $fullname;
1.619     www      1272: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1273: 	$ctr++;
                   1274:     }
                   1275:     return '';
1.35      ng       1276: }
1.34      ng       1277: 
1.44      ng       1278: #------------------------------------------------------------------------------------
                   1279: #
                   1280: #-------------------------- Next few routines handles grading by student, essentially
                   1281: #                           handles essay response type problem/part
                   1282: #
                   1283: #--- Javascript to handle the submission page functionality ---
                   1284: sub sub_page_js {
                   1285:     my $request = shift;
1.736     damieng  1286:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1287:     &js_escape(\$alertmsg);
1.597     wenzelju 1288:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1289:     function updateRadio(formname,id,weight) {
1.125     ng       1290: 	var gradeBox = formname["GD_BOX"+id];
                   1291: 	var radioButton = formname["RADVAL"+id];
                   1292: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1293: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1294: 	gradeBox.value = pts;
                   1295: 	var resetbox = false;
                   1296: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1297: 	    alert("$alertmsg"+pts);
1.71      ng       1298: 	    for (var i=0; i<radioButton.length; i++) {
                   1299: 		if (radioButton[i].checked) {
                   1300: 		    gradeBox.value = i;
                   1301: 		    resetbox = true;
                   1302: 		}
                   1303: 	    }
                   1304: 	    if (!resetbox) {
                   1305: 		formtextbox.value = "";
                   1306: 	    }
                   1307: 	    return;
1.44      ng       1308: 	}
1.71      ng       1309: 
                   1310: 	if (pts > weight) {
                   1311: 	    var resp = confirm("You entered a value ("+pts+
                   1312: 			       ") greater than the weight for the part. Accept?");
                   1313: 	    if (resp == false) {
1.125     ng       1314: 		gradeBox.value = oldpts;
1.71      ng       1315: 		return;
                   1316: 	    }
1.44      ng       1317: 	}
1.13      albertel 1318: 
1.71      ng       1319: 	for (var i=0; i<radioButton.length; i++) {
                   1320: 	    radioButton[i].checked=false;
                   1321: 	    if (pts == i && pts != "") {
                   1322: 		radioButton[i].checked=true;
                   1323: 	    }
                   1324: 	}
                   1325: 	updateSelect(formname,id);
1.125     ng       1326: 	formname["stores"+id].value = "0";
1.41      ng       1327:     }
1.5       albertel 1328: 
1.72      ng       1329:     function writeBox(formname,id,pts) {
1.125     ng       1330: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1331: 	if (checkSolved(formname,id) == 'update') {
                   1332: 	    gradeBox.value = pts;
                   1333: 	} else {
1.125     ng       1334: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1335: 	    gradeBox.value = oldpts;
1.125     ng       1336: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1337: 	    for (var i=0; i<radioButton.length; i++) {
                   1338: 		radioButton[i].checked=false;
1.72      ng       1339: 		if (i == oldpts) {
1.71      ng       1340: 		    radioButton[i].checked=true;
                   1341: 		}
                   1342: 	    }
1.41      ng       1343: 	}
1.125     ng       1344: 	formname["stores"+id].value = "0";
1.71      ng       1345: 	updateSelect(formname,id);
                   1346: 	return;
1.41      ng       1347:     }
1.44      ng       1348: 
1.71      ng       1349:     function clearRadBox(formname,id) {
                   1350: 	if (checkSolved(formname,id) == 'noupdate') {
                   1351: 	    updateSelect(formname,id);
                   1352: 	    return;
                   1353: 	}
1.125     ng       1354: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1355: 	for (var i=0; i<gradeSelect.length; i++) {
                   1356: 	    if (gradeSelect[i].selected) {
                   1357: 		var selectx=i;
                   1358: 	    }
                   1359: 	}
1.125     ng       1360: 	var stores = formname["stores"+id];
1.71      ng       1361: 	if (selectx == stores.value) { return };
1.125     ng       1362: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1363: 	gradeBox.value = "";
1.125     ng       1364: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1365: 	for (var i=0; i<radioButton.length; i++) {
                   1366: 	    radioButton[i].checked=false;
                   1367: 	}
                   1368: 	stores.value = selectx;
                   1369:     }
1.5       albertel 1370: 
1.71      ng       1371:     function checkSolved(formname,id) {
1.125     ng       1372: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1373: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1374: 	    if (!reply) {return "noupdate";}
1.120     ng       1375: 	    formname.overRideScore.value = 'yes';
1.41      ng       1376: 	}
1.71      ng       1377: 	return "update";
1.13      albertel 1378:     }
1.71      ng       1379: 
                   1380:     function updateSelect(formname,id) {
1.125     ng       1381: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1382: 	return;
1.41      ng       1383:     }
1.33      ng       1384: 
1.121     ng       1385: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1386:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1387: 	formname.gradeOpt.value = val;
1.71      ng       1388: 	if (val == "Save & Next") {
                   1389: 	    for (i=0;i<=total;i++) {
                   1390: 		for (j=0;j<parttot;j++) {
1.125     ng       1391: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1392: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1393: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1394: 			if (points == "") {
1.125     ng       1395: 			    var name = formname["name"+i].value;
1.129     ng       1396: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1397: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1398: 					       ", part "+partid+". Continue?");
1.71      ng       1399: 			    if (resp == false) {
1.125     ng       1400: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1401: 				return false;
                   1402: 			    }
                   1403: 			}
                   1404: 		    }
                   1405: 		}
                   1406: 	    }
                   1407: 	}
1.120     ng       1408: 	formname.submit();
                   1409:     }
                   1410: 
1.71      ng       1411: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1412:     function checkSubmitPage(formname,total) {
                   1413: 	noscore = new Array(100);
                   1414: 	var ptr = 0;
                   1415: 	for (i=1;i<total;i++) {
1.125     ng       1416: 	    var partid = formname["q_"+i].value;
1.127     ng       1417: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1418: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1419: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1420: 		if (points == "" && status != "correct_by_student") {
                   1421: 		    noscore[ptr] = i;
                   1422: 		    ptr++;
                   1423: 		}
                   1424: 	    }
                   1425: 	}
                   1426: 	if (ptr != 0) {
                   1427: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1428: 	    var prolist = "";
                   1429: 	    if (ptr == 1) {
                   1430: 		prolist = noscore[0];
                   1431: 	    } else {
                   1432: 		var i = 0;
                   1433: 		while (i < ptr-1) {
                   1434: 		    prolist += noscore[i]+", ";
                   1435: 		    i++;
                   1436: 		}
                   1437: 		prolist += "and "+noscore[i];
                   1438: 	    }
                   1439: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1440: 	    if (resp == false) {
                   1441: 		return false;
                   1442: 	    }
                   1443: 	}
1.45      ng       1444: 
1.71      ng       1445: 	formname.submit();
                   1446:     }
                   1447: SUBJAVASCRIPT
                   1448: }
1.45      ng       1449: 
1.71      ng       1450: #--- javascript for essay type problem --
                   1451: sub sub_page_kw_js {
                   1452:     my $request = shift;
1.80      ng       1453:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1454:     &commonJSfunctions($request);
1.350     albertel 1455: 
1.629     www      1456:     my $inner_js_msg_central= (<<INNERJS);
                   1457: <script type="text/javascript">
1.350     albertel 1458:     function checkInput() {
                   1459:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1460:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1461:       var usrctr = document.msgcenter.usrctr.value;
                   1462:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1463:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1464: 
                   1465:       var msgchk = "";
                   1466:       if (document.msgcenter.subchk.checked) {
                   1467:          msgchk = "msgsub,";
                   1468:       }
                   1469:       var includemsg = 0;
                   1470:       for (var i=1; i<=nmsg; i++) {
                   1471:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1472:           var frmmsg = document.msgcenter["msg"+i];
                   1473:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1474:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1475:           showflg.value = "1";
                   1476:           var chkbox = document.msgcenter["msgn"+i];
                   1477:           if (chkbox.checked) {
                   1478:              msgchk += "savemsg"+i+",";
                   1479:              includemsg = 1;
                   1480:           }
                   1481:       }
                   1482:       if (document.msgcenter.newmsgchk.checked) {
                   1483:          msgchk += "newmsg"+usrctr;
                   1484:          includemsg = 1;
                   1485:       }
                   1486:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1487:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1488:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1489:       includemsg.value = msgchk;
                   1490: 
                   1491:       self.close()
                   1492: 
                   1493:     }
1.629     www      1494: </script>
1.350     albertel 1495: INNERJS
                   1496: 
1.629     www      1497:     my $inner_js_highlight_central= (<<INNERJS);
                   1498: <script type="text/javascript">
1.351     albertel 1499:     function updateChoice(flag) {
                   1500:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1501:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1502:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1503:       opener.document.SCORE.refresh.value = "on";
                   1504:       if (opener.document.SCORE.keywords.value!=""){
                   1505:          opener.document.SCORE.submit();
                   1506:       }
                   1507:       self.close()
                   1508:     }
1.629     www      1509: </script>
1.351     albertel 1510: INNERJS
                   1511: 
                   1512:     my $start_page_msg_central = 
                   1513:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1514: 				       {'js_ready'  => 1,
                   1515: 					'only_body' => 1,
                   1516: 					'bgcolor'   =>'#FFFFFF',});
                   1517:     my $end_page_msg_central = 
                   1518: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1519: 
                   1520: 
                   1521:     my $start_page_highlight_central = 
                   1522:         &Apache::loncommon::start_page('Highlight Central',
                   1523: 				       $inner_js_highlight_central,
1.350     albertel 1524: 				       {'js_ready'  => 1,
                   1525: 					'only_body' => 1,
                   1526: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1527:     my $end_page_highlight_central = 
1.350     albertel 1528: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1529: 
1.219     www      1530:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1531:     $docopen=~s/^document\.//;
1.736     damieng  1532:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1533:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1534:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1535:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1536:                 col1 => 'red',
                   1537:                 col2 => 'green',
                   1538:                 col3 => 'blue',
                   1539:                 siz1 => 'normal',
                   1540:                 siz2 => '+1',
                   1541:                 siz3 => '+2',
                   1542:                 sty1 => 'normal',
                   1543:                 sty2 => 'italic',
                   1544:                 sty3 => 'bold',
                   1545:              );
                   1546:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1547:                 comp => 'Compose Message for: ',
                   1548:                 incl => 'Include',
1.656     raeburn  1549:                 type => 'Type',
1.652     raeburn  1550:                 subj => 'Subject',
                   1551:                 mesa => 'Message',
                   1552:                 new  => 'New',
                   1553:                 save => 'Save',
                   1554:                 canc => 'Cancel',
                   1555:                 kehi => 'Keyword Highlight Options',
                   1556:                 txtc => 'Text Color',
                   1557:                 font => 'Font Size',
1.656     raeburn  1558:                 fnst => 'Font Style',
1.652     raeburn  1559:              );
1.736     damieng  1560:     &js_escape(\%js_lt);
                   1561:     &html_escape(\%html_js_lt);
                   1562:     &js_escape(\%html_js_lt);
1.597     wenzelju 1563:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1564: 
1.44      ng       1565: //===================== Show list of keywords ====================
1.122     ng       1566:   function keywords(formname) {
1.736     damieng  1567:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1568:     if (nret==null) return;
1.122     ng       1569:     formname.keywords.value = nret;
1.44      ng       1570: 
1.122     ng       1571:     if (formname.keywords.value != "") {
1.128     ng       1572: 	formname.refresh.value = "on";
1.122     ng       1573: 	formname.submit();
1.44      ng       1574:     }
                   1575:     return;
                   1576:   }
                   1577: 
                   1578: //===================== Script to view submitted by ==================
                   1579:   function viewSubmitter(submitter) {
                   1580:     document.SCORE.refresh.value = "on";
                   1581:     document.SCORE.NCT.value = "1";
                   1582:     document.SCORE.unamedom0.value = submitter;
                   1583:     document.SCORE.submit();
                   1584:     return;
                   1585:   }
                   1586: 
                   1587: //===================== Script to add keyword(s) ==================
                   1588:   function getSel() {
                   1589:     if (document.getSelection) txt = document.getSelection();
                   1590:     else if (document.selection) txt = document.selection.createRange().text;
                   1591:     else return;
1.772   ! raeburn  1592:     if (typeof(txt) != 'string') {
        !          1593:         txt = String(txt);
        !          1594:     }
1.44      ng       1595:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1596:     if (cleantxt=="") {
1.736     damieng  1597: 	alert("$js_lt{'plse'}");
1.44      ng       1598: 	return;
                   1599:     }
1.736     damieng  1600:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1601:     if (nret==null) return;
1.127     ng       1602:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1603:     if (document.SCORE.keywords.value != "") {
1.127     ng       1604: 	document.SCORE.refresh.value = "on";
1.44      ng       1605: 	document.SCORE.submit();
                   1606:     }
                   1607:     return;
                   1608:   }
                   1609: 
                   1610: //====================== Script for composing message ==============
1.80      ng       1611:    // preload images
                   1612:    img1 = new Image();
                   1613:    img1.src = "$iconpath/mailbkgrd.gif";
                   1614:    img2 = new Image();
                   1615:    img2.src = "$iconpath/mailto.gif";
                   1616: 
1.44      ng       1617:   function msgCenter(msgform,usrctr,fullname) {
                   1618:     var Nmsg  = msgform.savemsgN.value;
                   1619:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1620:     var subject = msgform.msgsub.value;
1.127     ng       1621:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1622:     re = /msgsub/;
                   1623:     var shwsel = "";
                   1624:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1625:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1626:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1627:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1628: 	var testmsg = "savemsg"+i+",";
                   1629: 	re = new RegExp(testmsg,"g");
1.44      ng       1630: 	shwsel = "";
                   1631: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1632: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1633: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1634: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1635: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1636:     }
1.125     ng       1637:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1638:     shwsel = "";
                   1639:     re = /newmsg/;
                   1640:     if (re.test(msgchk)) { shwsel = "checked" }
                   1641:     newMsg(newmsg,shwsel);
                   1642:     msgTail(); 
                   1643:     return;
                   1644:   }
                   1645: 
1.123     ng       1646:   function checkEntities(strx) {
                   1647:     if (strx.length == 0) return strx;
                   1648:     var orgStr = ["&", "<", ">", '"']; 
                   1649:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1650:     var counter = 0;
                   1651:     while (counter < 4) {
                   1652: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1653: 	counter++;
                   1654:     }
                   1655:     return strx;
                   1656:   }
                   1657: 
                   1658:   function strReplace(strx, orgStr, newStr) {
                   1659:     return strx.split(orgStr).join(newStr);
                   1660:   }
                   1661: 
1.44      ng       1662:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1663:     var height = 70*Nmsg+250;
1.44      ng       1664:     if (height > 600) {
                   1665: 	height = 600;
                   1666:     }
1.118     ng       1667:     var xpos = (screen.width-600)/2;
                   1668:     xpos = (xpos < 0) ? '0' : xpos;
                   1669:     var ypos = (screen.height-height)/2-30;
                   1670:     ypos = (ypos < 0) ? '0' : ypos;
                   1671: 
1.668     www      1672:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1673:     pWin.focus();
                   1674:     pDoc = pWin.document;
1.219     www      1675:     pDoc.$docopen;
1.351     albertel 1676:     pDoc.write('$start_page_msg_central');
1.76      ng       1677: 
                   1678:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1679:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1680:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1681: 
1.676     golterma 1682:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1683:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1684: }
                   1685:     function displaySubject(msg,shwsel) {
1.76      ng       1686:     pDoc = pWin.document;
1.676     golterma 1687:     pDoc.write("<tr>");
                   1688:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1689:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1690:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1691: }
                   1692: 
1.72      ng       1693:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1694:     pDoc = pWin.document;
1.676     golterma 1695:     pDoc.write("<tr>");
                   1696:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1697:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1698:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1699: }
                   1700: 
                   1701:   function newMsg(newmsg,shwsel) {
1.76      ng       1702:     pDoc = pWin.document;
1.676     golterma 1703:     pDoc.write("<tr>");
                   1704:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1705:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1706:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1707: }
                   1708: 
                   1709:   function msgTail() {
1.76      ng       1710:     pDoc = pWin.document;
1.676     golterma 1711:     //pDoc.write("<\\/table>");
1.465     albertel 1712:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1713:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1714:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1715:     pDoc.write("<\\/form>");
1.351     albertel 1716:     pDoc.write('$end_page_msg_central');
1.128     ng       1717:     pDoc.close();
1.44      ng       1718: }
                   1719: 
                   1720: //====================== Script for keyword highlight options ==============
                   1721:   function kwhighlight() {
                   1722:     var kwclr    = document.SCORE.kwclr.value;
                   1723:     var kwsize   = document.SCORE.kwsize.value;
                   1724:     var kwstyle  = document.SCORE.kwstyle.value;
                   1725:     var redsel = "";
                   1726:     var grnsel = "";
                   1727:     var blusel = "";
1.736     damieng  1728:     var txtcol1 = "$js_lt{'col1'}";
                   1729:     var txtcol2 = "$js_lt{'col2'}";
                   1730:     var txtcol3 = "$js_lt{'col3'}";
                   1731:     var txtsiz1 = "$js_lt{'siz1'}";
                   1732:     var txtsiz2 = "$js_lt{'siz2'}";
                   1733:     var txtsiz3 = "$js_lt{'siz3'}";
                   1734:     var txtsty1 = "$js_lt{'sty1'}";
                   1735:     var txtsty2 = "$js_lt{'sty2'}";
                   1736:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1737:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1738:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1739:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1740:     var sznsel = "";
                   1741:     var sz1sel = "";
                   1742:     var sz2sel = "";
1.718     bisitz   1743:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1744:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1745:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1746:     var synsel = "";
                   1747:     var syisel = "";
                   1748:     var sybsel = "";
1.718     bisitz   1749:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1750:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1751:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1752:     highlightCentral();
1.718     bisitz   1753:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1754:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1755:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1756:     highlightend();
                   1757:     return;
                   1758:   }
                   1759: 
                   1760:   function highlightCentral() {
1.76      ng       1761: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1762:     var xpos = (screen.width-400)/2;
                   1763:     xpos = (xpos < 0) ? '0' : xpos;
                   1764:     var ypos = (screen.height-330)/2-30;
                   1765:     ypos = (ypos < 0) ? '0' : ypos;
                   1766: 
1.206     albertel 1767:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1768:     hwdWin.focus();
                   1769:     var hDoc = hwdWin.document;
1.219     www      1770:     hDoc.$docopen;
1.351     albertel 1771:     hDoc.write('$start_page_highlight_central');
1.76      ng       1772:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1773:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1774: 
1.718     bisitz   1775:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1776:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1777:   }
                   1778: 
                   1779:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1780:     var hDoc = hwdWin.document;
1.718     bisitz   1781:     hDoc.write("<tr>");
1.76      ng       1782:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1783:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1784:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1785:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1786:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1787:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1788:     hDoc.write("<\\/tr>");
1.44      ng       1789:   }
                   1790: 
                   1791:   function highlightend() { 
1.76      ng       1792:     var hDoc = hwdWin.document;
1.718     bisitz   1793:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1794:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1795:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1796:     hDoc.write("<\\/form>");
1.351     albertel 1797:     hDoc.write('$end_page_highlight_central');
1.128     ng       1798:     hDoc.close();
1.44      ng       1799:   }
                   1800: 
                   1801: SUBJAVASCRIPT
                   1802: }
                   1803: 
1.349     albertel 1804: sub get_increment {
1.348     bowersj2 1805:     my $increment = $env{'form.increment'};
                   1806:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1807:         $increment != .1) {
                   1808:         $increment = 1;
                   1809:     }
                   1810:     return $increment;
                   1811: }
                   1812: 
1.585     bisitz   1813: sub gradeBox_start {
                   1814:     return (
                   1815:         &Apache::loncommon::start_data_table()
                   1816:        .&Apache::loncommon::start_data_table_header_row()
                   1817:        .'<th>'.&mt('Part').'</th>'
                   1818:        .'<th>'.&mt('Points').'</th>'
                   1819:        .'<th>&nbsp;</th>'
                   1820:        .'<th>'.&mt('Assign Grade').'</th>'
                   1821:        .'<th>'.&mt('Weight').'</th>'
                   1822:        .'<th>'.&mt('Grade Status').'</th>'
                   1823:        .&Apache::loncommon::end_data_table_header_row()
                   1824:     );
                   1825: }
                   1826: 
                   1827: sub gradeBox_end {
                   1828:     return (
                   1829:         &Apache::loncommon::end_data_table()
                   1830:     );
                   1831: }
1.71      ng       1832: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1833: sub gradeBox {
1.322     albertel 1834:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1835:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1836: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1837:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1838:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1839:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1840:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1841:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1842: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1843:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1844:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1845:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1846: 				       [$partid]);
                   1847:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1848:     if ($last_resets{$partid}) {
                   1849:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1850:     }
1.695     bisitz   1851:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1852:     my $ctr = 0;
1.348     bowersj2 1853:     my $thisweight = 0;
1.349     albertel 1854:     my $increment = &get_increment();
1.485     albertel 1855: 
                   1856:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1857:     while ($thisweight<=$wgt) {
1.532     bisitz   1858: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1859:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1860: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1861: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1862: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1863:         $thisweight += $increment;
1.71      ng       1864: 	$ctr++;
                   1865:     }
1.485     albertel 1866:     $radio.='</tr></table>';
                   1867: 
                   1868:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1869: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1870: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1871: 	$wgt.')" /></td>'."\n";
1.485     albertel 1872:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1873: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1874: 	' </td>'."\n";
                   1875:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1876: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1877:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1878: 	$line.='<option></option>'.
                   1879: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1880:     } else {
1.485     albertel 1881: 	$line.='<option selected="selected"></option>'.
                   1882: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1883:     }
1.485     albertel 1884:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1885: 
                   1886: 
                   1887:     $result .= 
1.695     bisitz   1888: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1889:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1890:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1891:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1892: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1893: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1894: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1895:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1896:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1897:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1898:         $aggtries.'" />'."\n";
1.582     raeburn  1899:     my $res_error;
                   1900:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1901:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1902:     if ($res_error) {
                   1903:         return &navmap_errormsg();
                   1904:     }
1.318     banghart 1905:     return $result;
                   1906: }
1.322     albertel 1907: 
                   1908: sub handback_box {
1.623     www      1909:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1910:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1911:     my (@respids);
1.652     raeburn  1912:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1913:     foreach my $part_response_id (@part_response_id) {
                   1914:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1915:         if ($part eq $partid) {
1.375     albertel 1916:             push(@respids,$resp);
1.323     banghart 1917:         }
                   1918:     }
1.318     banghart 1919:     my $result;
1.323     banghart 1920:     foreach my $respid (@respids) {
1.322     albertel 1921: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1922: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1923: 	next if (!@$files);
1.654     raeburn  1924: 	my $file_counter = 0;
1.313     banghart 1925: 	foreach my $file (@$files) {
1.368     banghart 1926: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1927:                 $file_counter++;
1.368     banghart 1928:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1929:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1930:     	        $file_disp = "$name.$ext";
                   1931:     	        $file = $file_path.$file_disp;
                   1932:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1933:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1934:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1935:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1936: 	    }
1.322     albertel 1937: 	}
1.654     raeburn  1938:         if ($file_counter) {
                   1939:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1940:                        '<span class="LC_info">'.
                   1941:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1942:         }
1.313     banghart 1943:     }
1.318     banghart 1944:     return $result;    
1.71      ng       1945: }
1.44      ng       1946: 
1.58      albertel 1947: sub show_problem {
1.382     albertel 1948:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1949:     my $rendered;
1.382     albertel 1950:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1951:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1952:     if ($mode eq 'both' or $mode eq 'text') {
                   1953: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1954: 						       $env{'request.course.id'},
                   1955: 						       undef,\%form);
1.144     albertel 1956:     }
1.58      albertel 1957:     if ($removeform) {
                   1958: 	$rendered=~s|<form(.*?)>||g;
                   1959: 	$rendered=~s|</form>||g;
1.374     albertel 1960: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1961:     }
1.144     albertel 1962:     my $companswer;
                   1963:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1964: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1965: 	$companswer=
                   1966: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1967: 						    $env{'request.course.id'},
                   1968: 						    %form);
1.144     albertel 1969:     }
1.58      albertel 1970:     if ($removeform) {
                   1971: 	$companswer=~s|<form(.*?)>||g;
                   1972: 	$companswer=~s|</form>||g;
1.144     albertel 1973: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1974:     }
1.671     raeburn  1975:     my $renderheading = &mt('View of the problem');
                   1976:     my $answerheading = &mt('Correct answer');
                   1977:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1978:         my $stu_fullname = $env{'form.fullname'};
                   1979:         if ($stu_fullname eq '') {
                   1980:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1981:         }
                   1982:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1983:         if ($forwhom ne '') {
                   1984:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1985:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1986:         }
                   1987:     }
1.468     albertel 1988:     $rendered=
1.588     bisitz   1989:         '<div class="LC_Box">'
1.671     raeburn  1990:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1991:        .$rendered
                   1992:        .'</div>';
1.468     albertel 1993:     $companswer=
1.588     bisitz   1994:         '<div class="LC_Box">'
1.671     raeburn  1995:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1996:        .$companswer
                   1997:        .'</div>';
1.468     albertel 1998:     my $result;
1.144     albertel 1999:     if ($mode eq 'both') {
1.588     bisitz   2000:         $result=$rendered.$companswer;
1.144     albertel 2001:     } elsif ($mode eq 'text') {
1.588     bisitz   2002:         $result=$rendered;
1.144     albertel 2003:     } elsif ($mode eq 'answer') {
1.588     bisitz   2004:         $result=$companswer;
1.144     albertel 2005:     }
1.71      ng       2006:     return $result;
1.58      albertel 2007: }
1.397     albertel 2008: 
1.396     banghart 2009: sub files_exist {
                   2010:     my ($r, $symb) = @_;
                   2011:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2012:     foreach my $student (@students) {
                   2013:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2014:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2015: 					      $udom,$uname);
1.396     banghart 2016:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2017:         foreach my $submission (@$string) {
                   2018:             my ($partid,$respid) =
                   2019: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2020:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2021: 					   \%record);
                   2022:             return 1 if (@$files);
1.396     banghart 2023:         }
                   2024:     }
1.397     albertel 2025:     return 0;
1.396     banghart 2026: }
1.397     albertel 2027: 
1.394     banghart 2028: sub download_all_link {
                   2029:     my ($r,$symb) = @_;
1.621     www      2030:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2031:         $r->print(&mt('There are currently no submitted documents.'));
                   2032:         return;
1.621     www      2033:     }
1.395     albertel 2034:     my $all_students = 
                   2035: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2036: 
                   2037:     my $parts =
                   2038: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2039: 
1.394     banghart 2040:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2041:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2042:                              'cgi.'.$identifier.'.symb' => $symb,
                   2043:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2044:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2045: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2046:     return;
                   2047: }
                   2048: 
                   2049: sub submit_download_link {
                   2050:     my ($request,$symb) = @_;
                   2051:     if (!$symb) { return ''; }
                   2052: #FIXME: Figure out which type of problem this is and provide appropriate download
1.750     raeburn  2053:     my $res_error;
                   2054:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                   2055:     if (ref($res_error)) {
                   2056:         if ($$res_error) {
                   2057:             $request->print(&mt('An error occurred retrieving response types'));
                   2058:             return;
                   2059:         }
                   2060:     }
                   2061:     my ($numupload,$numessay) = (0,0);
                   2062:     if (ref($responseType) eq 'HASH') {
                   2063:         foreach my $part (sort(keys(%$responseType))) {
                   2064:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
                   2065:                 my $responsetype = $responseType->{$part}->{$id};
                   2066:                 if ($responsetype eq 'essay') {
                   2067:                     my $uploadedfiletypes =
                   2068:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
                   2069:                     if ($uploadedfiletypes) {
                   2070:                         $numupload++;
                   2071:                     } else {
                   2072:                         $numessay++;
                   2073:                     }
                   2074:                 }
                   2075:             }
                   2076:         }
                   2077:     }
                   2078:     if (($numupload) || ($numessay)) {
                   2079:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2080:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2081:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2082:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2083:         if (ref($fullname) eq 'HASH') {
                   2084:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2085:             if (@students) {
                   2086:                 @{$env{'form.stuinfo'}} = @students;
                   2087:                 if ($numupload) {
                   2088:                     &download_all_link($request,$symb);
                   2089:                 }
                   2090: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
                   2091: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2092:             } else {
                   2093:                 $request->print(&mt('No students match the criteria you selected'));
                   2094:             }
                   2095:         } else {
                   2096:             $request->print(&mt('Could not retrieve student information'));
                   2097:         }
                   2098:     } else {
                   2099:         $request->print(&mt('No essayresponse items found'));
                   2100:     }
                   2101:     return;
1.394     banghart 2102: }
1.395     albertel 2103: 
1.432     banghart 2104: sub build_section_inputs {
                   2105:     my $section_inputs;
                   2106:     if ($env{'form.section'} eq '') {
                   2107:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2108:     } else {
                   2109:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2110:         foreach my $section (@sections) {
1.432     banghart 2111:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2112:         }
                   2113:     }
                   2114:     return $section_inputs;
                   2115: }
                   2116: 
1.44      ng       2117: # --------------------------- show submissions of a student, option to grade 
                   2118: sub submission {
1.608     www      2119:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2120:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2121:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2122:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2123:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2124: 
1.605     www      2125:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2126:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2127:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2128:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2129: 
                   2130:     if (!&canview($usec)) {
1.712     bisitz   2131:         $request->print(
                   2132:             '<span class="LC_warning">'.
1.713     bisitz   2133:             &mt('Unable to view requested student.').
1.712     bisitz   2134:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2135:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2136:             '</span>');
1.104     albertel 2137: 	return;
                   2138:     }
                   2139: 
1.257     albertel 2140:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2141:     unless ($is_tool) { 
                   2142:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2143:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2144:     }
1.257     albertel 2145:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2146:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2147: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2148: 	'/check.gif" height="16" border="0" />';
1.41      ng       2149: 
                   2150:     # header info
                   2151:     if ($counter == 0) {
                   2152: 	&sub_page_js($request);
1.621     www      2153: 	&sub_page_kw_js($request);
1.118     ng       2154: 
1.44      ng       2155: 	# option to display problem, only once else it cause problems 
                   2156:         # with the form later since the problem has a form.
1.257     albertel 2157: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2158: 	    my $mode;
1.257     albertel 2159: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2160: 		$mode='both';
1.257     albertel 2161: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2162: 		$mode='text';
1.257     albertel 2163: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2164: 		$mode='answer';
                   2165: 	    }
1.329     albertel 2166: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2167: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2168: 	}
1.441     www      2169: 
1.704     raeburn  2170: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2171:         # if this subroutine has been called once.
1.41      ng       2172: 	my %keyhash = ();
1.624     www      2173: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2174:         if (1) {
1.41      ng       2175: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2176: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2177: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2178: 
1.257     albertel 2179: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2180: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2181: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2182: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2183: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2184: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2185: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2186: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2187: 	}
1.257     albertel 2188: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2189: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2190: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2191: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2192: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2193: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2194: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2195: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2196: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2197: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2198: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2199: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2200: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2201: 			&build_section_inputs().
1.326     albertel 2202: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2203: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2204: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2205: #	if ($env{'form.handgrade'} eq 'yes') {
                   2206:         if (1) {
1.257     albertel 2207: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2208: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2209: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2210: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2211: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2212: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2213: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2214: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2215: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2216: 	    }
1.123     ng       2217: 	}
1.41      ng       2218: 	
                   2219: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2220: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2221: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2222: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2223: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2224: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2225: 		'" />'."\n".
                   2226: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2227: 	    $cts++;
                   2228: 	}
                   2229: 	$request->print($prnmsg);
1.32      ng       2230: 
1.624     www      2231: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2232:         unless ($is_tool) {
1.652     raeburn  2233: 
                   2234:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2235:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2236:                           keyw => 'Keyword Options',
1.655     raeburn  2237:                           list => 'List',
1.652     raeburn  2238:                           past => 'Paste Selection to List',
1.661     www      2239:                           high => 'Highlight Attribute',
1.652     raeburn  2240:                      );    
1.88      www      2241: #
                   2242: # Print out the keyword options line
                   2243: #
1.718     bisitz   2244: 	    $request->print(
                   2245:                 '<div class="LC_columnSection">'
                   2246:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2247:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2248:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2249:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2250:  class="page">'.$lt{'past'}.'</a>',
                   2251:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2252:                     {legend => $lt{'keyw'}})
                   2253:                .'</fieldset></div>'
                   2254:             );
                   2255: 
1.88      www      2256: #
                   2257: # Load the other essays for similarity check
                   2258: #
1.753     raeburn  2259:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2260:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2261:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2262:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2263:                 if ($cdom ne '' && $cnum ne '') {
                   2264:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2265:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2266:                         my $apath = $1.'_'.$id;
                   2267:                         $apath=~s/\W/\_/gs;
                   2268:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2269:                     }
                   2270:                 }
                   2271:             } else {
                   2272: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2273: 	        $apath=&escape($apath);
                   2274: 	        $apath=~s/\W/\_/gs;
                   2275:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2276:             }
1.41      ng       2277:         }
                   2278:     }
1.44      ng       2279: 
1.441     www      2280: # This is where output for one specific student would start
1.592     bisitz   2281:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2282:     $request->print(
                   2283:         "\n\n"
                   2284:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2285:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2286:        ."\n"
                   2287:     );
1.441     www      2288: 
1.592     bisitz   2289:     # Show additional functions if allowed
                   2290:     if ($perm{'vgr'}) {
                   2291:         $request->print(
                   2292:             &Apache::loncommon::track_student_link(
1.708     bisitz   2293:                 'View recent activity',
1.592     bisitz   2294:                 $uname,$udom,'check')
                   2295:            .' '
                   2296:         );
                   2297:     }
                   2298:     if ($perm{'opa'}) {
                   2299:         $request->print(
                   2300:             &Apache::loncommon::pprmlink(
                   2301:                 &mt('Set/Change parameters'),
                   2302:                 $uname,$udom,$symb,'check'));
                   2303:     }
                   2304: 
                   2305:     # Show Problem
1.257     albertel 2306:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2307: 	my $mode;
1.257     albertel 2308: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2309: 	    $mode='both';
1.257     albertel 2310: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2311: 	    $mode='text';
1.257     albertel 2312: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2313: 	    $mode='answer';
                   2314: 	}
1.329     albertel 2315: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2316: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2317:     }
1.144     albertel 2318: 
1.257     albertel 2319:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2320:     my $res_error;
                   2321:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2322:     if ($res_error) {
                   2323:         $request->print(&navmap_errormsg());
                   2324:         return;
                   2325:     }
1.41      ng       2326: 
1.44      ng       2327:     # Display student info
1.41      ng       2328:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2329: 
1.745     raeburn  2330:     my $boxtitle = &mt('Submissions');
                   2331:     if ($is_tool) {
                   2332:         $boxtitle = &mt('Transactions')
                   2333:     }
1.590     bisitz   2334:     my $result='<div class="LC_Box">'
1.745     raeburn  2335:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2336:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2337:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2338: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2339:     unless ($is_tool) {
1.588     bisitz   2340:         $result.='<p class="LC_info">'
                   2341:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2342:                 ."</p>\n";
1.469     albertel 2343:     }
                   2344: 
1.118     ng       2345:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2346:     my $fullname;
                   2347:     my $col_fullnames = [];
1.624     www      2348: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2349:     unless ($is_tool) {
1.464     albertel 2350: 	(my $sub_result,$fullname,$col_fullnames)=
                   2351: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2352: 				 $counter);
                   2353: 	$result.=$sub_result;
1.41      ng       2354:     }
1.44      ng       2355:     $request->print($result."\n");
1.702     kruse    2356:     
1.44      ng       2357:     # print student answer/submission
1.588     bisitz   2358:     # Options are (1) Handgraded submission only
1.44      ng       2359:     #             (2) Last submission, includes submission that is not handgraded 
                   2360:     #                  (for multi-response type part)
                   2361:     #             (3) Last submission plus the parts info
                   2362:     #             (4) The whole record for this student
1.702     kruse    2363:     
1.745     raeburn  2364:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2365: 	
1.702     kruse    2366:     my $lastsubonly;
1.468     albertel 2367: 
1.702     kruse    2368:     if ($$timestamp eq '') {
                   2369:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2370:     } elsif ($is_tool) {
                   2371:         $lastsubonly =
                   2372:             '<div class="LC_grade_submissions_body">'
                   2373:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2374:     } else {
                   2375:         $lastsubonly =
                   2376:             '<div class="LC_grade_submissions_body">'
                   2377:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2378: 
                   2379: 	my %seenparts;
                   2380: 	my @part_response_id = &flatten_responseType($responseType);
                   2381: 	foreach my $part (@part_response_id) {
                   2382: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2383: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2384: 
1.702     kruse    2385: 	    my ($partid,$respid) = @{ $part };
                   2386: 	    my $display_part=&get_display_part($partid,$symb);
                   2387: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2388: 		if (exists($seenparts{$partid})) { next; }
                   2389: 		$seenparts{$partid}=1;
                   2390:                 $request->print(
                   2391:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2392:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2393:                                '<a href="javascript:viewSubmitter(\''.
                   2394:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2395:                                '\');" target="_self">'.
                   2396:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2397:                     '<br />');
                   2398: 		next;
                   2399: 		}
                   2400: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2401: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2402:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2403:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2404:                     ' <span class="LC_internal_info">'.
                   2405:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2406:                     '</span>&nbsp; &nbsp;'.
                   2407: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2408: 		next;
                   2409: 	    }
                   2410: 	    foreach my $submission (@$string) {
                   2411: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2412: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2413: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2414: 		# Similarity check
                   2415:                 my $similar='';
                   2416:                 my ($type,$trial,$rndseed);
                   2417:                 if ($hide eq 'rand') {
                   2418:                     $type = 'randomizetry';
                   2419:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2420:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2421:                 }
                   2422: 	        if ($env{'form.checkPlag'}) {
                   2423:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2424: 		        &most_similar($uname,$udom,$symb,$subval);
                   2425: 		    if ($osim) {
                   2426: 			$osim=int($osim*100.0);
                   2427:                         if ($hide eq 'anon') {
                   2428:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2429:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2430:                         } else {
1.753     raeburn  2431: 			    $similar='<hr />';
                   2432:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2433:                                 $similar .= '<h3><span class="LC_warning">'.
                   2434:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2435:                                                 $osim,
                   2436:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2437:                                             '</span></h3>';
                   2438:                             } else {
                   2439:                                 my %old_course_desc;
                   2440:                                 if ($ocrsid ne '') {
                   2441:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2442:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2443:                                     } else {
                   2444:                                         my $args;
                   2445:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2446:                                             $args = {'one_time' => 1};
                   2447:                                         }
                   2448:                                         %old_course_desc =
                   2449:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2450:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2451:                                     }
                   2452:                                     $similar .=
                   2453:                                         '<h3><span class="LC_warning">'.
                   2454:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2455:                                             $osim,
                   2456:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2457:                                             $old_course_desc{'description'},
                   2458:                                             $old_course_desc{'num'},
                   2459:                                             $old_course_desc{'domain'}).
                   2460:                                         '</span></h3>';
                   2461:                                 } else {
                   2462:                                     $similar .=
                   2463:                                         '<h3><span class="LC_warning">'.
                   2464:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2465:                                             $osim,
                   2466:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2467:                                         '</span></h3>';
                   2468:                                 }
                   2469:                             }
                   2470:                             $similar .= '<blockquote><i>'.
                   2471:                                         &keywords_highlight($oessay).
                   2472:                                         '</i></blockquote><hr />';
1.702     kruse    2473:                         }
                   2474: 	            }
                   2475: 		}
                   2476: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2477:                                      undef,$type,$trial,$rndseed);
                   2478:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2479: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2480: 		    my $display_part=&get_display_part($partid,$symb);
                   2481:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2482:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2483:                         ' <span class="LC_internal_info">'.
                   2484:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2485:                         '</span>&nbsp; &nbsp;';
                   2486: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2487:                         
                   2488: 		    if (@$files) {
                   2489:                         if ($hide eq 'anon') {
                   2490:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2491:                         } else {
                   2492:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2493:                                         .'<br /><span class="LC_warning">';
                   2494:                             if(@$files == 1) {
                   2495:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2496:                             } else {
1.702     kruse    2497:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2498:                             }
                   2499:                             $lastsubonly .= '</span>';                         
                   2500:                             foreach my $file (@$files) {
                   2501:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2502:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2503:                             }
                   2504:                         }
1.702     kruse    2505: 			$lastsubonly.='<br />';
                   2506:                     }
                   2507:                     if ($hide eq 'anon') {
                   2508:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2509:                     } else {
1.724     raeburn  2510:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2511:                         if ($draft) {
                   2512:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2513:                         }
                   2514:                         $subval =
1.702     kruse    2515: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2516: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2517:                         if ($responsetype eq 'essay') {
                   2518:                             $subval =~ s{\n}{<br />}g;
                   2519:                         }
                   2520:                         $lastsubonly.=$subval."\n";
1.702     kruse    2521:                     }
                   2522: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2523: 		    $lastsubonly.='</div>';
1.41      ng       2524: 		}
1.702     kruse    2525:             }
1.151     albertel 2526: 	}
1.702     kruse    2527: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2528:     }
                   2529:     $request->print($lastsubonly);
                   2530:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2531:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2532: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2533:   
1.702     kruse    2534:     } 
                   2535:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2536:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2537:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2538: 								 $env{'request.course.id'},
1.44      ng       2539: 								 $last,'.submission',
1.726     raeburn  2540: 								 'Apache::grades::keywords_highlight',
                   2541:                                                                  $usec,$identifier));
1.41      ng       2542:     }
1.121     ng       2543:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2544: 	.$udom.'" />'."\n");
1.44      ng       2545:     # return if view submission with no grading option
1.618     www      2546:     if (!&canmodify($usec)) {
1.633     www      2547: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2548: 	return;
1.180     albertel 2549:     } else {
1.468     albertel 2550: 	$request->print('</div>'."\n");
1.41      ng       2551:     }
1.33      ng       2552: 
1.121     ng       2553:     # essay grading message center
1.624     www      2554: #    if ($env{'form.handgrade'} eq 'yes') {
                   2555:     if (1) {
1.468     albertel 2556: 	my $result='<div class="LC_grade_message_center">';
                   2557:     
                   2558: 	$result.='<div class="LC_grade_message_center_header">'.
                   2559: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2560: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2561: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2562: 	if (scalar(@$col_fullnames) > 0) {
                   2563: 	    my $lastone = pop(@$col_fullnames);
                   2564: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2565: 	}
                   2566: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2567: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2568: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2569: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2570: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2571: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2572: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2573: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2574: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2575: 	    '<br />&nbsp;('.
1.468     albertel 2576: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2577: 	$result.='</div></div>';
1.121     ng       2578: 	$request->print($result);
1.118     ng       2579:     }
1.41      ng       2580: 
                   2581:     my %seen = ();
                   2582:     my @partlist;
1.129     ng       2583:     my @gradePartRespid;
1.745     raeburn  2584:     my @part_response_id;
                   2585:     if ($is_tool) {
                   2586:         @part_response_id = ([0,'']);
                   2587:     } else {
                   2588:         @part_response_id = &flatten_responseType($responseType);
                   2589:     }
1.585     bisitz   2590:     $request->print(
1.588     bisitz   2591:         '<div class="LC_Box">'
                   2592:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2593:     );
1.592     bisitz   2594:     $request->print(&gradeBox_start());
1.375     albertel 2595:     foreach my $part_response_id (@part_response_id) {
                   2596:     	my ($partid,$respid) = @{ $part_response_id };
                   2597: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2598: 	next if ($seen{$partid} > 0);
1.41      ng       2599: 	$seen{$partid}++;
1.393     albertel 2600: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2601: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2602: 	push(@partlist,$partid);
                   2603: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2604: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2605:     }
1.585     bisitz   2606:     $request->print(&gradeBox_end()); # </div>
                   2607:     $request->print('</div>');
1.468     albertel 2608: 
                   2609:     $request->print('<div class="LC_grade_info_links">');
                   2610:     $request->print('</div>');
                   2611: 
1.45      ng       2612:     $result='<input type="hidden" name="partlist'.$counter.
                   2613: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2614:     $result.='<input type="hidden" name="gradePartRespid'.
                   2615: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2616:     my $ctr = 0;
                   2617:     while ($ctr < scalar(@partlist)) {
                   2618: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2619: 	    $partlist[$ctr].'" />'."\n";
                   2620: 	$ctr++;
                   2621:     }
1.468     albertel 2622:     $request->print($result.''."\n");
1.41      ng       2623: 
1.441     www      2624: # Done with printing info for one student
                   2625: 
1.468     albertel 2626:     $request->print('</div>');#LC_grade_show_user
1.441     www      2627: 
                   2628: 
1.41      ng       2629:     # print end of form
                   2630:     if ($counter == $total) {
1.592     bisitz   2631:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2632: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2633: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2634: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2635: 	my $ntstu ='<select name="NTSTU">'.
                   2636: 	    '<option>1</option><option>2</option>'.
                   2637: 	    '<option>3</option><option>5</option>'.
                   2638: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2639: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2640: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2641:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2642: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2643: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2644: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2645: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2646:         $endform.='<span class="LC_warning">'.
                   2647:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2648:                   '</span>'."\n" ;
1.349     albertel 2649:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2650:             "' name='increment' />";
1.485     albertel 2651: 	$endform.='</td></tr></table></form>';
1.41      ng       2652: 	$request->print($endform);
                   2653:     }
                   2654:     return '';
1.38      ng       2655: }
                   2656: 
1.464     albertel 2657: sub check_collaborators {
                   2658:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2659:     my ($result,@col_fullnames);
                   2660:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2661:     foreach my $part (keys(%$handgrade)) {
                   2662: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2663: 					'.maxcollaborators',
                   2664: 					$symb,$udom,$uname);
                   2665: 	next if ($ncol <= 0);
                   2666: 	$part =~ s/\_/\./g;
                   2667: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2668: 	my (@good_collaborators, @bad_collaborators);
                   2669: 	foreach my $possible_collaborator
1.630     www      2670: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2671: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2672: 	    next if ($possible_collaborator eq '');
1.631     www      2673: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2674: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2675: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2676: 	    # Doing this grep allows 'fuzzy' specification
                   2677: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2678: 			       keys(%$classlist));
                   2679: 	    if (! scalar(@matches)) {
                   2680: 		push(@bad_collaborators, $possible_collaborator);
                   2681: 	    } else {
                   2682: 		push(@good_collaborators, @matches);
                   2683: 	    }
                   2684: 	}
                   2685: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2686: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2687: 	    foreach my $name (@good_collaborators) {
                   2688: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2689: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2690: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2691: 	    }
1.630     www      2692: 	    $result.='</ol><br />'."\n";
1.466     albertel 2693: 	    my ($part)=split(/\./,$part);
1.464     albertel 2694: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2695: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2696: 		"\n";
                   2697: 	}
                   2698: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2699: 	    $result.='<div class="LC_warning">';
1.464     albertel 2700: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2701: 	    $result .= '</div>';
                   2702: 	}         
                   2703: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2704: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2705: 	    $result .= &mt('This student has submitted too many '.
                   2706: 		'collaborators.  Maximum is [_1].',$ncol);
                   2707: 	    $result .= '</div>';
                   2708: 	}
                   2709:     }
                   2710:     return ($result,$fullname,\@col_fullnames);
                   2711: }
                   2712: 
1.44      ng       2713: #--- Retrieve the last submission for all the parts
1.38      ng       2714: sub get_last_submission {
1.745     raeburn  2715:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2716:     my (@string,$timestamp,%lasthidden);
1.119     ng       2717:     if ($$returnhash{'version'}) {
1.46      ng       2718: 	my %lasthash=();
                   2719: 	my ($version);
1.119     ng       2720: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2721: 	    foreach my $key (sort(split(/\:/,
                   2722: 					$$returnhash{$version.':keys'}))) {
                   2723: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2724: 		$timestamp = 
1.545     raeburn  2725: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2726: 	    }
                   2727: 	}
1.640     raeburn  2728:         my (%typeparts,%randombytry);
1.596     raeburn  2729:         my $showsurv = 
                   2730:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2731:         foreach my $key (sort(keys(%lasthash))) {
                   2732:             if ($key =~ /\.type$/) {
                   2733:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2734:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2735:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2736:                     my ($ign,@parts) = split(/\./,$key);
                   2737:                     pop(@parts);
1.641     raeburn  2738:                     my $id = join('.',@parts);
1.640     raeburn  2739:                     if ($lasthash{$key} eq 'randomizetry') {
                   2740:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2741:                     } else {
                   2742:                         unless ($showsurv) {
                   2743:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2744:                         }
1.596     raeburn  2745:                     }
                   2746:                     delete($lasthash{$key});
                   2747:                 }
                   2748:             }
                   2749:         }
                   2750:         my @hidden = keys(%typeparts);
1.640     raeburn  2751:         my @randomize = keys(%randombytry);
1.397     albertel 2752: 	foreach my $key (keys(%lasthash)) {
                   2753: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2754:             my $hide;
                   2755:             if (@hidden) {
                   2756:                 foreach my $id (@hidden) {
                   2757:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2758:                         $hide = 'anon';
1.596     raeburn  2759:                         last;
                   2760:                     }
                   2761:                 }
                   2762:             }
1.640     raeburn  2763:             unless ($hide) {
                   2764:                 if (@randomize) {
1.732     raeburn  2765:                     foreach my $id (@randomize) {
1.640     raeburn  2766:                         if ($key =~ /^\Q$id\E/) {
                   2767:                             $hide = 'rand';
                   2768:                             last;
                   2769:                         }
                   2770:                     }
                   2771:                 }
                   2772:             }
1.397     albertel 2773: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2774: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2775:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2776:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2777:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2778: 	}
                   2779:     }
1.397     albertel 2780:     if (!@string) {
1.745     raeburn  2781:         my $msg;
                   2782:         if ($is_tool) {
1.747     raeburn  2783:             $msg = &mt('No grade passed back.');
1.745     raeburn  2784:         } else {
                   2785:             $msg = &mt('Nothing submitted - no attempts.');
                   2786:         }
1.397     albertel 2787: 	$string[0] =
1.745     raeburn  2788: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2789:     }
                   2790:     return (\@string,\$timestamp);
1.38      ng       2791: }
1.35      ng       2792: 
1.44      ng       2793: #--- High light keywords, with style choosen by user.
1.38      ng       2794: sub keywords_highlight {
1.44      ng       2795:     my $string    = shift;
1.257     albertel 2796:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2797:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2798:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2799:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2800:     foreach my $keyword (@keylist) {
                   2801: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2802:     }
                   2803:     return $string;
1.38      ng       2804: }
1.36      ng       2805: 
1.671     raeburn  2806: # For Tasks provide a mechanism to display previous version for one specific student
                   2807: 
                   2808: sub show_previous_task_version {
                   2809:     my ($request,$symb) = @_;
                   2810:     if ($symb eq '') {
1.717     bisitz   2811:         $request->print(
                   2812:             '<span class="LC_error">'.
                   2813:             &mt('Unable to handle ambiguous references.').
                   2814:             '</span>');
1.671     raeburn  2815:         return '';
                   2816:     }
                   2817:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2818:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2819:     if (!&canview($usec)) {
1.712     bisitz   2820:         $request->print(
                   2821:             '<span class="LC_warning">'.
1.713     bisitz   2822:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2823:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2824:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2825:             '</span>');
1.671     raeburn  2826:         return;
                   2827:     }
                   2828:     my $mode = 'both';
                   2829:     my $isTask = ($symb =~/\.task$/);
                   2830:     if ($isTask) {
                   2831:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2832:             if ($env{'form.fullname'} eq '') {
                   2833:                 $env{'form.fullname'} =
                   2834:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2835:             }
                   2836:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2837:             $request->print("\n\n".
                   2838:                             '<div class="LC_grade_show_user">'.
                   2839:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2840:                             '</h2>'."\n");
                   2841:             &Apache::lonxml::clear_problem_counter();
                   2842:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2843:                             {'previousversion' => $env{'form.previousversion'} }));
                   2844:             $request->print("\n</div>");
                   2845:         }
                   2846:     }
                   2847:     return;
                   2848: }
                   2849: 
                   2850: sub choose_task_version_form {
                   2851:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2852:     my $isTask = ($symb =~/\.task$/);
                   2853:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2854:     if ($isTask) {
                   2855:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2856:                                               $udom,$uname);
                   2857:         if (($record{'resource.0.version'} eq '') ||
                   2858:             ($record{'resource.0.version'} < 2)) {
                   2859:             return ($record{'resource.0.version'},
                   2860:                     $record{'resource.0.version'},$result,$js);
                   2861:         } else {
                   2862:             $current = $record{'resource.0.version'};
                   2863:         }
                   2864:         if ($env{'form.previousversion'}) {
                   2865:             $displayed = $env{'form.previousversion'};
                   2866:             $rowtitle = &mt('Choose another version:')
                   2867:         } else {
                   2868:             $displayed = $current;
                   2869:             $rowtitle = &mt('Show earlier version:');
                   2870:         }
                   2871:         $result = '<div class="LC_left_float">';
                   2872:         my $list;
                   2873:         my $numversions = 0;
                   2874:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2875:             if ($i == $current) {
                   2876:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2877:                     next;
                   2878:                 } else {
                   2879:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2880:                     $numversions ++;
                   2881:                 }
                   2882:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2883:                 unless ($i == $env{'form.previousversion'}) {
                   2884:                     $numversions ++;
                   2885:                 }
                   2886:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2887:             }
                   2888:         }
                   2889:         if ($numversions) {
                   2890:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2891:             $result .=
                   2892:                 '<form name="getprev" method="post" action=""'.
                   2893:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2894:                 &Apache::loncommon::start_data_table().
                   2895:                 &Apache::loncommon::start_data_table_row().
                   2896:                 '<th align="left">'.$rowtitle.'</th>'.
                   2897:                 '<td><select name="version">'.
                   2898:                 '<option>'.&mt('Select').'</option>'.
                   2899:                 $list.
                   2900:                 '</select></td>'.
                   2901:                 &Apache::loncommon::end_data_table_row();
                   2902:             unless ($nomenu) {
                   2903:                 $result .= &Apache::loncommon::start_data_table_row().
                   2904:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2905:                 '<td><span class="LC_nobreak">'.
                   2906:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2907:                 &mt('Yes').'</label>'.
                   2908:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2909:                 '</span></td>'.
                   2910:                 &Apache::loncommon::end_data_table_row();
                   2911:             }
                   2912:             $result .=
                   2913:                 &Apache::loncommon::start_data_table_row().
                   2914:                 '<th align="left">&nbsp;</th>'.
                   2915:                 '<td>'.
                   2916:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2917:                 '</td>'.
                   2918:                 &Apache::loncommon::end_data_table_row().
                   2919:                 &Apache::loncommon::end_data_table().
                   2920:                 '</form>';
                   2921:             $js = &previous_display_javascript($nomenu,$current);
                   2922:         } elsif ($displayed && $nomenu) {
                   2923:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2924:         } else {
                   2925:             $result .= &mt('No previous versions to show for this student');
                   2926:         }
                   2927:         $result .= '</div>';
                   2928:     }
                   2929:     return ($current,$displayed,$result,$js);
                   2930: }
                   2931: 
                   2932: sub previous_display_javascript {
                   2933:     my ($nomenu,$current) = @_;
                   2934:     my $js = <<"JSONE";
                   2935: <script type="text/javascript">
                   2936: // <![CDATA[
                   2937: function previousVersion(uname,udom,symb) {
                   2938:     var current = '$current';
                   2939:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2940:     var prevstr = new RegExp("^\\\\d+\$");
                   2941:     if (!prevstr.test(version)) {
                   2942:         return false;
                   2943:     }
                   2944:     var url = '';
                   2945:     if (version == current) {
                   2946:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2947:     } else {
                   2948:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2949:     }
                   2950: JSONE
                   2951:     if ($nomenu) {
                   2952:         $js .= <<"JSTWO";
                   2953:     document.location.href = url;
                   2954: JSTWO
                   2955:     } else {
                   2956:         $js .= <<"JSTHREE";
                   2957:     var newwin = 0;
                   2958:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2959:         if (document.getprev.prevwin[i].checked == true) {
                   2960:             newwin = document.getprev.prevwin[i].value;
                   2961:         }
                   2962:     }
                   2963:     if (newwin == 1) {
                   2964:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2965:         url = url+'&inhibitmenu=yes';
                   2966:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2967:             previousWin = window.open(url,'',options,1);
                   2968:         } else {
                   2969:             previousWin.location.href = url;
                   2970:         }
                   2971:         previousWin.focus();
                   2972:         return false;
                   2973:     } else {
                   2974:         document.location.href = url;
                   2975:         return false;
                   2976:     }
                   2977: JSTHREE
                   2978:     }
                   2979:     $js .= <<"ENDJS";
                   2980:     return false;
                   2981: }
                   2982: // ]]>
                   2983: </script>
                   2984: ENDJS
                   2985: 
                   2986: }
                   2987: 
1.44      ng       2988: #--- Called from submission routine
1.38      ng       2989: sub processHandGrade {
1.608     www      2990:     my ($request,$symb) = @_;
1.324     albertel 2991:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2992:     my $button = $env{'form.gradeOpt'};
                   2993:     my $ngrade = $env{'form.NCT'};
                   2994:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2995:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2996:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2997: 
1.44      ng       2998:     if ($button eq 'Save & Next') {
                   2999: 	my $ctr = 0;
                   3000: 	while ($ctr < $ngrade) {
1.257     albertel 3001: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3002: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3003:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3004: 	    if ($errorflag eq 'no_score') {
                   3005: 		$ctr++;
                   3006: 		next;
                   3007: 	    }
1.104     albertel 3008: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3009: 		$request->print(
                   3010:                     '<span class="LC_error">'
                   3011:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3012:                    .'</span>');
1.104     albertel 3013: 		$ctr++;
                   3014: 		next;
                   3015: 	    }
1.726     raeburn  3016:             if ($numhidden) {
                   3017:                 $request->print(
                   3018:                     '<span class="LC_info">'
                   3019:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3020:                    .'</span><br />');
                   3021:             }
1.257     albertel 3022: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3023: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3024: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3025:             my ($feedurl,$showsymb) =
                   3026: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3027: 	    my $messagetail;
1.62      albertel 3028: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3029: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3030: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3031: 		$subject.=' ['.$restitle.']';
1.44      ng       3032: 		my (@msgnum) = split(/,/,$includemsg);
                   3033: 		foreach (@msgnum) {
1.257     albertel 3034: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3035: 		}
1.80      ng       3036: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3037: 		if ($env{'form.withgrades'.$ctr}) {
                   3038: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3039: 		    $messagetail = " for <a href=\"".
1.605     www      3040: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3041: 		}
                   3042: 		$msgstatus = 
                   3043:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3044: 						     $message.$messagetail,
1.418     albertel 3045:                                                      undef,$feedurl,undef,
1.386     raeburn  3046:                                                      undef,undef,$showsymb,
                   3047:                                                      $restitle);
1.574     bisitz   3048: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3049: 				$msgstatus.'<br />');
1.44      ng       3050: 	    }
1.257     albertel 3051: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3052: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3053: 		foreach my $collabstr (@collabstrs) {
                   3054: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3055: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3056: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3057: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3058: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3059: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3060: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3061: 			    next;
1.418     albertel 3062: 			} elsif ($message ne '') {
                   3063: 			    my ($baseurl,$showsymb) = 
                   3064: 				&get_feedurl_and_symb($symb,$collaborator,
                   3065: 						      $udom);
                   3066: 			    if ($env{'form.withgrades'.$ctr}) {
                   3067: 				$messagetail = " for <a href=\"".
1.605     www      3068:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3069: 			    }
1.418     albertel 3070: 			    $msgstatus = 
                   3071: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3072: 			}
1.44      ng       3073: 		    }
                   3074: 		}
                   3075: 	    }
                   3076: 	    $ctr++;
                   3077: 	}
                   3078:     }
                   3079: 
1.624     www      3080: #    if ($env{'form.handgrade'} eq 'yes') {
                   3081:     if (1) {
1.119     ng       3082: 	# Keywords sorted in alphabatical order
1.257     albertel 3083: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       3084: 	my %keyhash = ();
1.257     albertel 3085: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3086: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3087: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3088: 	$env{'form.keywords'} = join(' ',@keywords);
                   3089: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3090: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3091: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3092: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3093: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       3094: 
                   3095: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3096: 	# New messages are saved in env for the next student.
1.119     ng       3097: 	# All messages are saved in nohist_handgrade.db
                   3098: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3099: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3100: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3101: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3102: 		$idx++;
                   3103: 	    }
                   3104: 	    $ctr++;
1.41      ng       3105: 	}
1.119     ng       3106: 	$ctr = 0;
                   3107: 	while ($ctr < $ngrade) {
1.257     albertel 3108: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3109: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3110: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3111: 		$idx++;
                   3112: 	    }
                   3113: 	    $ctr++;
1.41      ng       3114: 	}
1.257     albertel 3115: 	$env{'form.savemsgN'} = --$idx;
                   3116: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       3117: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3118: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3119:     }
1.44      ng       3120:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3121:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3122:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3123: 	my ($ctr,$total) = (0,0);
                   3124: 	while ($ctr < $ngrade) {
1.257     albertel 3125: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3126: 	    $ctr++;
                   3127: 	}
1.257     albertel 3128: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3129: 	$ctr = 0;
                   3130: 	while ($ctr < $total) {
1.257     albertel 3131: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3132: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3133: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3134: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3135: 	    $ctr++;
                   3136: 	}
                   3137: 	return '';
                   3138:     }
1.36      ng       3139: 
1.44      ng       3140:     # Get the next/previous one or group of students
1.257     albertel 3141:     my $firststu = $env{'form.unamedom0'};
                   3142:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3143:     my $ctr = 2;
1.41      ng       3144:     while ($laststu eq '') {
1.257     albertel 3145: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3146: 	$ctr++;
                   3147: 	$laststu = $firststu if ($ctr > $ngrade);
                   3148:     }
1.44      ng       3149: 
1.41      ng       3150:     my (@parsedlist,@nextlist);
                   3151:     my ($nextflg) = 0;
1.524     raeburn  3152:     foreach my $item (sort 
1.294     albertel 3153: 	     {
                   3154: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3155: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3156: 		 }
                   3157: 		 return $a cmp $b;
                   3158: 	     } (keys(%$fullname))) {
1.605     www      3159: # FIXME: this is fishy, looks like the button label
1.41      ng       3160: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3161: 	    push(@parsedlist,$item);
1.41      ng       3162: 	}
1.524     raeburn  3163: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3164: 	if ($button eq 'Previous') {
1.524     raeburn  3165: 	    last if ($item eq $firststu);
                   3166: 	    push(@parsedlist,$item);
1.41      ng       3167: 	}
                   3168:     }
                   3169:     $ctr = 0;
1.605     www      3170: # FIXME: this is fishy, looks like the button label
1.41      ng       3171:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3172:     my $res_error;
                   3173:     my ($partlist) = &response_type($symb,\$res_error);
                   3174:     if ($res_error) {
                   3175:         $request->print(&navmap_errormsg());
                   3176:         return;
                   3177:     }
1.41      ng       3178:     foreach my $student (@parsedlist) {
1.257     albertel 3179: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3180: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3181: 	
                   3182: 	if ($submitonly eq 'queued') {
                   3183: 	    my %queue_status = 
                   3184: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3185: 							$udom,$uname);
                   3186: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3187: 	}
                   3188: 
1.156     albertel 3189: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3190: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3191: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3192: 	    my $submitted = 0;
1.248     albertel 3193: 	    my $ungraded = 0;
                   3194: 	    my $incorrect = 0;
1.524     raeburn  3195: 	    foreach my $item (keys(%status)) {
                   3196: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3197: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3198: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3199: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3200: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3201: 		    $submitted = 0;
                   3202: 		}
1.41      ng       3203: 	    }
1.156     albertel 3204: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3205: 				     $submitonly eq 'incorrect' ||
                   3206: 				     $submitonly eq 'graded'));
1.248     albertel 3207: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3208: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3209: 	}
1.524     raeburn  3210: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3211: 	last if ($ctr == $ntstu);
1.41      ng       3212: 	$ctr++;
                   3213:     }
1.36      ng       3214: 
1.41      ng       3215:     $ctr = 0;
                   3216:     my $total = scalar(@nextlist)-1;
1.39      ng       3217: 
1.524     raeburn  3218:     foreach (sort(@nextlist)) {
1.41      ng       3219: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3220: 	$env{'form.student'}  = $uname;
                   3221: 	$env{'form.userdom'}  = $udom;
                   3222: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3223: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3224: 	$ctr++;
                   3225:     }
                   3226:     if ($total < 0) {
1.653     raeburn  3227: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3228: 	$request->print($the_end);
                   3229:     }
                   3230:     return '';
1.38      ng       3231: }
1.36      ng       3232: 
1.44      ng       3233: #---- Save the score and award for each student, if changed
1.38      ng       3234: sub saveHandGrade {
1.324     albertel 3235:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3236:     my @version_parts;
1.104     albertel 3237:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3238: 					   $env{'request.course.id'});
1.104     albertel 3239:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3240:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3241:     my @parts_graded;
1.77      ng       3242:     my %newrecord  = ();
1.726     raeburn  3243:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3244:     my %aggregate = ();
                   3245:     my $aggregateflag = 0;
1.726     raeburn  3246:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3247:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3248:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3249:         $totchg += $numchgs;
                   3250:     }
1.301     albertel 3251:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3252:     foreach my $new_part (@parts) {
1.337     banghart 3253: 	#collaborator ($submi may vary for different parts
1.259     banghart 3254: 	if ($submitter && $new_part ne $part) { next; }
                   3255: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3256: 	if ($dropMenu eq 'excused') {
1.259     banghart 3257: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3258: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3259: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3260: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3261: 		}
1.364     banghart 3262: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3263: 	    }
1.125     ng       3264: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3265: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3266: 	    foreach my $key (keys(%record)) {
1.259     banghart 3267: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3268: 	    }
1.259     banghart 3269: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3270: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3271:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3272: 
                   3273:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3274: 					       [$new_part]);
                   3275:             my $aggtries =$totaltries;
1.269     raeburn  3276:             if ($last_resets{$new_part}) {
1.270     albertel 3277:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3278: 					   $new_part);
1.269     raeburn  3279:             }
1.270     albertel 3280: 
                   3281:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3282:             if ($aggtries > 0) {
1.327     albertel 3283:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3284:                 $aggregateflag = 1;
                   3285:             }
1.125     ng       3286: 	} elsif ($dropMenu eq '') {
1.259     banghart 3287: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3288: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3289: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3290: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3291: 		next;
                   3292: 	    }
1.259     banghart 3293: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3294: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3295: 	    my $partial= $pts/$wgt;
1.259     banghart 3296: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3297: 		#do not update score for part if not changed.
1.346     banghart 3298:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3299: 		next;
1.251     banghart 3300: 	    } else {
1.524     raeburn  3301: 	        push(@parts_graded,$new_part);
1.153     albertel 3302: 	    }
1.259     banghart 3303: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3304: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3305: 	    }
1.259     banghart 3306: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3307: 	    if ($partial == 0) {
1.153     albertel 3308: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3309: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3310: 		}
1.41      ng       3311: 	    } else {
1.153     albertel 3312: 		if ($record{$reckey} ne 'correct_by_override') {
                   3313: 		    $newrecord{$reckey} = 'correct_by_override';
                   3314: 		}
                   3315: 	    }	    
                   3316: 	    if ($submitter && 
1.259     banghart 3317: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3318: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3319: 	    }
1.259     banghart 3320: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3321: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3322: 	}
1.259     banghart 3323: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3324: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3325: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3326: 	        $dropMenu eq 'reset status')
                   3327: 	   {
1.524     raeburn  3328: 	    push(@version_parts,$new_part);
1.259     banghart 3329: 	}
1.41      ng       3330:     }
1.301     albertel 3331:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3332:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3333: 
1.344     albertel 3334:     if (%newrecord) {
                   3335:         if (@version_parts) {
1.364     banghart 3336:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3337:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3338: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3339: 	    foreach my $new_part (@version_parts) {
                   3340: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3341: 				$new_part,\%newrecord);
                   3342: 	    }
1.259     banghart 3343:         }
1.44      ng       3344: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3345: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3346: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3347: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3348:     }
1.269     raeburn  3349:     if ($aggregateflag) {
                   3350:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3351: 			      $cdom,$cnum);
1.269     raeburn  3352:     }
1.726     raeburn  3353:     return ('',$pts,$wgt,$totchg);
                   3354: }
                   3355: 
                   3356: sub makehidden {
1.728     raeburn  3357:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3358:     return unless (ref($record) eq 'HASH');
                   3359:     my %modified;
                   3360:     my $numchanged = 0;
                   3361:     if (exists($record->{$version.':keys'})) {
                   3362:         my $partsregexp = $parts;
                   3363:         $partsregexp =~ s/,/|/g;
                   3364:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3365:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3366:                  my $item = $1;
                   3367:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3368:                      $modified{$key} = $record->{$version.':'.$key};
                   3369:                  }
                   3370:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3371:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3372:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3373:                 $modified{$key} = $record->{$version.':'.$key};
                   3374:             }
                   3375:         }
                   3376:         if (keys(%modified)) {
                   3377:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3378:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3379:                 $numchanged ++;
                   3380:             }
                   3381:         }
                   3382:     }
                   3383:     return $numchanged;
1.36      ng       3384: }
1.322     albertel 3385: 
1.380     albertel 3386: sub check_and_remove_from_queue {
                   3387:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3388:     my @ungraded_parts;
                   3389:     foreach my $part (@{$parts}) {
                   3390: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3391: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3392: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3393: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3394: 		) {
                   3395: 	    push(@ungraded_parts, $part);
                   3396: 	}
                   3397:     }
                   3398:     if ( !@ungraded_parts ) {
                   3399: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3400: 					       $cnum,$domain,$stuname);
                   3401:     }
                   3402: }
                   3403: 
1.337     banghart 3404: sub handback_files {
                   3405:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3406:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3407:     my $res_error;
                   3408:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3409:     if ($res_error) {
                   3410:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3411:         return;
                   3412:     }
1.654     raeburn  3413:     my @handedback;
                   3414:     my $file_msg;
1.375     albertel 3415:     my @part_response_id = &flatten_responseType($responseType);
                   3416:     foreach my $part_response_id (@part_response_id) {
                   3417:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3418: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3419:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3420:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3421:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3422:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3423:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3424:                     my ($directory,$answer_file) = 
1.654     raeburn  3425:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3426:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3427: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3428: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3429:                     my $getpropath = 1;
1.662     raeburn  3430:                     my ($dir_list,$listerror) = 
                   3431:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3432:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3433: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3434:                     # fix filename
1.355     banghart 3435:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3436:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3437:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3438:             	                                $save_file_name);
1.337     banghart 3439:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3440:                         $request->print('<br /><span class="LC_error">'.
                   3441:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3442:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3443:                                         '</span>');
1.356     banghart 3444:                     } else {
1.360     banghart 3445:                         # mark the file as read only
1.654     raeburn  3446:                         push(@handedback,$save_file_name);
1.367     albertel 3447: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3448: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3449: 			}
                   3450:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3451: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3452:                     }
1.686     bisitz   3453:                     $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 3454:                 }
                   3455:             }
                   3456:         }
1.654     raeburn  3457:     }
                   3458:     if (@handedback > 0) {
                   3459:         $request->print('<br />');
                   3460:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3461:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3462:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3463:         my ($subject,$message);
                   3464:         if (scalar(@handedback) == 1) {
                   3465:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3466:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3467:         } else {
                   3468:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3469:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3470:         }
                   3471:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3472:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3473:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3474:         my ($feedurl,$showsymb) =
                   3475:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3476:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3477:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3478:         my $msgstatus =
                   3479:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3480:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3481:                  $restitle);
                   3482:         if ($msgstatus) {
                   3483:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3484:         }
                   3485:     }
1.338     banghart 3486:     return;
1.337     banghart 3487: }
                   3488: 
1.418     albertel 3489: sub get_feedurl_and_symb {
                   3490:     my ($symb,$uname,$udom) = @_;
                   3491:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3492:     $url = &Apache::lonnet::clutter($url);
                   3493:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3494: 					$symb,$udom,$uname);
                   3495:     if ($encrypturl =~ /^yes$/i) {
                   3496: 	&Apache::lonenc::encrypted(\$url,1);
                   3497: 	&Apache::lonenc::encrypted(\$symb,1);
                   3498:     }
                   3499:     return ($url,$symb);
                   3500: }
                   3501: 
1.313     banghart 3502: sub get_submitted_files {
                   3503:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3504:     my @files;
                   3505:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3506:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3507:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3508:     	    push(@files,$file_url.$file);
                   3509:         }
                   3510:     }
                   3511:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3512:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3513:     }
                   3514:     return (\@files);
                   3515: }
1.322     albertel 3516: 
1.269     raeburn  3517: # ----------- Provides number of tries since last reset.
                   3518: sub get_num_tries {
                   3519:     my ($record,$last_reset,$part) = @_;
                   3520:     my $timestamp = '';
                   3521:     my $num_tries = 0;
                   3522:     if ($$record{'version'}) {
                   3523:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3524:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3525:                 $timestamp = $$record{$version.':timestamp'};
                   3526:                 if ($timestamp > $last_reset) {
                   3527:                     $num_tries ++;
                   3528:                 } else {
                   3529:                     last;
                   3530:                 }
                   3531:             }
                   3532:         }
                   3533:     }
                   3534:     return $num_tries;
                   3535: }
                   3536: 
                   3537: # ----------- Determine decrements required in aggregate totals 
                   3538: sub decrement_aggs {
                   3539:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3540:     my %decrement = (
                   3541:                         attempts => 0,
                   3542:                         users => 0,
                   3543:                         correct => 0
                   3544:                     );
                   3545:     $decrement{'attempts'} = $aggtries;
                   3546:     if ($solvedstatus =~ /^correct/) {
                   3547:         $decrement{'correct'} = 1;
                   3548:     }
                   3549:     if ($aggtries == $totaltries) {
                   3550:         $decrement{'users'} = 1;
                   3551:     }
1.524     raeburn  3552:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3553:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3554:     }
                   3555:     return;
                   3556: }
                   3557: 
                   3558: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3559: sub get_last_resets {
1.270     albertel 3560:     my ($symb,$courseid,$partids) =@_;
                   3561:     my %last_resets;
1.269     raeburn  3562:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3563:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3564:     my @keys;
                   3565:     foreach my $part (@{$partids}) {
                   3566: 	push(@keys,"$symb\0$part\0resettime");
                   3567:     }
                   3568:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3569: 				     $cdom,$cname);
                   3570:     foreach my $part (@{$partids}) {
                   3571: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3572:     }
1.270     albertel 3573:     return %last_resets;
1.269     raeburn  3574: }
                   3575: 
1.251     banghart 3576: # ----------- Handles creating versions for portfolio files as answers
                   3577: sub version_portfiles {
1.343     banghart 3578:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3579:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3580:     my @returned_keys;
1.255     banghart 3581:     my $parts = join('|', @$parts_graded);
1.277     albertel 3582:     foreach my $key (keys(%$record)) {
1.259     banghart 3583:         my $new_portfiles;
1.263     banghart 3584:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3585:             my @versioned_portfiles;
1.367     albertel 3586:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3587:             if (@portfiles) {
                   3588:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3589:                                                       \@versioned_portfiles);
1.252     banghart 3590:             }
1.343     banghart 3591:             $$record{$key} = join(',',@versioned_portfiles);
                   3592:             push(@returned_keys,$key);
1.251     banghart 3593:         }
                   3594:     } 
1.343     banghart 3595:     return (@returned_keys);   
1.305     banghart 3596: }
                   3597: 
1.44      ng       3598: #--------------------------------------------------------------------------------------
                   3599: #
                   3600: #-------------------------- Next few routines handles grading by section or whole class
                   3601: #
                   3602: #--- Javascript to handle grading by section or whole class
1.42      ng       3603: sub viewgrades_js {
                   3604:     my ($request) = shift;
                   3605: 
1.539     riegler  3606:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3607:     &js_escape(\$alertmsg);
1.597     wenzelju 3608:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3609:    function writePoint(partid,weight,point) {
1.125     ng       3610: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3611: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3612: 	if (point == "textval") {
1.125     ng       3613: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3614: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3615: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3616: 		var resetbox = false;
                   3617: 		for (var i=0; i<radioButton.length; i++) {
                   3618: 		    if (radioButton[i].checked) {
                   3619: 			textbox.value = i;
                   3620: 			resetbox = true;
                   3621: 		    }
                   3622: 		}
                   3623: 		if (!resetbox) {
                   3624: 		    textbox.value = "";
                   3625: 		}
                   3626: 		return;
                   3627: 	    }
1.109     matthew  3628: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3629: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3630: 				   ") greater than the weight for the part. Accept?");
                   3631: 		if (resp == false) {
                   3632: 		    textbox.value = "";
                   3633: 		    return;
                   3634: 		}
                   3635: 	    }
1.42      ng       3636: 	    for (var i=0; i<radioButton.length; i++) {
                   3637: 		radioButton[i].checked=false;
1.109     matthew  3638: 		if (parseFloat(point) == i) {
1.42      ng       3639: 		    radioButton[i].checked=true;
                   3640: 		}
                   3641: 	    }
1.41      ng       3642: 
1.42      ng       3643: 	} else {
1.125     ng       3644: 	    textbox.value = parseFloat(point);
1.42      ng       3645: 	}
1.41      ng       3646: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3647: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3648: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3649: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3650: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3651: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3652: 	    if (saveval != "correct") {
                   3653: 		scorename.value = point;
1.43      ng       3654: 		if (selname[0].selected != true) {
                   3655: 		    selname[0].selected = true;
                   3656: 		}
1.42      ng       3657: 	    }
                   3658: 	}
1.125     ng       3659: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3660:     }
                   3661: 
                   3662:     function writeRadText(partid,weight) {
1.125     ng       3663: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3664: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3665:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3666: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3667: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3668: 	    for (var i=0; i<radioButton.length; i++) {
                   3669: 		radioButton[i].checked=false;
                   3670: 
                   3671: 	    }
                   3672: 	    textbox.value = "";
                   3673: 
                   3674: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3675: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3676: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3677: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3678: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3679: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3680: 		if ((saveval != "correct") || override) {
1.42      ng       3681: 		    scorename.value = "";
1.125     ng       3682: 		    if (selval[1].selected) {
                   3683: 			selname[1].selected = true;
                   3684: 		    } else {
                   3685: 			selname[2].selected = true;
                   3686: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3687: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3688: 		    }
1.42      ng       3689: 		}
                   3690: 	    }
1.43      ng       3691: 	} else {
                   3692: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3693: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3694: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3695: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3696: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3697: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3698: 		if ((saveval != "correct") || override) {
1.125     ng       3699: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3700: 		    selname[0].selected = true;
                   3701: 		}
                   3702: 	    }
                   3703: 	}	    
1.42      ng       3704:     }
                   3705: 
                   3706:     function changeSelect(partid,user) {
1.125     ng       3707: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3708: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3709: 	var point  = textbox.value;
1.125     ng       3710: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3711: 
1.109     matthew  3712: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3713: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3714: 	    textbox.value = "";
                   3715: 	    return;
                   3716: 	}
1.109     matthew  3717: 	if (parseFloat(point) > parseFloat(weight)) {
                   3718: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3719: 			       ") greater than the weight of the part. Accept?");
                   3720: 	    if (resp == false) {
                   3721: 		textbox.value = "";
                   3722: 		return;
                   3723: 	    }
                   3724: 	}
1.42      ng       3725: 	selval[0].selected = true;
                   3726:     }
                   3727: 
                   3728:     function changeOneScore(partid,user) {
1.125     ng       3729: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3730: 	if (selval[1].selected || selval[2].selected) {
                   3731: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3732: 	    if (selval[2].selected) {
                   3733: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3734: 	    }
1.269     raeburn  3735:         }
1.42      ng       3736:     }
                   3737: 
                   3738:     function resetEntry(numpart) {
                   3739: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3740: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3741: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3742: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3743: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3744: 	    for (var i=0; i<radioButton.length; i++) {
                   3745: 		radioButton[i].checked=false;
                   3746: 
                   3747: 	    }
                   3748: 	    textbox.value = "";
                   3749: 	    selval[0].selected = true;
                   3750: 
                   3751: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3752: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3753: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3754: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3755: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3756: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3757: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3758: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3759: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3760: 		if (saveselval == "excused") {
1.43      ng       3761: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3762: 		} else {
1.43      ng       3763: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3764: 		}
                   3765: 	    }
1.41      ng       3766: 	}
1.42      ng       3767:     }
                   3768: 
1.41      ng       3769: VIEWJAVASCRIPT
1.42      ng       3770: }
                   3771: 
1.44      ng       3772: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3773: sub viewgrades {
1.608     www      3774:     my ($request,$symb) = @_;
1.745     raeburn  3775:     my ($is_tool,$toolsymb);
                   3776:     if ($symb =~ /ext\.tool$/) {
                   3777:         $is_tool = 1;
                   3778:         $toolsymb = $symb;
                   3779:     }
1.42      ng       3780:     &viewgrades_js($request);
1.41      ng       3781: 
1.168     albertel 3782:     #need to make sure we have the correct data for later EXT calls, 
                   3783:     #thus invalidate the cache
                   3784:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3785:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3786:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3787:     &Apache::lonnet::clear_EXT_cache_status();
                   3788: 
1.398     albertel 3789:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3790: 
                   3791:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3792:     $result.=&jscriptNform($symb);
1.41      ng       3793: 
1.44      ng       3794:     #beginning of class grading form
1.442     banghart 3795:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3796:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3797: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3798: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3799: 	&build_section_inputs().
1.442     banghart 3800: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3801: 
1.738     raeburn  3802:     #retrieve selected groups
                   3803:     my (@groups,$group_display);
                   3804:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3805:     if (grep(/^all$/,@groups)) {
                   3806:         @groups = ('all');
                   3807:     } elsif (grep(/^none$/,@groups)) {
                   3808:         @groups = ('none');
                   3809:     } elsif (@groups > 0) {
                   3810:         $group_display = join(', ',@groups);
                   3811:     }
                   3812: 
                   3813:     my ($common_header,$specific_header,@sections,$section_display);
                   3814:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3815:     if (grep(/^all$/,@sections)) {
                   3816:         @sections = ('all');
                   3817:         if ($group_display) {
                   3818:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3819:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3820:         } elsif (grep(/^none$/,@groups)) {
                   3821:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3822:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3823:         } else {
                   3824: 	    $common_header = &mt('Assign Common Grade to Class');
                   3825:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3826:         }
                   3827:     } elsif (grep(/^none$/,@sections)) {
                   3828:         @sections = ('none');
                   3829:         if ($group_display) {
                   3830:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3831:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3832:         } elsif (grep(/^none$/,@groups)) {
                   3833:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3834:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3835:         } else {
                   3836:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3837: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3838:         }
                   3839:     } else {
                   3840:         $section_display = join (", ",@sections);
                   3841:         if ($group_display) {
                   3842:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3843:                                  $section_display,$group_display);
                   3844:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3845:                                    $section_display,$group_display);
                   3846:         } elsif (grep(/^none$/,@groups)) {
                   3847:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3848:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3849:         } else {
                   3850:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3851: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3852:         }
                   3853:     }
                   3854:     my %submit_types = &substatus_options();
                   3855:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3856: 
                   3857:     if ($env{'form.submitonly'} eq 'all') {
                   3858:         $result.= '<h3>'.$common_header.'</h3>';
                   3859:     } else {
1.745     raeburn  3860:         my $text;
                   3861:         if ($is_tool) {
                   3862:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3863:         } else {
                   3864:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3865:         }
                   3866:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3867:     }
1.738     raeburn  3868:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3869:     #radio buttons/text box for assigning points for a section or class.
                   3870:     #handles different parts of a problem
1.582     raeburn  3871:     my $res_error;
                   3872:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3873:     if ($res_error) {
                   3874:         return &navmap_errormsg();
                   3875:     }
1.42      ng       3876:     my %weight = ();
                   3877:     my $ctsparts = 0;
1.45      ng       3878:     my %seen = ();
1.745     raeburn  3879:     my @part_response_id;
                   3880:     if ($is_tool) {
                   3881:         @part_response_id = ([0,'']);
                   3882:     } else {
                   3883:         @part_response_id = &flatten_responseType($responseType);
                   3884:     }
1.375     albertel 3885:     foreach my $part_response_id (@part_response_id) {
                   3886:     	my ($partid,$respid) = @{ $part_response_id };
                   3887: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3888: 	next if $seen{$partid};
                   3889: 	$seen{$partid}++;
1.744     raeburn  3890: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3891: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3892: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3893: 
1.324     albertel 3894: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3895: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3896: 	my $ctr = 0;
1.42      ng       3897: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3898: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3899: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3900: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3901: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3902: 	    $ctr++;
                   3903: 	}
1.485     albertel 3904: 	$radio.='</tr></table>';
                   3905: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3906: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3907: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3908: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3909:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3910:             '<select name="SELVAL_'.$partid.'" '.
                   3911:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3912:                 $weight{$partid}.')"> '.
1.401     albertel 3913: 	    '<option selected="selected"> </option>'.
1.485     albertel 3914: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3915: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3916: 	    '</select></td>'.
                   3917:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3918: 	$line.='<input type="hidden" name="partid_'.
                   3919: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3920: 	$line.='<input type="hidden" name="weight_'.
                   3921: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3922: 
                   3923: 	$result.=
                   3924: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3925: 	    '<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 3926: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3927: 	$ctsparts++;
1.41      ng       3928:     }
1.474     albertel 3929:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3930: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3931:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3932: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3933: 
1.44      ng       3934:     #table listing all the students in a section/class
                   3935:     #header of table
1.738     raeburn  3936:     if ($env{'form.submitonly'} eq 'all') {
                   3937:         $result.= '<h3>'.$specific_header.'</h3>';
                   3938:     } else {
1.745     raeburn  3939:         my $text;
                   3940:         if ($is_tool) {
                   3941:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3942:         } else {
                   3943:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3944:         }
                   3945:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3946:     }
                   3947:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3948: 	      &Apache::loncommon::start_data_table_header_row().
                   3949: 	      '<th>'.&mt('No.').'</th>'.
                   3950: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3951:     my $partserror;
                   3952:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3953:     if ($partserror) {
                   3954:         return &navmap_errormsg();
                   3955:     }
1.324     albertel 3956:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3957:     my @partids = ();
1.41      ng       3958:     foreach my $part (@parts) {
1.745     raeburn  3959: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3960:         my $narrowtext = &mt('Tries');
                   3961: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3962: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3963: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3964:         push(@partids,$partid);
1.628     www      3965: #
                   3966: # FIXME: Looks like $display looks at English text
                   3967: #
1.324     albertel 3968: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3969: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3970: 	    $result.='<th>'.
1.697     bisitz   3971: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3972: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3973: 	    next;
1.485     albertel 3974: 	    
1.207     albertel 3975: 	} else {
1.485     albertel 3976: 	    if ($display =~ /Problem Status/) {
                   3977: 		my $grade_status_mt = &mt('Grade Status');
                   3978: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3979: 	    }
                   3980: 	    my $part_mt = &mt('Part:');
                   3981: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3982: 	}
1.485     albertel 3983: 
1.474     albertel 3984: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3985:     }
1.474     albertel 3986:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3987: 
1.270     albertel 3988:     my %last_resets = 
                   3989: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3990: 
1.41      ng       3991:     #get info for each student
1.44      ng       3992:     #list all the students - with points and grade status
1.738     raeburn  3993:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3994:     my $ctr = 0;
1.294     albertel 3995:     foreach (sort 
                   3996: 	     {
                   3997: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3998: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3999: 		 }
                   4000: 		 return $a cmp $b;
                   4001: 	     } (keys(%$fullname))) {
1.324     albertel 4002: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4003: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4004:     }
1.474     albertel 4005:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4006:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4007:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4008: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4009:     if ($ctr == 0) {
1.442     banghart 4010:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4011:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4012:                 '<span class="LC_warning">';
                   4013:         if ($env{'form.submitonly'} eq 'all') {
                   4014:             if (grep(/^all$/,@sections)) {
                   4015:                 if (grep(/^all$/,@groups)) {
                   4016:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4017:                                    $stu_status);
                   4018:                 } elsif (grep(/^none$/,@groups)) {
                   4019:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4020:                                    $stu_status); 
                   4021:                 } else {
                   4022:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4023:                                    $group_display,$stu_status);
                   4024:                 }
                   4025:             } elsif (grep(/^none$/,@sections)) {
                   4026:                 if (grep(/^all$/,@groups)) {
                   4027:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4028:                                    $stu_status);
                   4029:                 } elsif (grep(/^none$/,@groups)) {
                   4030:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4031:                                    $stu_status);
                   4032:                 } else {
                   4033:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4034:                                    $group_display,$stu_status);
                   4035:                 }
                   4036:             } else {
                   4037:                 if (grep(/^all$/,@groups)) {
                   4038:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4039:                                    $section_display,$stu_status);
                   4040:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4041:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4042:                                    $section_display,$stu_status);
                   4043:                 } else {
                   4044:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4045:                                    $section_display,$group_display,$stu_status);
                   4046:                 }
                   4047:             }
                   4048:         } else {
                   4049:             if (grep(/^all$/,@sections)) {
                   4050:                 if (grep(/^all$/,@groups)) {
                   4051:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4052:                                    $stu_status,$submission_status);
                   4053:                 } elsif (grep(/^none$/,@groups)) {
                   4054:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4055:                                    $stu_status,$submission_status);
                   4056:                 } else {
                   4057:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4058:                                    $group_display,$stu_status,$submission_status);
                   4059:                 }
                   4060:             } elsif (grep(/^none$/,@sections)) {
                   4061:                 if (grep(/^all$/,@groups)) {
                   4062:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4063:                                    $stu_status,$submission_status);
                   4064:                 } elsif (grep(/^none$/,@groups)) {
                   4065:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4066:                                    $stu_status,$submission_status);
                   4067:                 } else {
                   4068:                     $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.',
                   4069:                                    $group_display,$stu_status,$submission_status);
                   4070:                 }
                   4071:             } else {
                   4072:                 if (grep(/^all$/,@groups)) {
                   4073: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4074: 	                           $section_display,$stu_status,$submission_status);
                   4075:                 } elsif (grep(/^none$/,@groups)) {
                   4076:                     $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.',
                   4077:                                    $section_display,$stu_status,$submission_status);
                   4078:                 } else {
                   4079:                     $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.',
                   4080:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4081:                 }
                   4082:             }
                   4083:         }
                   4084: 	$result .= '</span><br />';
1.96      albertel 4085:     }
1.41      ng       4086:     return $result;
                   4087: }
                   4088: 
1.738     raeburn  4089: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4090: sub viewstudentgrade {
1.745     raeburn  4091:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4092:     my ($uname,$udom) = split(/:/,$student);
                   4093:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4094:     my $submitonly = $env{'form.submitonly'};
                   4095:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4096:         my %partstatus = ();
                   4097:         if (ref($parts) eq 'ARRAY') {
                   4098:             foreach my $apart (@{$parts}) {
                   4099:                 my ($part,$type) = &split_part_type($apart);
                   4100:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4101:                 $status = 'nothing' if ($status eq '');
                   4102:                 $partstatus{$part}      = $status;
                   4103:                 my $subkey = "resource.$part.submitted_by";
                   4104:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4105:             }
                   4106:             my $submitted = 0;
                   4107:             my $graded = 0;
                   4108:             my $incorrect = 0;
                   4109:             foreach my $key (keys(%partstatus)) {
                   4110:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4111:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4112:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4113: 
                   4114:                 my $partid = (split(/\./,$key))[1];
                   4115:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4116:                     $submitted = 0;
                   4117:                 }
                   4118:             }
                   4119:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4120:                                        $submitonly eq 'incorrect' ||
                   4121:                                        $submitonly eq 'graded'));
                   4122:             return if (!$graded && ($submitonly eq 'graded'));
                   4123:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4124:         }
                   4125:     }
                   4126:     if ($submitonly eq 'queued') {
                   4127:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4128:         my %queue_status =
                   4129:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4130:                                                     $udom,$uname);
                   4131:         return if (!defined($queue_status{'gradingqueue'}));
                   4132:     }
                   4133:     $$ctr++;
                   4134:     my %aggregates = ();
1.474     albertel 4135:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4136: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4137: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4138: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4139: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4140: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4141:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4142:     foreach my $apart (@$parts) {
                   4143: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4144: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4145:         $result.='<td align="center">';
1.269     raeburn  4146:         my ($aggtries,$totaltries);
                   4147:         unless (exists($aggregates{$part})) {
1.270     albertel 4148: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4149: 	    $aggtries = $totaltries;
1.269     raeburn  4150:             if ($$last_resets{$part}) {  
1.270     albertel 4151:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4152: 					   $part);
                   4153:             }
1.269     raeburn  4154:             $result.='<input type="hidden" name="'.
                   4155:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4156:             $result.='<input type="hidden" name="'.
                   4157:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4158:             $aggregates{$part} = 1;
                   4159:         }
1.41      ng       4160: 	if ($type eq 'awarded') {
1.320     albertel 4161: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4162: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4163: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4164: 	    $result.='<input type="text" name="'.
1.89      albertel 4165: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4166:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4167: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4168: 	} elsif ($type eq 'solved') {
                   4169: 	    my ($status,$foo)=split(/_/,$score,2);
                   4170: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4171: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4172: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4173: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4174: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4175:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4176: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4177: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4178: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4179: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4180: 	} else {
                   4181: 	    $result.='<input type="hidden" name="'.
                   4182: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4183: 		    "\n";
1.233     albertel 4184: 	    $result.='<input type="text" name="'.
1.122     ng       4185: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4186: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4187: 	}
                   4188:     }
1.474     albertel 4189:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4190:     return $result;
1.38      ng       4191: }
                   4192: 
1.44      ng       4193: #--- change scores for all the students in a section/class
                   4194: #    record does not get update if unchanged
1.38      ng       4195: sub editgrades {
1.608     www      4196:     my ($request,$symb) = @_;
1.745     raeburn  4197:     my $toolsymb;
                   4198:     if ($symb =~ /ext\.tool$/) {
                   4199:         $toolsymb = $symb;
                   4200:     }
1.41      ng       4201: 
1.433     banghart 4202:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4203:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4204:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4205: 
1.477     albertel 4206:     my $result= &Apache::loncommon::start_data_table().
                   4207: 	&Apache::loncommon::start_data_table_header_row().
                   4208: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4209: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4210:     my %scoreptr = (
                   4211: 		    'correct'  =>'correct_by_override',
                   4212: 		    'incorrect'=>'incorrect_by_override',
                   4213: 		    'excused'  =>'excused',
                   4214: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4215:                     'credited' =>'credit_attempted',
1.43      ng       4216: 		    'nothing'  => '',
                   4217: 		    );
1.257     albertel 4218:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4219: 
1.44      ng       4220:     my (@partid);
                   4221:     my %weight = ();
1.54      albertel 4222:     my %columns = ();
1.44      ng       4223:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4224: 
1.582     raeburn  4225:     my $partserror;
                   4226:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4227:     if ($partserror) {
                   4228:         return &navmap_errormsg();
                   4229:     }
1.54      albertel 4230:     my $header;
1.257     albertel 4231:     while ($ctr < $env{'form.totalparts'}) {
                   4232: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4233: 	push(@partid,$partid);
1.257     albertel 4234: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4235: 	$ctr++;
1.54      albertel 4236:     }
1.324     albertel 4237:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4238:     my $totcolspan = 0;
1.54      albertel 4239:     foreach my $partid (@partid) {
1.478     albertel 4240: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4241: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4242: 	$columns{$partid}=2;
                   4243: 	foreach my $stores (@parts) {
                   4244: 	    my ($part,$type) = &split_part_type($stores);
                   4245: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4246: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4247: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4248: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4249:             my $narrowtext = &mt('Tries');
                   4250: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4251: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4252: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4253: 	    $columns{$partid}+=2;
                   4254: 	}
1.748     raeburn  4255:         $totcolspan += $columns{$partid};
1.54      albertel 4256:     }
                   4257:     foreach my $partid (@partid) {
1.324     albertel 4258: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4259: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4260: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4261: 	    '</th>';
1.54      albertel 4262: 
1.44      ng       4263:     }
1.477     albertel 4264:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4265: 	&Apache::loncommon::start_data_table_header_row().
                   4266: 	$header.
                   4267: 	&Apache::loncommon::end_data_table_header_row();
                   4268:     my @noupdate;
1.126     ng       4269:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4270:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4271: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4272: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4273: 	my %newrecord;
                   4274: 	my $updateflag = 0;
1.108     albertel 4275: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4276: 	my $canmodify = &canmodify($usec);
                   4277: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4278: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4279: 	if (!$canmodify) {
1.477     albertel 4280: 	    push(@noupdate,
1.748     raeburn  4281: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4282: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4283: 	    next;
                   4284: 	}
1.269     raeburn  4285:         my %aggregate = ();
                   4286:         my $aggregateflag = 0;
1.281     albertel 4287: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4288: 	foreach (@partid) {
1.257     albertel 4289: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4290: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4291: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4292: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4293: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4294: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4295: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4296: 	    my $score;
                   4297: 	    if ($partial eq '') {
1.257     albertel 4298: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4299: 	    } elsif ($partial > 0) {
                   4300: 		$score = 'correct_by_override';
                   4301: 	    } elsif ($partial == 0) {
                   4302: 		$score = 'incorrect_by_override';
                   4303: 	    }
1.257     albertel 4304: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4305: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4306: 
1.292     albertel 4307: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4308: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4309: 	    if ($dropMenu eq 'reset status' &&
                   4310: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4311: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4312: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4313: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4314: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4315: 		$updateflag = 1;
1.269     raeburn  4316:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4317:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4318:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4319:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4320:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4321:                     $aggregateflag = 1;
                   4322:                 }
1.139     albertel 4323: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4324: 		$updateflag = 1;
                   4325: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4326: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4327: 		$rec_update++;
1.125     ng       4328: 	    }
                   4329: 
1.93      albertel 4330: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4331: 		'<td align="center">'.$awarded.
                   4332: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4333: 
1.54      albertel 4334: 
                   4335: 	    my $partid=$_;
                   4336: 	    foreach my $stores (@parts) {
                   4337: 		my ($part,$type) = &split_part_type($stores);
                   4338: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4339: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4340: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4341: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4342: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4343: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4344: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4345: 		    $updateflag=1;
                   4346: 		}
1.93      albertel 4347: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4348: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4349: 	    }
1.44      ng       4350: 	}
1.477     albertel 4351: 	$line.="\n";
1.301     albertel 4352: 
                   4353: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4354: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4355: 
1.44      ng       4356: 	if ($updateflag) {
                   4357: 	    $count++;
1.257     albertel 4358: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4359: 				    $udom,$uname);
1.301     albertel 4360: 
                   4361: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4362: 					      $cnum,$udom,$uname)) {
                   4363: 		# need to figure out if should be in queue.
                   4364: 		my %record =  
                   4365: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4366: 					     $udom,$uname);
                   4367: 		my $all_graded = 1;
                   4368: 		my $none_graded = 1;
                   4369: 		foreach my $part (@parts) {
                   4370: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4371: 			$all_graded = 0;
                   4372: 		    } else {
                   4373: 			$none_graded = 0;
                   4374: 		    }
                   4375: 		}
                   4376: 
                   4377: 		if ($all_graded || $none_graded) {
                   4378: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4379: 							   $symb,$cdom,$cnum,
                   4380: 							   $udom,$uname);
                   4381: 		}
                   4382: 	    }
                   4383: 
1.477     albertel 4384: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4385: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4386: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4387: 	    $updateCtr++;
1.93      albertel 4388: 	} else {
1.477     albertel 4389: 	    push(@noupdate,
                   4390: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4391: 	    $noupdateCtr++;
1.44      ng       4392: 	}
1.269     raeburn  4393:         if ($aggregateflag) {
                   4394:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4395: 				  $cdom,$cnum);
1.269     raeburn  4396:         }
1.93      albertel 4397:     }
1.477     albertel 4398:     if (@noupdate) {
1.748     raeburn  4399:         my $numcols=$totcolspan+2;
1.477     albertel 4400: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4401: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4402: 	    &mt('No Changes Occurred For the Students Below').
                   4403: 	    '</td>'.
1.477     albertel 4404: 	    &Apache::loncommon::end_data_table_row();
                   4405: 	foreach my $line (@noupdate) {
                   4406: 	    $result.=
                   4407: 		&Apache::loncommon::start_data_table_row().
                   4408: 		$line.
                   4409: 		&Apache::loncommon::end_data_table_row();
                   4410: 	}
1.44      ng       4411:     }
1.614     www      4412:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4413:     my $msg = '<p><b>'.
                   4414: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4415: 	    $rec_update,$count).'</b><br />'.
                   4416: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4417: 	'</b></p>';
1.44      ng       4418:     return $title.$msg.$result;
1.5       albertel 4419: }
1.54      albertel 4420: 
                   4421: sub split_part_type {
                   4422:     my ($partstr) = @_;
                   4423:     my ($temp,@allparts)=split(/_/,$partstr);
                   4424:     my $type=pop(@allparts);
1.439     albertel 4425:     my $part=join('_',@allparts);
1.54      albertel 4426:     return ($part,$type);
                   4427: }
                   4428: 
1.44      ng       4429: #------------- end of section for handling grading by section/class ---------
                   4430: #
                   4431: #----------------------------------------------------------------------------
                   4432: 
1.5       albertel 4433: 
1.44      ng       4434: #----------------------------------------------------------------------------
                   4435: #
                   4436: #-------------------------- Next few routines handles grading by csv upload
                   4437: #
                   4438: #--- Javascript to handle csv upload
1.27      albertel 4439: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4440:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4441:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4442:   &js_escape(\$error1);
                   4443:   &js_escape(\$error2);
1.27      albertel 4444:   return(<<ENDPICK);
                   4445:   function verify(vf) {
                   4446:     var foundsomething=0;
                   4447:     var founduname=0;
1.243     albertel 4448:     var foundID=0;
1.743     raeburn  4449:     var foundclicker=0;
1.27      albertel 4450:     for (i=0;i<=vf.nfields.value;i++) {
                   4451:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4452:       if (i==0 && tw!=0) { foundID=1; }
                   4453:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4454:       if (i==2 && tw!=0) { foundclicker=1; }
                   4455:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4456:     }
1.743     raeburn  4457:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4458: 	alert('$error1');
                   4459: 	return;
1.27      albertel 4460:     }
                   4461:     if (foundsomething==0) {
1.246     albertel 4462: 	alert('$error2');
                   4463: 	return;
1.27      albertel 4464:     }
                   4465:     vf.submit();
                   4466:   }
                   4467:   function flip(vf,tf) {
                   4468:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4469:     var i;
                   4470:     for (i=0;i<=vf.nfields.value;i++) {
                   4471:       //can not pick the same destination field for both name and domain
                   4472:       if (((i ==0)||(i ==1)) && 
                   4473:           ((tf==0)||(tf==1)) && 
                   4474:           (i!=tf) &&
                   4475:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4476:         eval('vf.f'+i+'.selectedIndex=0;')
                   4477:       }
                   4478:     }
                   4479:   }
                   4480: ENDPICK
                   4481: }
                   4482: 
                   4483: sub csvupload_javascript_forward_associate {
1.743     raeburn  4484:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4485:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4486:   &js_escape(\$error1);
                   4487:   &js_escape(\$error2);
1.27      albertel 4488:   return(<<ENDPICK);
                   4489:   function verify(vf) {
                   4490:     var foundsomething=0;
                   4491:     var founduname=0;
1.243     albertel 4492:     var foundID=0;
1.743     raeburn  4493:     var foundclicker=0;
1.27      albertel 4494:     for (i=0;i<=vf.nfields.value;i++) {
                   4495:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4496:       if (tw==1) { foundID=1; }
                   4497:       if (tw==2) { founduname=1; }
1.745     raeburn  4498:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4499:       if (tw>4) { foundsomething=1; }
1.27      albertel 4500:     }
1.743     raeburn  4501:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4502: 	alert('$error1');
                   4503: 	return;
1.27      albertel 4504:     }
                   4505:     if (foundsomething==0) {
1.246     albertel 4506: 	alert('$error2');
                   4507: 	return;
1.27      albertel 4508:     }
                   4509:     vf.submit();
                   4510:   }
                   4511:   function flip(vf,tf) {
                   4512:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4513:     var i;
                   4514:     //can not pick the same destination field twice
                   4515:     for (i=0;i<=vf.nfields.value;i++) {
                   4516:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4517:         eval('vf.f'+i+'.selectedIndex=0;')
                   4518:       }
                   4519:     }
                   4520:   }
                   4521: ENDPICK
                   4522: }
                   4523: 
1.26      albertel 4524: sub csvuploadmap_header {
1.324     albertel 4525:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4526:     my $javascript;
1.257     albertel 4527:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4528: 	$javascript=&csvupload_javascript_reverse_associate();
                   4529:     } else {
                   4530: 	$javascript=&csvupload_javascript_forward_associate();
                   4531:     }
1.45      ng       4532: 
1.418     albertel 4533:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4534:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4535:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4536:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4537:     my $reverse=&mt("Reverse Association");
1.41      ng       4538:     $request->print(<<ENDPICK);
1.632     www      4539: <br />
                   4540: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4541: <input type="hidden" name="associate"  value="" />
                   4542: <input type="hidden" name="phase"      value="three" />
                   4543: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4544: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4545: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4546: <input type="hidden" name="upfile_associate" 
1.257     albertel 4547:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4548: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4549: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4550: <hr />
                   4551: ENDPICK
1.597     wenzelju 4552:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4553:     return '';
1.26      albertel 4554: 
                   4555: }
                   4556: 
                   4557: sub csvupload_fields {
1.582     raeburn  4558:     my ($symb,$errorref) = @_;
1.745     raeburn  4559:     my $toolsymb;
                   4560:     if ($symb =~ /ext\.tool$/) {
                   4561:         $toolsymb = $symb;
                   4562:     }
1.582     raeburn  4563:     my (@parts) = &getpartlist($symb,$errorref);
                   4564:     if (ref($errorref)) {
                   4565:         if ($$errorref) {
                   4566:             return;
                   4567:         }
                   4568:     }
                   4569: 
1.556     weissno  4570:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4571: 		['username','Student Username'],
1.743     raeburn  4572: 		['clicker','Clicker ID'],
1.243     albertel 4573: 		['domain','Student Domain']);
1.324     albertel 4574:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4575:     foreach my $part (sort(@parts)) {
                   4576: 	my @datum;
1.745     raeburn  4577: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4578: 	my $name=$part;
1.745     raeburn  4579: 	if (!$display) { $display = $name; }
1.41      ng       4580: 	@datum=($name,$display);
1.244     albertel 4581: 	if ($name=~/^stores_(.*)_awarded/) {
                   4582: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4583: 	}
1.41      ng       4584: 	push(@fields,\@datum);
                   4585:     }
                   4586:     return (@fields);
1.26      albertel 4587: }
                   4588: 
                   4589: sub csvuploadmap_footer {
1.41      ng       4590:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4591:     my $buttontext = &mt('Assign Grades');
1.41      ng       4592:     $request->print(<<ENDPICK);
1.26      albertel 4593: </table>
                   4594: <input type="hidden" name="nfields" value="$i" />
                   4595: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4596: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4597: </form>
                   4598: ENDPICK
                   4599: }
                   4600: 
1.283     albertel 4601: sub checkforfile_js {
1.638     www      4602:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4603:     &js_escape(\$alertmsg);
1.597     wenzelju 4604:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4605:     function checkUpload(formname) {
                   4606: 	if (formname.upfile.value == "") {
1.539     riegler  4607: 	    alert("$alertmsg");
1.86      ng       4608: 	    return false;
                   4609: 	}
                   4610: 	formname.submit();
                   4611:     }
                   4612: CSVFORMJS
1.283     albertel 4613:     return $result;
                   4614: }
                   4615: 
                   4616: sub upcsvScores_form {
1.608     www      4617:     my ($request,$symb) = @_;
1.283     albertel 4618:     if (!$symb) {return '';}
                   4619:     my $result=&checkforfile_js();
1.632     www      4620:     $result.=&Apache::loncommon::start_data_table().
                   4621:              &Apache::loncommon::start_data_table_header_row().
                   4622:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4623:              &Apache::loncommon::end_data_table_header_row().
                   4624:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4625:     my $upload=&mt("Upload Scores");
1.86      ng       4626:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4627:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4628:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4629:     $result.=<<ENDUPFORM;
1.106     albertel 4630: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4631: <input type="hidden" name="symb" value="$symb" />
                   4632: <input type="hidden" name="command" value="csvuploadmap" />
                   4633: $upfile_select
1.589     bisitz   4634: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4635: </form>
                   4636: ENDUPFORM
1.370     www      4637:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4638:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4639:              '</td>'.
                   4640:             &Apache::loncommon::end_data_table_row().
                   4641:             &Apache::loncommon::end_data_table();
1.86      ng       4642:     return $result;
                   4643: }
                   4644: 
                   4645: 
1.26      albertel 4646: sub csvuploadmap {
1.768     raeburn  4647:     my ($request,$symb) = @_;
1.41      ng       4648:     if (!$symb) {return '';}
1.72      ng       4649: 
1.41      ng       4650:     my $datatoken;
1.257     albertel 4651:     if (!$env{'form.datatoken'}) {
1.41      ng       4652: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4653:     } else {
1.742     raeburn  4654: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4655:         if ($datatoken ne '') {
                   4656: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4657:         }
1.26      albertel 4658:     }
1.41      ng       4659:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4660:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4661:     my ($i,$keyfields);
                   4662:     if (@records) {
1.582     raeburn  4663:         my $fieldserror;
                   4664: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4665:         if ($fieldserror) {
                   4666:             $request->print(&navmap_errormsg());
                   4667:             return;
                   4668:         }
1.257     albertel 4669: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4670: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4671: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4672: 							  \@fields);
                   4673: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4674: 	    chop($keyfields);
                   4675: 	} else {
                   4676: 	    unshift(@fields,['none','']);
                   4677: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4678: 							    \@fields);
1.311     banghart 4679:             foreach my $rec (@records) {
                   4680:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4681:                 if (%temp) {
                   4682:                     $keyfields=join(',',sort(keys(%temp)));
                   4683:                     last;
                   4684:                 }
                   4685:             }
1.41      ng       4686: 	}
                   4687:     }
                   4688:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4689: 
1.41      ng       4690:     return '';
1.27      albertel 4691: }
                   4692: 
1.246     albertel 4693: sub csvuploadoptions {
1.608     www      4694:     my ($request,$symb)= @_;
1.632     www      4695:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4696:     $request->print(<<ENDPICK);
                   4697: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4698: <input type="hidden" name="command"    value="csvuploadassign" />
                   4699: <p>
                   4700: <label>
                   4701:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4702:    $overwrite
1.246     albertel 4703: </label>
                   4704: </p>
                   4705: ENDPICK
                   4706:     my %fields=&get_fields();
                   4707:     if (!defined($fields{'domain'})) {
1.257     albertel 4708: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4709: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4710:     }
1.257     albertel 4711:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4712: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4713: 	my $cleankey=$1;
                   4714: 	if ($cleankey eq 'command') { next; }
                   4715: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4716: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4717:     }
                   4718:     # FIXME do a check for any duplicated user ids...
                   4719:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4720:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4721: <hr /></form>'."\n");
1.246     albertel 4722:     return '';
                   4723: }
                   4724: 
                   4725: sub get_fields {
                   4726:     my %fields;
1.257     albertel 4727:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4728:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4729: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4730: 	    if ($env{'form.f'.$i} ne 'none') {
                   4731: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4732: 	    }
                   4733: 	} else {
1.257     albertel 4734: 	    if ($env{'form.f'.$i} ne 'none') {
                   4735: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4736: 	    }
                   4737: 	}
1.27      albertel 4738:     }
1.246     albertel 4739:     return %fields;
                   4740: }
                   4741: 
                   4742: sub csvuploadassign {
1.766     raeburn  4743:     my ($request,$symb) = @_;
1.246     albertel 4744:     if (!$symb) {return '';}
1.345     bowersj2 4745:     my $error_msg = '';
1.742     raeburn  4746:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4747:     if ($datatoken ne '') { 
                   4748:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4749:     }
1.246     albertel 4750:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4751:     my %fields=&get_fields();
1.257     albertel 4752:     my $courseid=$env{'request.course.id'};
1.97      albertel 4753:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4754:     my @notallowed;
1.41      ng       4755:     my @skipped;
1.657     raeburn  4756:     my @warnings;
1.41      ng       4757:     my $countdone=0;
                   4758:     foreach my $grade (@gradedata) {
                   4759: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4760: 	my $domain;
                   4761: 	if ($entries{$fields{'domain'}}) {
                   4762: 	    $domain=$entries{$fields{'domain'}};
                   4763: 	} else {
1.257     albertel 4764: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4765: 	}
1.243     albertel 4766: 	$domain=~s/\s//g;
1.41      ng       4767: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4768: 	$username=~s/\s//g;
1.243     albertel 4769: 	if (!$username) {
                   4770: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4771: 	    $id=~s/\s//g;
1.737     raeburn  4772:             if ($id ne '') {
                   4773: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4774: 	        $username=$ids{$id};
                   4775:             } else {
                   4776:                 if ($entries{$fields{'clicker'}}) {
                   4777:                     my $clicker = $entries{$fields{'clicker'}};
                   4778:                     $clicker=~s/\s//g;
                   4779:                     if ($clicker ne '') {
                   4780:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4781:                         if ($clickers{$clicker} ne '') {  
                   4782:                             my $match = 0;
                   4783:                             my @inclass;
                   4784:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4785:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4786:                                     $username = $poss;
                   4787:                                     push(@inclass,$poss);
                   4788:                                     $match ++;
                   4789:                                     
                   4790:                                 }
                   4791:                             }
                   4792:                             if ($match > 1) {
                   4793:                                 undef($username); 
                   4794:                                 $request->print('<p class="LC_warning">'.
                   4795:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4796:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4797:                             }
                   4798:                         }
                   4799:                     }
                   4800:                 }
                   4801:             }
1.243     albertel 4802: 	}
1.41      ng       4803: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4804: 	    my $id=$entries{$fields{'ID'}};
                   4805: 	    $id=~s/\s//g;
1.737     raeburn  4806:             my $clicker = $entries{$fields{'clicker'}};
                   4807:             $clicker=~s/\s//g;
                   4808:             if ($clicker) {
                   4809:                 push(@skipped,"$clicker:$domain");
                   4810: 	    } elsif ($id) {
1.247     albertel 4811: 		push(@skipped,"$id:$domain");
                   4812: 	    } else {
                   4813: 		push(@skipped,"$username:$domain");
                   4814: 	    }
1.41      ng       4815: 	    next;
                   4816: 	}
1.108     albertel 4817: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4818: 	if (!&canmodify($usec)) {
                   4819: 	    push(@notallowed,"$username:$domain");
                   4820: 	    next;
                   4821: 	}
1.244     albertel 4822: 	my %points;
1.41      ng       4823: 	my %grades;
                   4824: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4825: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4826: 		$dest eq 'domain') { next; }
                   4827: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4828: 	    if ($dest=~/stores_(.*)_points/) {
                   4829: 		my $part=$1;
                   4830: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4831: 					      $symb,$domain,$username);
1.345     bowersj2 4832:                 if ($wgt) {
                   4833:                     $entries{$fields{$dest}}=~s/\s//g;
                   4834:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4835:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4836:                                           : 'correct_by_override';
1.638     www      4837:                     if ($pcr>1) {
1.657     raeburn  4838:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4839:                     }
1.345     bowersj2 4840:                     $grades{"resource.$part.awarded"}=$pcr;
                   4841:                     $grades{"resource.$part.solved"}=$award;
                   4842:                     $points{$part}=1;
                   4843:                 } else {
                   4844:                     $error_msg = "<br />" .
                   4845:                         &mt("Some point values were assigned"
                   4846:                             ." for problems with a weight "
                   4847:                             ."of zero. These values were "
                   4848:                             ."ignored.");
                   4849:                 }
1.244     albertel 4850: 	    } else {
                   4851: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4852: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4853: 		my $store_key=$dest;
                   4854: 		$store_key=~s/^stores/resource/;
                   4855: 		$store_key=~s/_/\./g;
                   4856: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4857: 	    }
1.41      ng       4858: 	}
1.766     raeburn  4859: 	if (! %grades) {
1.508     www      4860:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4861:         } else {
                   4862: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4863: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4864: 					   $env{'request.course.id'},
                   4865: 					   $domain,$username);
1.508     www      4866: 	   if ($result eq 'ok') {
1.627     www      4867: # Successfully stored
1.508     www      4868: 	      $request->print('.');
1.627     www      4869: # Remove from grading queue
                   4870:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4871:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4872:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4873:                                              $domain,$username);
                   4874:               $countdone++;
                   4875:            } else {
1.508     www      4876: 	      $request->print("<p><span class=\"LC_error\">".
                   4877:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4878:                                   "$username:$domain",$result)."</span></p>");
                   4879: 	   }
                   4880: 	   $request->rflush();
                   4881:         }
1.41      ng       4882:     }
1.570     www      4883:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4884:     if (@warnings) {
                   4885:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4886:         $request->print(join(', ',@warnings));
                   4887:     }
1.41      ng       4888:     if (@skipped) {
1.571     www      4889: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4890:         $request->print(join(', ',@skipped));
1.106     albertel 4891:     }
                   4892:     if (@notallowed) {
1.571     www      4893: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4894: 	$request->print(join(', ',@notallowed));
1.41      ng       4895:     }
1.106     albertel 4896:     $request->print("<br />\n");
1.345     bowersj2 4897:     return $error_msg;
1.26      albertel 4898: }
1.44      ng       4899: #------------- end of section for handling csv file upload ---------
                   4900: #
                   4901: #-------------------------------------------------------------------
                   4902: #
1.122     ng       4903: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4904: #
                   4905: #--- Select a page/sequence and a student to grade
1.68      ng       4906: sub pickStudentPage {
1.608     www      4907:     my ($request,$symb) = @_;
1.68      ng       4908: 
1.539     riegler  4909:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4910:     &js_escape(\$alertmsg);
1.597     wenzelju 4911:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4912: 
                   4913: function checkPickOne(formname) {
1.76      ng       4914:     if (radioSelection(formname.student) == null) {
1.539     riegler  4915: 	alert("$alertmsg");
1.68      ng       4916: 	return;
                   4917:     }
1.125     ng       4918:     ptr = pullDownSelection(formname.selectpage);
                   4919:     formname.page.value = formname["page"+ptr].value;
                   4920:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4921:     formname.submit();
                   4922: }
                   4923: 
                   4924: LISTJAVASCRIPT
1.118     ng       4925:     &commonJSfunctions($request);
1.608     www      4926: 
1.257     albertel 4927:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4928:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4929:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  4930:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       4931: 
1.398     albertel 4932:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4933: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4934: 
1.80      ng       4935:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4936:     my $map_error;
                   4937:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4938:     if ($map_error) {
                   4939:         $request->print(&navmap_errormsg());
                   4940:         return; 
                   4941:     }
1.137     albertel 4942:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4943: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4944: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4945: 
                   4946:     # Collection of hidden fields
1.70      ng       4947:     my $ctr=0;
1.68      ng       4948:     foreach (@$titles) {
1.700     bisitz   4949:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4950:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4951:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4952:         $ctr++;
1.68      ng       4953:     }
1.700     bisitz   4954:     $result.='<input type="hidden" name="page" />'."\n".
                   4955:         '<input type="hidden" name="title" />'."\n";
                   4956: 
                   4957:     $result.=&build_section_inputs();
                   4958:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4959:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4960: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4961: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4962: 
1.700     bisitz   4963:     # Show grading options
                   4964:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4965:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4966:     $ctr=0;
                   4967:     foreach (@$titles) {
                   4968: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4969: 	$select.='<option value="'.$ctr.'"'.
                   4970: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4971: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4972: 	$ctr++;
                   4973:     }
1.700     bisitz   4974:     $select.= '</select>';
1.68      ng       4975: 
1.700     bisitz   4976:     $result.=
                   4977:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4978:        .$select
                   4979:        .&Apache::lonhtmlcommon::row_closure();
                   4980: 
                   4981:     $result.=
                   4982:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4983:        .'<label><input type="radio" name="vProb" value="no"'
                   4984:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4985:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4986:            .&mt('yes').'</label>'."\n"
                   4987:        .&Apache::lonhtmlcommon::row_closure();
                   4988: 
                   4989:     $result.=
                   4990:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4991:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4992:            .&mt('none').' </label>'."\n"
                   4993:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4994:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4995:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4996:            .&mt('all submissions with details').' </label>'
                   4997:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4998:     
1.700     bisitz   4999:     $result.=
                   5000:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5001:        .'<input type="text" name="CODE" value="" />'
                   5002:        .&Apache::lonhtmlcommon::row_closure(1)
                   5003:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5004: 
1.700     bisitz   5005:     # Show list of students to select for grading
                   5006:     $result.='<br /><input type="button" '.
1.589     bisitz   5007:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5008: 
1.68      ng       5009:     $request->print($result);
                   5010: 
1.485     albertel 5011:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5012: 	&Apache::loncommon::start_data_table().
                   5013: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5014: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5015: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5016: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5017: 	'<th>'.&nameUserString('header').'</th>'.
                   5018: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5019:  
1.761     raeburn  5020:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5021:     my $ptr = 1;
1.294     albertel 5022:     foreach my $student (sort 
                   5023: 			 {
                   5024: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5025: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5026: 			     }
                   5027: 			     return $a cmp $b;
                   5028: 			 } (keys(%$fullname))) {
1.68      ng       5029: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5030: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5031:                                   : '</td>');
1.126     ng       5032: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5033: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5034: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5035: 	$studentTable.=
                   5036: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5037:                          : '');
1.68      ng       5038: 	$ptr++;
                   5039:     }
1.484     albertel 5040:     if ($ptr%2 == 0) {
                   5041: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5042: 	    &Apache::loncommon::end_data_table_row();
                   5043:     }
                   5044:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5045:     $studentTable.='<input type="button" '.
1.589     bisitz   5046:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5047: 
                   5048:     $request->print($studentTable);
                   5049: 
                   5050:     return '';
                   5051: }
                   5052: 
                   5053: sub getSymbMap {
1.582     raeburn  5054:     my ($map_error) = @_;
1.132     bowersj2 5055:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5056:     unless (ref($navmap)) {
                   5057:         if (ref($map_error)) {
                   5058:             $$map_error = 'navmap';
                   5059:         }
                   5060:         return;
                   5061:     }
1.68      ng       5062:     my %symbx = ();
                   5063:     my @titles = ();
1.117     bowersj2 5064:     my $minder = 0;
                   5065: 
                   5066:     # Gather every sequence that has problems.
1.240     albertel 5067:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5068: 					       1,0,1);
1.117     bowersj2 5069:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5070: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5071: 	    my $title = $minder.'.'.
                   5072: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5073: 	    push(@titles, $title); # minder in case two titles are identical
                   5074: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5075: 	    $minder++;
1.241     albertel 5076: 	}
1.68      ng       5077:     }
                   5078:     return \@titles,\%symbx;
                   5079: }
                   5080: 
1.72      ng       5081: #
                   5082: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5083: sub displayPage {
1.608     www      5084:     my ($request,$symb) = @_;
1.257     albertel 5085:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5086:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5087:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5088:     my $pageTitle = $env{'form.page'};
1.103     albertel 5089:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5090:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5091:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5092: 
                   5093:     #need to make sure we have the correct data for later EXT calls, 
                   5094:     #thus invalidate the cache
                   5095:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5096:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5097:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5098:     &Apache::lonnet::clear_EXT_cache_status();
                   5099: 
1.103     albertel 5100:     if (!&canview($usec)) {
1.712     bisitz   5101:         $request->print(
                   5102:             '<span class="LC_warning">'.
                   5103:             &mt('Unable to view requested student. ([_1])',
                   5104:                     $env{'form.student'}).
                   5105:             '</span>');
                   5106:         return;
1.103     albertel 5107:     }
1.398     albertel 5108:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5109:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5110: 	'</h3>'."\n";
1.500     albertel 5111:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5112:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5113: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5114:     } else {
                   5115: 	delete($env{'form.CODE'});
                   5116:     }
1.71      ng       5117:     &sub_page_js($request);
                   5118:     $request->print($result);
                   5119: 
1.132     bowersj2 5120:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5121:     unless (ref($navmap)) {
                   5122:         $request->print(&navmap_errormsg());
                   5123:         return;
                   5124:     }
1.257     albertel 5125:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5126:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5127:     if (!$map) {
1.485     albertel 5128: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5129: 	return; 
                   5130:     }
1.68      ng       5131:     my $iterator = $navmap->getIterator($map->map_start(),
                   5132: 					$map->map_finish());
                   5133: 
1.71      ng       5134:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5135: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5136: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5137: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5138: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5139: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5140: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5141: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5142: 
1.382     albertel 5143:     if (defined($env{'form.CODE'})) {
                   5144: 	$studentTable.=
                   5145: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5146:     }
1.381     albertel 5147:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5148: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5149: 
1.594     bisitz   5150:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5151:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5152:         '</span>'."\n".
1.484     albertel 5153: 	&Apache::loncommon::start_data_table().
                   5154: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5155: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5156: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5157: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5158: 
1.329     albertel 5159:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5160:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5161:     $iterator->next(); # skip the first BEGIN_MAP
                   5162:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5163:     while ($depth > 0) {
1.68      ng       5164:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5165:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5166: 
1.745     raeburn  5167:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5168: 	    my $parts = $curRes->parts();
1.68      ng       5169:             my $title = $curRes->compTitle();
1.71      ng       5170: 	    my $symbx = $curRes->symb();
1.746     raeburn  5171:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5172: 	    $studentTable.=
                   5173: 		&Apache::loncommon::start_data_table_row().
                   5174: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5175: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5176: 		                        : '<br />('.&mt('[_1]parts',
                   5177: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5178: 		 ).
                   5179: 		 '</td>';
1.71      ng       5180: 	    $studentTable.='<td valign="top">';
1.382     albertel 5181: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5182:             if ($is_tool) {
                   5183:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5184:             } else {
1.745     raeburn  5185: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5186: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5187: 					         undef,'both',\%form);
                   5188: 	        } else {
                   5189: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5190: 		    $companswer =~ s|<form(.*?)>||g;
                   5191: 		    $companswer =~ s|</form>||g;
                   5192: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5193: #		        $companswer =~ s/$1/ /ms;
                   5194: #		        $request->print('match='.$1."<br />\n");
                   5195: #		    }
                   5196: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5197: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5198: 		}
1.71      ng       5199: 	    }
                   5200: 
1.257     albertel 5201: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5202: 
1.257     albertel 5203: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5204: 		if ($record{'version'} eq '') {
1.745     raeburn  5205:                     my $msg = &mt('No recorded submission for this problem.');
                   5206:                     if ($is_tool) {
                   5207:                         $msg = &mt('No recorded transactions for this external tool');
                   5208:                     }
                   5209: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5210: 		} else {
1.116     ng       5211: 		    my %responseType = ();
                   5212: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5213: 			my @responseIds =$curRes->responseIds($partid);
                   5214: 			my @responseType =$curRes->responseType($partid);
                   5215: 			my %responseIds;
                   5216: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5217: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5218: 			}
                   5219: 			$responseType{$partid} = \%responseIds;
1.116     ng       5220: 		    }
1.148     albertel 5221: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5222: 		}
1.257     albertel 5223: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5224: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5225:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5226: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5227: 									$env{'request.course.id'},
1.726     raeburn  5228: 									'','.submission',undef,
                   5229:                                                                         $usec,$identifier);
1.71      ng       5230:  
                   5231: 	    }
1.103     albertel 5232: 	    if (&canmodify($usec)) {
1.585     bisitz   5233:             $studentTable.=&gradeBox_start();
1.103     albertel 5234: 		foreach my $partid (@{$parts}) {
                   5235: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5236: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5237: 		    $question++;
                   5238: 		}
1.585     bisitz   5239:             $studentTable.=&gradeBox_end();
1.196     albertel 5240: 		$prob++;
1.71      ng       5241: 	    }
                   5242: 	    $studentTable.='</td></tr>';
1.68      ng       5243: 
1.103     albertel 5244: 	}
1.68      ng       5245:         $curRes = $iterator->next();
                   5246:     }
                   5247: 
1.589     bisitz   5248:     $studentTable.=
                   5249:         '</table>'."\n".
                   5250:         '<input type="button" value="'.&mt('Save').'" '.
                   5251:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5252:         '</form>'."\n";
1.71      ng       5253:     $request->print($studentTable);
                   5254: 
                   5255:     return '';
1.119     ng       5256: }
                   5257: 
                   5258: sub displaySubByDates {
1.148     albertel 5259:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5260:     my $isCODE=0;
1.335     albertel 5261:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5262:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5263:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5264:     my $studentTable=&Apache::loncommon::start_data_table().
                   5265: 	&Apache::loncommon::start_data_table_header_row().
                   5266: 	'<th>'.&mt('Date/Time').'</th>'.
                   5267: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5268:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5269: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5270: 	'<th>'.&mt('Status').'</th>'.
                   5271: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5272:     my ($version);
                   5273:     my %mark;
1.148     albertel 5274:     my %orders;
1.119     ng       5275:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5276:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5277:         if ($is_tool) {
                   5278:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5279:         } else {
                   5280:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5281:         }
1.147     albertel 5282:     }
1.335     albertel 5283: 
                   5284:     my $interaction;
1.525     raeburn  5285:     my $no_increment = 1;
1.735     raeburn  5286:     my (%lastrndseed,%lasttype);
1.119     ng       5287:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5288: 	my $timestamp = 
                   5289: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5290: 	if (exists($$record{$version.':resource.0.version'})) {
                   5291: 	    $interaction = $$record{$version.':resource.0.version'};
                   5292: 	}
1.671     raeburn  5293:         if ($isTask && $env{'form.previousversion'}) {
                   5294:             next unless ($interaction == $env{'form.previousversion'});
                   5295:         }
1.335     albertel 5296: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5297: 		             : "$version:resource");
1.467     albertel 5298: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5299: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5300: 	if ($isCODE) {
                   5301: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5302: 	}
1.671     raeburn  5303:         if ($isTask) {
                   5304:             $studentTable.='<td>'.$interaction.'</td>';
                   5305:         }
1.119     ng       5306: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5307: 	my @displaySub = ();
                   5308: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5309:             my ($hidden,$type);
                   5310:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5311:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5312:                 $hidden = 1;
                   5313:             }
1.749     raeburn  5314:             my @matchKey;
                   5315:             if ($isTask) {
1.769     raeburn  5316:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5317:             } elsif ($is_tool) {
1.769     raeburn  5318:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5319:             } else {
1.769     raeburn  5320:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5321:             }
1.122     ng       5322: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5323: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5324: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5325: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5326: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5327:                     if ($is_tool) {
                   5328:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5329:                     } else {
1.749     raeburn  5330: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5331: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5332:                         $displaySub[0].='<span class="LC_nobreak">';
                   5333:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5334:                                        .' <span class="LC_internal_info">'
                   5335:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5336:                                        .'</span>'
                   5337:                                        .' <b>';
                   5338:                         if ($hidden) {
                   5339:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5340:                         } else {
                   5341:                             my ($trial,$rndseed,$newvariation);
                   5342:                             if ($type eq 'randomizetry') {
                   5343:                                 $trial = $$record{"$where.$partid.tries"};
                   5344:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5345:                             }
                   5346: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5347: 			        $displaySub[0].=&mt('Trial not counted');
                   5348: 		            } else {
                   5349: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5350: 					        $$record{"$where.$partid.tries"});
                   5351:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5352:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5353:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5354:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5355:                                     }
1.640     raeburn  5356:                                 }
1.749     raeburn  5357:                                 $lastrndseed{$partid} = $rndseed;
                   5358:                                 $lasttype{$partid} = $type;
                   5359: 		            }
                   5360: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5361:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5362: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5363: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5364: 			        $orders{$partid}->{$responseId}=
                   5365: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5366:                                                $no_increment,$type,$trial,$rndseed);
                   5367: 		            }
                   5368: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5369: 		            $displaySub[0].='&nbsp; '.
                   5370: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5371:                         }
1.596     raeburn  5372:                     }
1.147     albertel 5373: 		}
                   5374: 	    }
1.335     albertel 5375: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5376: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5377: 				    $$record{"$where.$partid.checkedin"},
                   5378: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5379: 					'<br />';
1.335     albertel 5380: 	    }
                   5381: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5382: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5383: 		    lc($$record{"$where.$partid.award"}).' '.
                   5384: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5385: 		    '<br />';
1.749     raeburn  5386: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5387: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5388: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5389: 		}
1.147     albertel 5390: 	    }
1.335     albertel 5391: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5392: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5393: 		unless ($is_tool) {
                   5394: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5395: 		}
1.335     albertel 5396: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5397: 		$displaySub[2].=
1.749     raeburn  5398: 		    $$record{"$version:resource.$partid.regrader"};
                   5399:                 unless ($is_tool) {
                   5400: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5401:                 }
1.147     albertel 5402: 	    }
                   5403: 	}
                   5404: 	# needed because old essay regrader has not parts info
                   5405: 	if (exists $$record{"$version:resource.regrader"}) {
                   5406: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5407: 	}
                   5408: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5409: 	if ($displaySub[2]) {
1.467     albertel 5410: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5411: 	}
1.467     albertel 5412: 	$studentTable.='&nbsp;</td>'.
                   5413: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5414:     }
1.467     albertel 5415:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5416:     return $studentTable;
1.71      ng       5417: }
                   5418: 
                   5419: sub updateGradeByPage {
1.608     www      5420:     my ($request,$symb) = @_;
1.71      ng       5421: 
1.257     albertel 5422:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5423:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5424:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5425:     my $pageTitle = $env{'form.page'};
1.103     albertel 5426:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5427:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5428:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5429:     if (!&canmodify($usec)) {
1.526     raeburn  5430: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5431: 	return;
                   5432:     }
1.398     albertel 5433:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5434:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5435: 	'</h3>'."\n";
1.70      ng       5436: 
1.68      ng       5437:     $request->print($result);
                   5438: 
1.582     raeburn  5439: 
1.132     bowersj2 5440:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5441:     unless (ref($navmap)) {
                   5442:         $request->print(&navmap_errormsg());
                   5443:         return;
                   5444:     }
1.257     albertel 5445:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5446:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5447:     if (!$map) {
1.527     raeburn  5448: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5449: 	return; 
                   5450:     }
1.71      ng       5451:     my $iterator = $navmap->getIterator($map->map_start(),
                   5452: 					$map->map_finish());
1.70      ng       5453: 
1.484     albertel 5454:     my $studentTable=
                   5455: 	&Apache::loncommon::start_data_table().
                   5456: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5457: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5458: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5459: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5460: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5461: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5462: 
                   5463:     $iterator->next(); # skip the first BEGIN_MAP
                   5464:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5465:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5466:     while ($depth > 0) {
1.71      ng       5467:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5468:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5469: 
1.385     albertel 5470:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5471: 	    my $parts = $curRes->parts();
1.71      ng       5472:             my $title = $curRes->compTitle();
                   5473: 	    my $symbx = $curRes->symb();
1.484     albertel 5474: 	    $studentTable.=
                   5475: 		&Apache::loncommon::start_data_table_row().
                   5476: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5477: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5478:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5479: 		.')').'</td>';
1.71      ng       5480: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5481: 
                   5482: 	    my %newrecord=();
                   5483: 	    my @displayPts=();
1.269     raeburn  5484:             my %aggregate = ();
                   5485:             my $aggregateflag = 0;
1.726     raeburn  5486:             if ($env{'form.HIDE'.$prob}) {
                   5487:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5488:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5489:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5490:                 $hideflag += $numchgs;
                   5491:             }
1.71      ng       5492: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5493: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5494: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5495: 
1.257     albertel 5496: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5497: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5498: 		my $partial = $newpts/$wgt;
                   5499: 		my $score;
                   5500: 		if ($partial > 0) {
                   5501: 		    $score = 'correct_by_override';
1.125     ng       5502: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5503: 		    $score = 'incorrect_by_override';
                   5504: 		}
1.257     albertel 5505: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5506: 		if ($dropMenu eq 'excused') {
1.71      ng       5507: 		    $partial = '';
                   5508: 		    $score = 'excused';
1.125     ng       5509: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5510: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5511: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5512: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5513: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5514: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5515: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5516: 		    $changeflag++;
                   5517: 		    $newpts = '';
1.269     raeburn  5518:                     
                   5519:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5520:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5521:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5522:                     if ($aggtries > 0) {
                   5523:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5524:                         $aggregateflag = 1;
                   5525:                     }
1.71      ng       5526: 		}
1.324     albertel 5527: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5528: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5529: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5530: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5531: 		    '&nbsp;<br />';
1.526     raeburn  5532: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5533: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5534: 		    '&nbsp;<br />';
1.71      ng       5535: 		$question++;
1.380     albertel 5536: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5537: 
1.71      ng       5538: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5539: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5540: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5541: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5542: 
                   5543: 		$changeflag++;
                   5544: 	    }
                   5545: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5546: 		my %record = 
                   5547: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5548: 					     $udom,$uname);
                   5549: 
                   5550: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5551: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5552: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5553: 		    $newrecord{'resource.CODE'} = '';
                   5554: 		}
1.257     albertel 5555: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5556: 					$udom,$uname);
1.382     albertel 5557: 		%record = &Apache::lonnet::restore($symbx,
                   5558: 						   $env{'request.course.id'},
                   5559: 						   $udom,$uname);
1.380     albertel 5560: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5561: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5562: 	    }
1.380     albertel 5563: 	    
1.269     raeburn  5564:             if ($aggregateflag) {
                   5565:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5566:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5567:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5568:             }
1.125     ng       5569: 
1.71      ng       5570: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5571: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5572: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5573: 
1.196     albertel 5574: 	    $prob++;
1.68      ng       5575: 	}
1.71      ng       5576:         $curRes = $iterator->next();
1.68      ng       5577:     }
1.98      albertel 5578: 
1.484     albertel 5579:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5580:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5581: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5582: 		  $changeflag).'<br />');
                   5583:     my $hidemsg=($hideflag == 0 ? '' :
                   5584:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5585:                      $hideflag).'<br />');
                   5586:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5587: 
1.70      ng       5588:     return '';
                   5589: }
                   5590: 
1.72      ng       5591: #-------- end of section for handling grading by page/sequence ---------
                   5592: #
                   5593: #-------------------------------------------------------------------
                   5594: 
1.581     www      5595: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5596: #
                   5597: #------ start of section for handling grading by page/sequence ---------
                   5598: 
1.423     albertel 5599: =pod
                   5600: 
                   5601: =head1 Bubble sheet grading routines
                   5602: 
1.424     albertel 5603:   For this documentation:
                   5604: 
                   5605:    'scanline' refers to the full line of characters
                   5606:    from the file that we are parsing that represents one entire sheet
                   5607: 
                   5608:    'bubble line' refers to the data
1.659     raeburn  5609:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5610: 
                   5611: 
1.659     raeburn  5612: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5613: into a course. When a user wants to grade, they select a
1.659     raeburn  5614: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5615: one of the predefined configurations for what each scanline looks
                   5616: like.
                   5617: 
                   5618: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5619: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5620: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5621: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5622: invalid student/employee ID
1.424     albertel 5623: 
                   5624: If the CODE option is used that determines the randomization of the
1.556     weissno  5625: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5626: username:domain.
                   5627: 
                   5628: During the validation phase the instructor can choose to skip scanlines. 
                   5629: 
1.659     raeburn  5630: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5631: 
                   5632:   scantron_original_filename (unmodified original file)
                   5633:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5634:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5635: 
                   5636: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5637: correction information that isn't representable in the bubblesheet
1.424     albertel 5638: file (see &scantron_getfile() for more information)
                   5639: 
                   5640: After all scanlines are either valid, marked as valid or skipped, then
                   5641: foreach line foreach problem in the picked sequence, an ssi request is
                   5642: made that simulates a user submitting their selected letter(s) against
                   5643: the homework problem.
1.423     albertel 5644: 
                   5645: =over 4
                   5646: 
                   5647: 
                   5648: 
                   5649: =item defaultFormData
                   5650: 
                   5651:   Returns html hidden inputs used to hold context/default values.
                   5652: 
                   5653:  Arguments:
                   5654:   $symb - $symb of the current resource 
                   5655: 
                   5656: =cut
1.422     foxr     5657: 
1.81      albertel 5658: sub defaultFormData {
1.324     albertel 5659:     my ($symb)=@_;
1.766     raeburn  5660:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5661: }
                   5662: 
1.447     foxr     5663: 
1.423     albertel 5664: =pod 
                   5665: 
                   5666: =item getSequenceDropDown
                   5667: 
                   5668:    Return html dropdown of possible sequences to grade
                   5669:  
                   5670:  Arguments:
1.582     raeburn  5671:    $symb - $symb of the current resource
                   5672:    $map_error - ref to scalar which will container error if
                   5673:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5674: 
                   5675: =cut
1.422     foxr     5676: 
1.75      albertel 5677: sub getSequenceDropDown {
1.582     raeburn  5678:     my ($symb,$map_error)=@_;
1.75      albertel 5679:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5680:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5681:     if (ref($map_error)) {
                   5682:         return if ($$map_error);
                   5683:     }
1.137     albertel 5684:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5685:     my $ctr=0;
                   5686:     foreach (@$titles) {
                   5687: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5688: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5689: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5690: 	    '>'.$showtitle.'</option>'."\n";
                   5691: 	$ctr++;
                   5692:     }
                   5693:     $result.= '</select>';
                   5694:     return $result;
                   5695: }
                   5696: 
1.495     albertel 5697: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5698:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5699: 
                   5700: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5701: 
1.509     raeburn  5702: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5703:                                    # matchresponse or rankresponse, where 
                   5704:                                    # an individual response can have multiple 
                   5705:                                    # lines
1.503     raeburn  5706: 
                   5707: my %responsetype_per_response;     # responsetype for each response
                   5708: 
1.691     raeburn  5709: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5710:                                    # numbered response. Needed when randomorder
                   5711:                                    # or randompick are in use. Key is ID, value 
                   5712:                                    # is response number.
                   5713: 
1.495     albertel 5714: # Save and restore the bubble lines array to the form env.
                   5715: 
                   5716: 
                   5717: sub save_bubble_lines {
                   5718:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5719: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5720: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5721: 	    $first_bubble_line{$line};
1.503     raeburn  5722:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5723:             $subdivided_bubble_lines{$line};
                   5724:         $env{"form.scantron.responsetype.$line"} =
                   5725:             $responsetype_per_response{$line};
1.495     albertel 5726:     }
1.691     raeburn  5727:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5728:         my $line = $masterseq_id_responsenum{$resid};
                   5729:         $env{"form.scantron.residpart.$line"} = $resid;
                   5730:     }
1.495     albertel 5731: }
                   5732: 
                   5733: 
                   5734: sub restore_bubble_lines {
                   5735:     my $line = 0;
                   5736:     %bubble_lines_per_response = ();
1.691     raeburn  5737:     %masterseq_id_responsenum = ();
1.495     albertel 5738:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5739: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5740: 	$bubble_lines_per_response{$line} = $value;
                   5741: 	$first_bubble_line{$line}  =
                   5742: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5743:         $subdivided_bubble_lines{$line} =
                   5744:             $env{"form.scantron.sub_bubblelines.$line"};
                   5745:         $responsetype_per_response{$line} =
                   5746:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5747:         my $id = $env{"form.scantron.residpart.$line"};
                   5748:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5749: 	$line++;
                   5750:     }
                   5751: }
                   5752: 
1.423     albertel 5753: =pod 
                   5754: 
                   5755: =item scantron_filenames
                   5756: 
                   5757:    Returns a list of the scantron files in the current course 
                   5758: 
                   5759: =cut
1.422     foxr     5760: 
1.202     albertel 5761: sub scantron_filenames {
1.257     albertel 5762:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5763:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5764:     my $getpropath = 1;
1.662     raeburn  5765:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5766:                                                         $cname,$getpropath);
1.202     albertel 5767:     my @possiblenames;
1.662     raeburn  5768:     if (ref($dirlist) eq 'ARRAY') {
                   5769:         foreach my $filename (sort(@{$dirlist})) {
                   5770: 	    ($filename)=split(/&/,$filename);
                   5771: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5772: 	    $filename=~s/^scantron_orig_//;
                   5773: 	    push(@possiblenames,$filename);
                   5774:         }
1.202     albertel 5775:     }
                   5776:     return @possiblenames;
                   5777: }
                   5778: 
1.423     albertel 5779: =pod 
                   5780: 
                   5781: =item scantron_uploads
                   5782: 
                   5783:    Returns  html drop-down list of scantron files in current course.
                   5784: 
                   5785:  Arguments:
                   5786:    $file2grade - filename to set as selected in the dropdown
                   5787: 
                   5788: =cut
1.422     foxr     5789: 
1.202     albertel 5790: sub scantron_uploads {
1.209     ng       5791:     my ($file2grade) = @_;
1.202     albertel 5792:     my $result=	'<select name="scantron_selectfile">';
                   5793:     $result.="<option></option>";
                   5794:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5795: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5796:     }
                   5797:     $result.="</select>";
                   5798:     return $result;
                   5799: }
                   5800: 
1.423     albertel 5801: =pod 
                   5802: 
                   5803: =item scantron_scantab
                   5804: 
                   5805:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5806:   file.
                   5807: 
                   5808: =cut
1.422     foxr     5809: 
1.82      albertel 5810: sub scantron_scantab {
                   5811:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5812:     $result.='<option></option>'."\n";
1.754     raeburn  5813:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5814:     if (@lines > 0) {
                   5815:         foreach my $line (@lines) {
                   5816:             next if (($line =~ /^\#/) || ($line eq ''));
                   5817: 	    my ($name,$descrip)=split(/:/,$line);
                   5818: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5819:         }
1.82      albertel 5820:     }
                   5821:     $result.='</select>'."\n";
1.518     raeburn  5822:     return $result;
                   5823: }
                   5824: 
1.423     albertel 5825: =pod 
                   5826: 
                   5827: =item scantron_CODElist
                   5828: 
                   5829:   Returns html drop down of the saved CODE lists from current course,
                   5830:   generated from earlier printings.
                   5831: 
                   5832: =cut
1.422     foxr     5833: 
1.186     albertel 5834: sub scantron_CODElist {
1.257     albertel 5835:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5836:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5837:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5838:     my $namechoice='<option></option>';
1.225     albertel 5839:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5840: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5841: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5842: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5843:     }
                   5844:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5845:     return $namechoice;
                   5846: }
                   5847: 
1.423     albertel 5848: =pod 
                   5849: 
                   5850: =item scantron_CODEunique
                   5851: 
                   5852:   Returns the html for "Each CODE to be used once" radio.
                   5853: 
                   5854: =cut
1.422     foxr     5855: 
1.186     albertel 5856: sub scantron_CODEunique {
1.532     bisitz   5857:     my $result='<span class="LC_nobreak">
1.272     albertel 5858:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5859:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5860:                 </span>
1.532     bisitz   5861:                 <span class="LC_nobreak">
1.272     albertel 5862:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5863:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5864:                 </span>';
1.186     albertel 5865:     return $result;
                   5866: }
1.423     albertel 5867: 
                   5868: =pod 
                   5869: 
                   5870: =item scantron_selectphase
                   5871: 
1.659     raeburn  5872:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5873:   Allows for - starting a grading run.
1.424     albertel 5874:              - downloading existing scan data (original, corrected
1.423     albertel 5875:                                                 or skipped info)
                   5876: 
                   5877:              - uploading new scan data
                   5878: 
                   5879:  Arguments:
                   5880:   $r          - The Apache request object
                   5881:   $file2grade - name of the file that contain the scanned data to score
                   5882: 
                   5883: =cut
1.186     albertel 5884: 
1.75      albertel 5885: sub scantron_selectphase {
1.608     www      5886:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5887:     if (!$symb) {return '';}
1.582     raeburn  5888:     my $map_error;
                   5889:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5890:     if ($map_error) {
                   5891:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5892:         return;
                   5893:     }
1.324     albertel 5894:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5895:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5896:     my $format_selector=&scantron_scantab();
1.186     albertel 5897:     my $CODE_selector=&scantron_CODElist();
                   5898:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5899:     my $result;
1.422     foxr     5900: 
1.513     foxr     5901:     $ssi_error = 0;
                   5902: 
1.770     raeburn  5903:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 5904: 
                   5905: 	# Chunk of form to prompt for a scantron file upload.
                   5906: 
                   5907:         $r->print('
1.754     raeburn  5908:     <br />');
1.606     wenzelju 5909:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5910:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  5911:     my $csec= $env{'request.course.sec'};
1.736     damieng  5912:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5913:     &js_escape(\$alertmsg);
1.754     raeburn  5914:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 5915:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5916:     function checkUpload(formname) {
                   5917: 	if (formname.upfile.value == "") {
1.736     damieng  5918: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5919: 	    return false;
                   5920: 	}
                   5921: 	formname.submit();
1.756     raeburn  5922:     }'."\n".$formatjs));
1.606     wenzelju 5923:     $r->print('
                   5924:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5925:                 '.$default_form_data.'
                   5926:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  5927:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 5928:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5929:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  5930:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5931:               '.&Apache::loncommon::start_data_table_header_row().'
                   5932:                 <th>
                   5933:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5934:                 </th>
                   5935:               '.&Apache::loncommon::end_data_table_header_row().'
                   5936:               '.&Apache::loncommon::start_data_table_row().'
                   5937:             <td>
                   5938:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   5939:     if ($formatoptions) {
                   5940:         $r->print('</td>
                   5941:                  '.&Apache::loncommon::end_data_table_row().'
                   5942:                  '.&Apache::loncommon::start_data_table_row().'
                   5943:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   5944:                  </td>
                   5945:                  '.&Apache::loncommon::end_data_table_row().'
                   5946:                  '.&Apache::loncommon::start_data_table_row().'
                   5947:                  <td>'
                   5948:         );
                   5949:     } else {
                   5950:         $r->print(' <br />');
                   5951:     }
                   5952:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5953:               </td>
                   5954:              '.&Apache::loncommon::end_data_table_row().'
                   5955:              '.&Apache::loncommon::end_data_table().'
                   5956:              </form>'
                   5957:     );
1.606     wenzelju 5958: 
                   5959:     }
                   5960: 
1.422     foxr     5961:     # Chunk of form to prompt for a file to grade and how:
                   5962: 
1.489     albertel 5963:     $result.= '
                   5964:     <br />
                   5965:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5966:     <input type="hidden" name="command" value="scantron_warning" />
                   5967:     '.$default_form_data.'
                   5968:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5969:        '.&Apache::loncommon::start_data_table_header_row().'
                   5970:             <th colspan="2">
1.492     albertel 5971:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5972:             </th>
                   5973:        '.&Apache::loncommon::end_data_table_header_row().'
                   5974:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5975:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5976:        '.&Apache::loncommon::end_data_table_row().'
                   5977:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5978:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5979:        '.&Apache::loncommon::end_data_table_row().'
                   5980:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5981:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5982:        '.&Apache::loncommon::end_data_table_row().'
                   5983:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5984:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5985:        '.&Apache::loncommon::end_data_table_row().'
                   5986:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5987:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5988:        '.&Apache::loncommon::end_data_table_row().'
                   5989:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5990: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5991:             <td>
1.492     albertel 5992: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5993:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5994:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5995: 	    </td>
1.489     albertel 5996:        '.&Apache::loncommon::end_data_table_row().'
                   5997:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5998:             <td colspan="2">
1.572     www      5999:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6000:             </td>
1.489     albertel 6001:        '.&Apache::loncommon::end_data_table_row().'
                   6002:     '.&Apache::loncommon::end_data_table().'
                   6003:     </form>
                   6004: ';
1.162     albertel 6005:    
                   6006:     $r->print($result);
                   6007: 
1.422     foxr     6008:     # Chunk of the form that prompts to view a scoring office file,
                   6009:     # corrected file, skipped records in a file.
                   6010: 
1.489     albertel 6011:     $r->print('
                   6012:    <br />
                   6013:    <form action="/adm/grades" name="scantron_download">
                   6014:      '.$default_form_data.'
                   6015:      <input type="hidden" name="command" value="scantron_download" />
                   6016:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6017:        '.&Apache::loncommon::start_data_table_header_row().'
                   6018:               <th>
1.492     albertel 6019:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6020:               </th>
                   6021:        '.&Apache::loncommon::end_data_table_header_row().'
                   6022:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6023:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6024:                 <br />
1.492     albertel 6025:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6026:        '.&Apache::loncommon::end_data_table_row().'
                   6027:      '.&Apache::loncommon::end_data_table().'
                   6028:    </form>
                   6029:    <br />
                   6030: ');
1.162     albertel 6031: 
1.457     banghart 6032:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6033: 
1.694     bisitz   6034:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6035:              $default_form_data."\n".
                   6036:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6037:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6038:              '<th colspan="2">
1.572     www      6039:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6040:              '</th>'."\n".
                   6041:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6042:               &Apache::loncommon::start_data_table_row()."\n".
                   6043:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6044:               '<td> '.$sequence_selector.' </td>'.
                   6045:               &Apache::loncommon::end_data_table_row()."\n".
                   6046:               &Apache::loncommon::start_data_table_row()."\n".
                   6047:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6048:               '<td> '.$file_selector.' </td>'."\n".
                   6049:               &Apache::loncommon::end_data_table_row()."\n".
                   6050:               &Apache::loncommon::start_data_table_row()."\n".
                   6051:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6052:               '<td> '.$format_selector.' </td>'."\n".
                   6053:               &Apache::loncommon::end_data_table_row()."\n".
                   6054:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6055:               '<td> '.&mt('Options').' </td>'."\n".
                   6056:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6057:               &Apache::loncommon::end_data_table_row()."\n".
                   6058:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6059:               '<td colspan="2">'."\n".
                   6060:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6061:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6062:               '</td>'."\n".
                   6063:               &Apache::loncommon::end_data_table_row()."\n".
                   6064:               &Apache::loncommon::end_data_table()."\n".
                   6065:               '</form><br />');
                   6066:     return;
1.75      albertel 6067: }
                   6068: 
1.423     albertel 6069: =pod 
                   6070: 
                   6071: =item username_to_idmap
                   6072: 
1.556     weissno  6073:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6074:     student username:domain. If a single ID occurs for more than one student,
                   6075:     the status of the student is checked, and if Active, the value in the hash
                   6076:     will be set to the Active student.
1.423     albertel 6077: 
                   6078:   Arguments:
                   6079: 
                   6080:     $classlist - reference to the class list hash. This is a hash
                   6081:                  keyed by student name:domain  whose elements are references
1.424     albertel 6082:                  to arrays containing various chunks of information
1.423     albertel 6083:                  about the student. (See loncoursedata for more info).
                   6084: 
                   6085:   Returns
                   6086:     %idmap - the constructed hash
                   6087: 
                   6088: =cut
                   6089: 
1.82      albertel 6090: sub username_to_idmap {
                   6091:     my ($classlist)= @_;
                   6092:     my %idmap;
                   6093:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6094:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6095:         unless ($id eq '') {
                   6096:             if (!exists($idmap{$id})) {
                   6097:                 $idmap{$id} = $student;
                   6098:             } else {
                   6099:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6100:                 if ($status eq 'Active') {
                   6101:                     $idmap{$id} = $student;
                   6102:                 }
                   6103:             }
                   6104:         }
1.82      albertel 6105:     }
                   6106:     return %idmap;
                   6107: }
1.423     albertel 6108: 
                   6109: =pod
                   6110: 
1.424     albertel 6111: =item scantron_fixup_scanline
1.423     albertel 6112: 
                   6113:    Process a requested correction to a scanline.
                   6114: 
                   6115:   Arguments:
1.754     raeburn  6116:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6117:     $scan_data         - hash of correction information 
                   6118:                           (see &scantron_getfile())
                   6119:     $line              - existing scanline
                   6120:     $whichline         - line number of the passed in scanline
                   6121:     $field             - type of change to process 
                   6122:                          (either 
1.573     bisitz   6123:                           'ID'     -> correct the student/employee ID
1.423     albertel 6124:                           'CODE'   -> correct the CODE
                   6125:                           'answer' -> fixup the submitted answers)
                   6126:     
                   6127:    $args               - hash of additional info,
                   6128:                           - 'ID' 
                   6129:                                'newid' -> studentID to use in replacement
1.424     albertel 6130:                                           of existing one
1.423     albertel 6131:                           - 'CODE' 
                   6132:                                'CODE_ignore_dup' - set to true if duplicates
                   6133:                                                    should be ignored.
                   6134: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6135:                                         if the existing unfound code should
1.423     albertel 6136:                                         be used as is
                   6137:                           - 'answer'
                   6138:                                'response' - new answer or 'none' if blank
                   6139:                                'question' - the bubble line to change
1.503     raeburn  6140:                                'questionnum' - the question identifier,
                   6141:                                                may include subquestion. 
1.423     albertel 6142: 
                   6143:   Returns:
                   6144:     $line - the modified scanline
                   6145: 
                   6146:   Side effects: 
                   6147:     $scan_data - may be updated
                   6148: 
                   6149: =cut
                   6150: 
1.82      albertel 6151: 
1.157     albertel 6152: sub scantron_fixup_scanline {
                   6153:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6154:     if ($field eq 'ID') {
                   6155: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6156: 	    return ($line,1,'New value too large');
1.157     albertel 6157: 	}
                   6158: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6159: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6160: 				     $args->{'newid'});
                   6161: 	}
                   6162: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6163: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6164: 	if ($args->{'newid'}=~/^\s*$/) {
                   6165: 	    &scan_data($scan_data,"$whichline.user",
                   6166: 		       $args->{'username'}.':'.$args->{'domain'});
                   6167: 	}
1.186     albertel 6168:     } elsif ($field eq 'CODE') {
1.192     albertel 6169: 	if ($args->{'CODE_ignore_dup'}) {
                   6170: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6171: 	}
                   6172: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6173: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6174: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6175: 		return ($line,1,'New CODE value too large');
                   6176: 	    }
                   6177: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6178: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6179: 	    }
                   6180: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6181: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6182: 	}
1.157     albertel 6183:     } elsif ($field eq 'answer') {
1.497     foxr     6184: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6185: 	my $off=$scantron_config->{'Qoff'};
                   6186: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6187: 	my $answer=${off}x$length;
                   6188: 	if ($args->{'response'} eq 'none') {
                   6189: 	    &scan_data($scan_data,
1.503     raeburn  6190: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6191: 	} else {
                   6192: 	    if ($on eq 'letter') {
                   6193: 		my @alphabet=('A'..'Z');
                   6194: 		$answer=$alphabet[$args->{'response'}];
                   6195: 	    } elsif ($on eq 'number') {
                   6196: 		$answer=$args->{'response'}+1;
                   6197: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6198: 	    } else {
1.497     foxr     6199: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6200: 	    }
1.497     foxr     6201: 	    &scan_data($scan_data,
1.503     raeburn  6202: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6203: 	}
1.497     foxr     6204: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6205: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6206:     }
                   6207:     return $line;
                   6208: }
1.423     albertel 6209: 
                   6210: =pod
                   6211: 
                   6212: =item scan_data
                   6213: 
                   6214:     Edit or look up  an item in the scan_data hash.
                   6215: 
                   6216:   Arguments:
                   6217:     $scan_data  - The hash (see scantron_getfile)
                   6218:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6219:                   scantronfilename_key).
1.423     albertel 6220:     $data        - New value of the hash entry.
                   6221:     $delete      - If true, the entry is removed from the hash.
                   6222: 
                   6223:   Returns:
                   6224:     The new value of the hash table field (undefined if deleted).
                   6225: 
                   6226: =cut
                   6227: 
                   6228: 
1.157     albertel 6229: sub scan_data {
                   6230:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6231:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6232:     if (defined($value)) {
                   6233: 	$scan_data->{$filename.'_'.$key} = $value;
                   6234:     }
                   6235:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6236:     return $scan_data->{$filename.'_'.$key};
                   6237: }
1.423     albertel 6238: 
1.495     albertel 6239: # ----- These first few routines are general use routines.----
                   6240: 
                   6241: # Return the number of occurences of a pattern in a string.
                   6242: 
                   6243: sub occurence_count {
                   6244:     my ($string, $pattern) = @_;
                   6245: 
                   6246:     my @matches = ($string =~ /$pattern/g);
                   6247: 
                   6248:     return scalar(@matches);
                   6249: }
                   6250: 
                   6251: 
                   6252: # Take a string known to have digits and convert all the
                   6253: # digits into letters in the range J,A..I.
                   6254: 
                   6255: sub digits_to_letters {
                   6256:     my ($input) = @_;
                   6257: 
                   6258:     my @alphabet = ('J', 'A'..'I');
                   6259: 
                   6260:     my @input    = split(//, $input);
                   6261:     my $output ='';
                   6262:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6263: 	if ($input[$i] =~ /\d/) {
                   6264: 	    $output .= $alphabet[$input[$i]];
                   6265: 	} else {
                   6266: 	    $output .= $input[$i];
                   6267: 	}
                   6268:     }
                   6269:     return $output;
                   6270: }
                   6271: 
1.423     albertel 6272: =pod 
                   6273: 
                   6274: =item scantron_parse_scanline
                   6275: 
1.711     bisitz   6276:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6277: 
                   6278:  Arguments:
1.711     bisitz   6279:     line             - The text of the bubblesheet file line to process
1.423     albertel 6280:     whichline        - Line number
1.711     bisitz   6281:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6282:     scan_data        - Hash of extra information about the scanline
                   6283:                        (see scantron_getfile for more information)
                   6284:     just_header      - True if should not process question answers but only
                   6285:                        the stuff to the left of the answers.
1.691     raeburn  6286:     randomorder      - True if randomorder in use
                   6287:     randompick       - True if randompick in use
                   6288:     sequence         - Exam folder URL
                   6289:     master_seq       - Ref to array containing symbs in exam folder
                   6290:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6291:                        (corresponding values are resource objects)
                   6292:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6293:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6294:                        are refs to an array of resource objects, ordered
                   6295:                        according to order used for CODE, when randomorder
                   6296:                        and or randompick are in use.
                   6297:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6298:                        for current line to question number used for same question
                   6299:                         in "Master Sequence" (as seen by Course Coordinator).
                   6300:     startline        - Ref to hash where key is question number (0 is first)
                   6301:                        and value is number of first bubble line for current 
                   6302:                        student or code-based randompick and/or randomorder.
                   6303:     totalref         - Ref of scalar used to score total number of bubble
                   6304:                        lines needed for responses in a scan line (used when
                   6305:                        randompick in use. 
                   6306:     
1.423     albertel 6307:  Returns:
                   6308:    Hash containing the result of parsing the scanline
                   6309: 
                   6310:    Keys are all proceeded by the string 'scantron.'
                   6311: 
                   6312:        CODE    - the CODE in use for this scanline
                   6313:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6314:                  by the operator
                   6315:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6316:                             CODEs were selected, but the usage has been
                   6317:                             forced by the operator
1.556     weissno  6318:        ID  - student/employee ID
1.423     albertel 6319:        PaperID - if used, the ID number printed on the sheet when the 
                   6320:                  paper was scanned
                   6321:        FirstName - first name from the sheet
                   6322:        LastName  - last name from the sheet
                   6323: 
                   6324:      if just_header was not true these key may also exist
                   6325: 
1.447     foxr     6326:        missingerror - a list of bubble ranges that are considered to be answers
                   6327:                       to a single question that don't have any bubbles filled in.
                   6328:                       Of the form questionnumber:firstbubblenumber:count.
                   6329:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6330:                       to a single question that have more than one bubble filled in.
                   6331:                       Of the form questionnumber::firstbubblenumber:count
                   6332:    
                   6333:                 In the above, count is the number of bubble responses in the
                   6334:                 input line needed to represent the possible answers to the question.
                   6335:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6336:                 per line would have count = 2.
                   6337: 
1.423     albertel 6338:        maxquest     - the number of the last bubble line that was parsed
                   6339: 
                   6340:        (<number> starts at 1)
                   6341:        <number>.answer - zero or more letters representing the selected
                   6342:                          letters from the scanline for the bubble line 
                   6343:                          <number>.
                   6344:                          if blank there was either no bubble or there where
                   6345:                          multiple bubbles, (consult the keys missingerror and
                   6346:                          doubleerror if this is an error condition)
                   6347: 
                   6348: =cut
                   6349: 
1.82      albertel 6350: sub scantron_parse_scanline {
1.691     raeburn  6351:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6352:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6353:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6354: 
1.82      albertel 6355:     my %record;
1.691     raeburn  6356:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6357:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6358: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6359: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6360: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6361: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6362: 	    $record{'scantron.CODE'}=substr($data,
                   6363: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6364: 					    $$scantron_config{'CODElength'});
1.191     albertel 6365: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6366: 		$record{'scantron.useCODE'}=1;
                   6367: 	    }
1.192     albertel 6368: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6369: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6370: 	    }
1.82      albertel 6371: 	} else {
                   6372: 	    #FIXME interpret first N questions
                   6373: 	}
                   6374:     }
1.83      albertel 6375:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6376: 				  $$scantron_config{'IDlength'});
1.157     albertel 6377:     $record{'scantron.PaperID'}=
                   6378: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6379: 	       $$scantron_config{'PaperIDlength'});
                   6380:     $record{'scantron.FirstName'}=
                   6381: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6382: 	       $$scantron_config{'FirstNamelength'});
                   6383:     $record{'scantron.LastName'}=
                   6384: 	substr($data,$$scantron_config{'LastName'}-1,
                   6385: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6386:     if ($just_header) { return \%record; }
1.194     albertel 6387: 
1.82      albertel 6388:     my @alphabet=('A'..'Z');
                   6389:     my $questnum=0;
1.447     foxr     6390:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6391: 
1.691     raeburn  6392:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6393:     if ($randompick || $randomorder) {
                   6394:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6395:                                          $master_seq,$symb_to_resource,
                   6396:                                          $partids_by_symb,$orderedforcode,
                   6397:                                          $respnumlookup,$startline);
                   6398:         if ($total) {
                   6399:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6400:         }
                   6401:         if (ref($totalref)) {
                   6402:             $$totalref = $total;
                   6403:         }
                   6404:     }
                   6405:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6406:     chomp($questions);		# Get rid of any trailing \n.
                   6407:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6408:     while (length($questions)) {
1.691     raeburn  6409:         my $answers_needed;
                   6410:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6411:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6412:         } else {
                   6413: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6414:         }
1.503     raeburn  6415:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6416:                              || 1;
                   6417:         $questnum++;
                   6418:         my $quest_id = $questnum;
                   6419:         my $currentquest = substr($questions,0,$answer_length);
                   6420:         $questions       = substr($questions,$answer_length);
                   6421:         if (length($currentquest) < $answer_length) { next; }
                   6422: 
1.691     raeburn  6423:         my $subdivided;
                   6424:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6425:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6426:         } else {
                   6427:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6428:         }
                   6429:         if ($subdivided =~ /,/) {
1.503     raeburn  6430:             my $subquestnum = 1;
                   6431:             my $subquestions = $currentquest;
1.691     raeburn  6432:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6433:             foreach my $subans (@subanswers_needed) {
                   6434:                 my $subans_length =
                   6435:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6436:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6437:                 $subquestions   = substr($subquestions,$subans_length);
                   6438:                 $quest_id = "$questnum.$subquestnum";
                   6439:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6440:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6441:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6442:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6443:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6444:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6445:                 } else {
                   6446:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6447:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6448:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6449:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6450:                 }
                   6451:                 $subquestnum ++;
                   6452:             }
                   6453:         } else {
                   6454:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6455:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6456:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6457:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6458:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6459:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6460:             } else {
                   6461:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6462:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6463:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6464:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6465:             }
                   6466:         }
                   6467:     }
                   6468:     $record{'scantron.maxquest'}=$questnum;
                   6469:     return \%record;
                   6470: }
1.447     foxr     6471: 
1.691     raeburn  6472: sub get_master_seq {
                   6473:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6474:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6475:                    (ref($symb_to_resource) eq 'HASH'));
                   6476:     my $resource_error;
                   6477:     foreach my $resource (@{$resources}) {
                   6478:         my $ressymb;
                   6479:         if (ref($resource)) {
                   6480:             $ressymb = $resource->symb();
                   6481:             push(@{$master_seq},$ressymb);
                   6482:             $symb_to_resource->{$ressymb} = $resource;
                   6483:         } else {
                   6484:             $resource_error = 1;
                   6485:             last;
                   6486:         }
                   6487:     }
                   6488:     return $resource_error;
                   6489: }
                   6490: 
                   6491: sub get_respnum_lookups {
                   6492:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6493:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6494:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6495:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6496:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6497:                    (ref($startline) eq 'HASH'));
                   6498:     my ($user,$scancode);
                   6499:     if ((exists($record->{'scantron.CODE'})) &&
                   6500:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6501:         $scancode = $record->{'scantron.CODE'};
                   6502:     } else {
                   6503:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6504:     }
                   6505:     my @mapresources =
                   6506:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6507:                      $orderedforcode);
                   6508:     my $total = 0;
                   6509:     my $count = 0;
                   6510:     foreach my $resource (@mapresources) {
                   6511:         my $id = $resource->id();
                   6512:         my $symb = $resource->symb();
                   6513:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6514:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6515:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6516:                 if ($respnum ne '') {
                   6517:                     $respnumlookup->{$count} = $respnum;
                   6518:                     $startline->{$count} = $total;
                   6519:                     $total += $bubble_lines_per_response{$respnum};
                   6520:                     $count ++;
                   6521:                 }
                   6522:             }
                   6523:         }
                   6524:     }
                   6525:     return $total;
                   6526: }
                   6527: 
1.503     raeburn  6528: sub scantron_validator_lettnum {
                   6529:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6530:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6531:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6532: 
                   6533:     # Qon 'letter' implies for each slot in currquest we have:
                   6534:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6535:     #    about anything else (esp. a value of Qoff) for missing
                   6536:     #    bubbles.
                   6537:     #
                   6538:     # Qon 'number' implies each slot gives a digit that indexes the
                   6539:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6540:     #    and * or ? for double bubbles on a single line.
                   6541:     #
1.447     foxr     6542: 
1.503     raeburn  6543:     my $matchon;
                   6544:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6545:         $matchon = '[A-Z]';
                   6546:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6547:         $matchon = '\d';
                   6548:     }
                   6549:     my $occurrences = 0;
1.691     raeburn  6550:     my $responsenum = $questnum-1;
                   6551:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6552:        $responsenum = $respnumlookup->{$questnum-1} 
                   6553:     }
                   6554:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6555:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6556:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6557:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6558:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6559:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6560:         my @singlelines = split('',$currquest);
                   6561:         foreach my $entry (@singlelines) {
                   6562:             $occurrences = &occurence_count($entry,$matchon);
                   6563:             if ($occurrences > 1) {
                   6564:                 last;
                   6565:             }
1.691     raeburn  6566:         }
1.503     raeburn  6567:     } else {
                   6568:         $occurrences = &occurence_count($currquest,$matchon); 
                   6569:     }
                   6570:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6571:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6572:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6573:             my $bubble = substr($currquest,$ans,1);
                   6574:             if ($bubble =~ /$matchon/ ) {
                   6575:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6576:                     if ($bubble == 0) {
                   6577:                         $bubble = 10; 
                   6578:                     }
                   6579:                     $record->{"scantron.$ansnum.answer"} = 
                   6580:                         $alphabet->[$bubble-1];
                   6581:                 } else {
                   6582:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6583:                 }
                   6584:             } else {
                   6585:                 $record->{"scantron.$ansnum.answer"}='';
                   6586:             }
                   6587:             $ansnum++;
                   6588:         }
                   6589:     } elsif (!defined($currquest)
                   6590:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6591:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6592:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6593:             $record->{"scantron.$ansnum.answer"}='';
                   6594:             $ansnum++;
                   6595:         }
                   6596:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6597:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6598:         }
                   6599:     } else {
                   6600:         if ($$scantron_config{'Qon'} eq 'number') {
                   6601:             $currquest = &digits_to_letters($currquest);            
                   6602:         }
                   6603:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6604:             my $bubble = substr($currquest,$ans,1);
                   6605:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6606:             $ansnum++;
                   6607:         }
                   6608:     }
                   6609:     return $ansnum;
                   6610: }
1.447     foxr     6611: 
1.503     raeburn  6612: sub scantron_validator_positional {
                   6613:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6614:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6615:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6616: 
1.503     raeburn  6617:     # Otherwise there's a positional notation;
                   6618:     # each bubble line requires Qlength items, and there are filled in
                   6619:     # bubbles for each case where there 'Qon' characters.
                   6620:     #
1.447     foxr     6621: 
1.503     raeburn  6622:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6623: 
1.503     raeburn  6624:     # If the split only gives us one element.. the full length of the
                   6625:     # answer string, no bubbles are filled in:
1.447     foxr     6626: 
1.507     raeburn  6627:     if ($answers_needed eq '') {
                   6628:         return;
                   6629:     }
                   6630: 
1.503     raeburn  6631:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6632:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6633:             $record->{"scantron.$ansnum.answer"}='';
                   6634:             $ansnum++;
                   6635:         }
                   6636:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6637:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6638:         }
                   6639:     } elsif (scalar(@array) == 2) {
                   6640:         my $location = length($array[0]);
                   6641:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6642:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6643:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6644:             if ($ans eq $line_num) {
                   6645:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6646:             } else {
                   6647:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6648:             }
                   6649:             $ansnum++;
                   6650:          }
                   6651:     } else {
                   6652:         #  If there's more than one instance of a bubble character
                   6653:         #  That's a double bubble; with positional notation we can
                   6654:         #  record all the bubbles filled in as well as the
                   6655:         #  fact this response consists of multiple bubbles.
                   6656:         #
1.691     raeburn  6657:         my $responsenum = $questnum-1;
                   6658:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6659:             $responsenum = $respnumlookup->{$questnum-1}
                   6660:         }
                   6661:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6662:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6663:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6664:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6665:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6666:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6667:             my $doubleerror = 0;
                   6668:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6669:                    (!$doubleerror)) {
                   6670:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6671:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6672:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6673:                if (length(@currarray) > 2) {
                   6674:                    $doubleerror = 1;
                   6675:                } 
                   6676:             }
                   6677:             if ($doubleerror) {
                   6678:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6679:             }
                   6680:         } else {
                   6681:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6682:         }
                   6683:         my $item = $ansnum;
                   6684:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6685:             $record->{"scantron.$item.answer"} = '';
                   6686:             $item ++;
                   6687:         }
1.447     foxr     6688: 
1.503     raeburn  6689:         my @ans=@array;
                   6690:         my $i=0;
                   6691:         my $increment = 0;
                   6692:         while ($#ans) {
                   6693:             $i+=length($ans[0]) + $increment;
                   6694:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6695:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6696:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6697:             shift(@ans);
                   6698:             $increment = 1;
                   6699:         }
                   6700:         $ansnum += $answers_needed;
1.82      albertel 6701:     }
1.503     raeburn  6702:     return $ansnum;
1.82      albertel 6703: }
                   6704: 
1.423     albertel 6705: =pod
                   6706: 
                   6707: =item scantron_add_delay
                   6708: 
                   6709:    Adds an error message that occurred during the grading phase to a
                   6710:    queue of messages to be shown after grading pass is complete
                   6711: 
                   6712:  Arguments:
1.424     albertel 6713:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6714:    $scanline    - the scanline that caused the error
                   6715:    $errormesage - the error message
                   6716:    $errorcode   - a numeric code for the error
                   6717: 
                   6718:  Side Effects:
1.424     albertel 6719:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6720: 
                   6721: =cut
                   6722: 
1.82      albertel 6723: sub scantron_add_delay {
1.140     albertel 6724:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6725:     push(@$delayqueue,
                   6726: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6727: 	  'ecode' => $errorcode }
                   6728: 	 );
1.82      albertel 6729: }
                   6730: 
1.423     albertel 6731: =pod
                   6732: 
                   6733: =item scantron_find_student
                   6734: 
1.424     albertel 6735:    Finds the username for the current scanline
                   6736: 
                   6737:   Arguments:
                   6738:    $scantron_record - hash result from scantron_parse_scanline
                   6739:    $scan_data       - hash of correction information 
                   6740:                       (see &scantron_getfile() form more information)
                   6741:    $idmap           - hash from &username_to_idmap()
                   6742:    $line            - number of current scanline
                   6743:  
                   6744:   Returns:
                   6745:    Either 'username:domain' or undef if unknown
                   6746: 
1.423     albertel 6747: =cut
                   6748: 
1.82      albertel 6749: sub scantron_find_student {
1.157     albertel 6750:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6751:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6752:     if ($scanID =~ /^\s*$/) {
                   6753:  	return &scan_data($scan_data,"$line.user");
                   6754:     }
1.83      albertel 6755:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6756:  	if (lc($id) eq lc($scanID)) {
                   6757:  	    return $$idmap{$id};
                   6758:  	}
1.83      albertel 6759:     }
                   6760:     return undef;
                   6761: }
                   6762: 
1.423     albertel 6763: =pod
                   6764: 
                   6765: =item scantron_filter
                   6766: 
1.424     albertel 6767:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6768:    hidden resources was selected
                   6769: 
1.423     albertel 6770: =cut
                   6771: 
1.83      albertel 6772: sub scantron_filter {
                   6773:     my ($curres)=@_;
1.331     albertel 6774: 
                   6775:     if (ref($curres) && $curres->is_problem()) {
                   6776: 	# if the user has asked to not have either hidden
                   6777: 	# or 'randomout' controlled resources to be graded
                   6778: 	# don't include them
                   6779: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6780: 	    && $curres->randomout) {
                   6781: 	    return 0;
                   6782: 	}
1.83      albertel 6783: 	return 1;
                   6784:     }
                   6785:     return 0;
1.82      albertel 6786: }
                   6787: 
1.423     albertel 6788: =pod
                   6789: 
                   6790: =item scantron_process_corrections
                   6791: 
1.424     albertel 6792:    Gets correction information out of submitted form data and corrects
                   6793:    the scanline
                   6794: 
1.423     albertel 6795: =cut
                   6796: 
1.157     albertel 6797: sub scantron_process_corrections {
                   6798:     my ($r) = @_;
1.754     raeburn  6799:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6800:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6801:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6802:     my $which=$env{'form.scantron_line'};
1.200     albertel 6803:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6804:     my ($skip,$err,$errmsg);
1.257     albertel 6805:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6806: 	$skip=1;
1.257     albertel 6807:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6808: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6809: 	    $env{'form.scantron_domain'};
1.157     albertel 6810: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6811: 	($line,$err,$errmsg)=
                   6812: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6813: 				     'ID',{'newid'=>$newid,
1.257     albertel 6814: 				    'username'=>$env{'form.scantron_username'},
                   6815: 				    'domain'=>$env{'form.scantron_domain'}});
                   6816:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6817: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6818: 	my $newCODE;
1.192     albertel 6819: 	my %args;
1.190     albertel 6820: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6821: 	    $newCODE='use_unfound';
1.190     albertel 6822: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6823: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6824: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6825: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6826: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6827: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6828: 	}
1.257     albertel 6829: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6830: 	    $args{'CODE_ignore_dup'}=1;
                   6831: 	}
                   6832: 	$args{'CODE'}=$newCODE;
1.186     albertel 6833: 	($line,$err,$errmsg)=
                   6834: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6835: 				     'CODE',\%args);
1.257     albertel 6836:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6837: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6838: 	    ($line,$err,$errmsg)=
                   6839: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6840: 					 $which,'answer',
                   6841: 					 { 'question'=>$question,
1.503     raeburn  6842: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6843:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6844: 	    if ($err) { last; }
                   6845: 	}
                   6846:     }
                   6847:     if ($err) {
1.703     bisitz   6848:         $r->print(
                   6849:             '<p class="LC_error">'
                   6850:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6851:                 $errmsg)
1.704     raeburn  6852:            .'</p>');
1.157     albertel 6853:     } else {
1.200     albertel 6854: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6855: 	&scantron_putfile($scanlines,$scan_data);
                   6856:     }
                   6857: }
                   6858: 
1.423     albertel 6859: =pod
                   6860: 
                   6861: =item reset_skipping_status
                   6862: 
1.424     albertel 6863:    Forgets the current set of remember skipped scanlines (and thus
                   6864:    reverts back to considering all lines in the
                   6865:    scantron_skipped_<filename> file)
                   6866: 
1.423     albertel 6867: =cut
                   6868: 
1.200     albertel 6869: sub reset_skipping_status {
                   6870:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6871:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6872:     &scantron_putfile(undef,$scan_data);
                   6873: }
                   6874: 
1.423     albertel 6875: =pod
                   6876: 
                   6877: =item start_skipping
                   6878: 
1.424     albertel 6879:    Marks a scanline to be skipped. 
                   6880: 
1.423     albertel 6881: =cut
                   6882: 
1.376     albertel 6883: sub start_skipping {
1.200     albertel 6884:     my ($scan_data,$i)=@_;
                   6885:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6886:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6887: 	$remembered{$i}=2;
                   6888:     } else {
                   6889: 	$remembered{$i}=1;
                   6890:     }
1.200     albertel 6891:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6892: }
                   6893: 
1.423     albertel 6894: =pod
                   6895: 
                   6896: =item should_be_skipped
                   6897: 
1.424     albertel 6898:    Checks whether a scanline should be skipped.
                   6899: 
1.423     albertel 6900: =cut
                   6901: 
1.200     albertel 6902: sub should_be_skipped {
1.376     albertel 6903:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6904:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6905: 	# not redoing old skips
1.376     albertel 6906: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6907: 	return 0;
                   6908:     }
                   6909:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6910: 
                   6911:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6912: 	return 0;
                   6913:     }
1.200     albertel 6914:     return 1;
                   6915: }
                   6916: 
1.423     albertel 6917: =pod
                   6918: 
                   6919: =item remember_current_skipped
                   6920: 
1.424     albertel 6921:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6922:    file and remembers them into scan_data for later use.
                   6923: 
1.423     albertel 6924: =cut
                   6925: 
1.200     albertel 6926: sub remember_current_skipped {
                   6927:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6928:     my %to_remember;
                   6929:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6930: 	if ($scanlines->{'skipped'}[$i]) {
                   6931: 	    $to_remember{$i}=1;
                   6932: 	}
                   6933:     }
1.376     albertel 6934: 
1.200     albertel 6935:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6936:     &scantron_putfile(undef,$scan_data);
                   6937: }
                   6938: 
1.423     albertel 6939: =pod
                   6940: 
                   6941: =item check_for_error
                   6942: 
1.424     albertel 6943:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6944:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6945:     something went wrong.
                   6946: 
1.423     albertel 6947: =cut
                   6948: 
1.200     albertel 6949: sub check_for_error {
                   6950:     my ($r,$result)=@_;
                   6951:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6952: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6953:     }
                   6954: }
1.157     albertel 6955: 
1.423     albertel 6956: =pod
                   6957: 
                   6958: =item scantron_warning_screen
                   6959: 
1.424     albertel 6960:    Interstitial screen to make sure the operator has selected the
                   6961:    correct options before we start the validation phase.
                   6962: 
1.423     albertel 6963: =cut
                   6964: 
1.203     albertel 6965: sub scantron_warning_screen {
1.650     raeburn  6966:     my ($button_text,$symb)=@_;
1.257     albertel 6967:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  6968:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6969:     my $CODElist;
1.284     albertel 6970:     if ($scantron_config{'CODElocation'} &&
                   6971: 	$scantron_config{'CODEstart'} &&
                   6972: 	$scantron_config{'CODElength'}) {
                   6973: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6974: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6975: 	$CODElist=
1.492     albertel 6976: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6977: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6978:     }
1.663     raeburn  6979:     my $lastbubblepoints;
                   6980:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6981:         $lastbubblepoints =
                   6982:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6983:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6984:     }
1.770     raeburn  6985:     return '
1.203     albertel 6986: <p>
1.492     albertel 6987: <span class="LC_warning">
1.705     raeburn  6988: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6989: </p>
                   6990: <table>
1.492     albertel 6991: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6992: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6993: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6994: </table>
1.680     raeburn  6995: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6996: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
1.770     raeburn  6997: ';
1.203     albertel 6998: }
                   6999: 
1.423     albertel 7000: =pod
                   7001: 
                   7002: =item scantron_do_warning
                   7003: 
1.424     albertel 7004:    Check if the operator has picked something for all required
                   7005:    fields. Error out if something is missing.
                   7006: 
1.423     albertel 7007: =cut
                   7008: 
1.203     albertel 7009: sub scantron_do_warning {
1.608     www      7010:     my ($r,$symb)=@_;
1.203     albertel 7011:     if (!$symb) {return '';}
1.324     albertel 7012:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7013:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7014:     if ( $env{'form.selectpage'} eq '' ||
                   7015: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7016: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7017: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7018: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7019: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7020: 	} 
1.257     albertel 7021: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7022: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.770     raeburn  7023: 	}
1.257     albertel 7024: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7025: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.770     raeburn  7026: 	}
1.237     albertel 7027:     } else {
1.650     raeburn  7028: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7029:         my ($checksec,@possibles) = &gradable_sections();
                   7030:         my $gradesections;
                   7031:         if ($checksec) {
                   7032:             my $file=$env{'form.scantron_selectfile'};
                   7033:             if (&valid_file($file)) {
                   7034:                 my %bysec = &scantron_get_sections();
                   7035:                 my $table;
                   7036:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7037:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7038:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7039:                              &Apache::loncommon::start_data_table_header_row().
                   7040:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7041:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7042:                     if ($bysec{'none'}) {
                   7043:                         $table .= &Apache::loncommon::start_data_table_row().
                   7044:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7045:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7046:                     }
                   7047:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7048:                         next if ($sec eq 'none');
                   7049:                         $table .= &Apache::loncommon::start_data_table_row().
                   7050:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7051:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7052:                     }
                   7053:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7054:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7055:                                       '<p>'.$table.'</p>';
                   7056:                     if (@possibles) {
                   7057:                         $gradesections .= '<p>'.
                   7058:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7059:                                               scalar(@possibles)).'<br />'.
                   7060:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7061:                                               '<i>'.$checksec.'</i>').' ';
                   7062:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7063:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7064:                         }
                   7065:                         $gradesections .= '</p>';
                   7066:                     }
                   7067:                 }
                   7068:             } else {
                   7069:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7070:             }
                   7071:         }
1.663     raeburn  7072:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7073: 	$r->print('
1.770     raeburn  7074: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7075: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7076: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7077: ');
1.237     albertel 7078:     }
1.614     www      7079:     $r->print("</form><br />");
1.203     albertel 7080:     return '';
                   7081: }
                   7082: 
1.423     albertel 7083: =pod
                   7084: 
                   7085: =item scantron_form_start
                   7086: 
1.424     albertel 7087:     html hidden input for remembering all selected grading options
                   7088: 
1.423     albertel 7089: =cut
                   7090: 
1.203     albertel 7091: sub scantron_form_start {
                   7092:     my ($max_bubble)=@_;
                   7093:     my $result= <<SCANTRONFORM;
                   7094: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7095:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7096:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7097:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7098:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7099:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7100:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7101:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7102:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7103:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7104: SCANTRONFORM
1.447     foxr     7105: 
                   7106:   my $line = 0;
                   7107:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7108:        my $chunk =
                   7109: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7110:        $chunk .=
                   7111: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7112:        $chunk .= 
                   7113:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7114:        $chunk .=
                   7115:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7116:        $chunk .=
                   7117:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7118:        $result .= $chunk;
                   7119:        $line++;
1.691     raeburn  7120:     }
1.203     albertel 7121:     return $result;
                   7122: }
                   7123: 
1.423     albertel 7124: =pod
                   7125: 
                   7126: =item scantron_validate_file
                   7127: 
1.659     raeburn  7128:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7129: 
                   7130:     Also processes any necessary information resets that need to
                   7131:     occur before validation begins (ignore previous corrections,
                   7132:     restarting the skipped records processing)
                   7133: 
1.423     albertel 7134: =cut
                   7135: 
1.157     albertel 7136: sub scantron_validate_file {
1.608     www      7137:     my ($r,$symb) = @_;
1.157     albertel 7138:     if (!$symb) {return '';}
1.324     albertel 7139:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7140:     
1.703     bisitz   7141:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7142:     # them when doing the corrections reset
1.257     albertel 7143:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7144: 	&reset_skipping_status();
                   7145:     }
1.257     albertel 7146:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7147: 	&remember_current_skipped();
1.257     albertel 7148: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7149:     }
                   7150: 
1.257     albertel 7151:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7152: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7153: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7154: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7155: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7156:     }
1.200     albertel 7157: 
1.257     albertel 7158:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7159: 	&scantron_process_corrections($r);
                   7160:     }
1.770     raeburn  7161: 
                   7162:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7163:     my ($checksec,@gradable);
                   7164:     if ($env{'request.course.sec'}) {
                   7165:         ($checksec,my @possibles) = &gradable_sections();
                   7166:         if ($checksec) {
                   7167:             if (@possibles) {
                   7168:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7169:                 if (@chosensecs) {
                   7170:                     foreach my $sec (@chosensecs) {
                   7171:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7172:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7173:                                 push(@gradable,$sec);
                   7174:                             }
                   7175:                         }
                   7176:                     }
                   7177:                 }
                   7178:             }
                   7179:             $r->print('<p><table>');
                   7180:             if (@gradable) {
                   7181:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7182:                 $r->print(
                   7183:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7184:             } else {
                   7185:                 $r->print(
                   7186:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7187:             }
                   7188:             $r->print('</table></p>');
                   7189:         }
                   7190:     }
                   7191:     $r->rflush();
                   7192: 
1.157     albertel 7193:     #get the student pick code ready
                   7194:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7195:     my $nav_error;
1.754     raeburn  7196:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7197:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7198:     if ($nav_error) {
                   7199:         $r->print(&navmap_errormsg());
                   7200:         return '';
                   7201:     }
1.203     albertel 7202:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7203:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7204:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7205:     }
1.157     albertel 7206:     $r->print($result);
                   7207:     
1.334     albertel 7208:     my @validate_phases=( 'sequence',
                   7209: 			  'ID',
1.157     albertel 7210: 			  'CODE',
                   7211: 			  'doublebubble',
                   7212: 			  'missingbubbles');
1.257     albertel 7213:     if (!$env{'form.validatepass'}) {
                   7214: 	$env{'form.validatepass'} = 0;
1.157     albertel 7215:     }
1.257     albertel 7216:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7217:     my %skipbysec=();
1.448     foxr     7218: 
1.157     albertel 7219:     my $stop=0;
                   7220:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7221: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7222: 	$r->rflush();
1.691     raeburn  7223:      
1.157     albertel 7224: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7225: 	{
                   7226: 	    no strict 'refs';
1.770     raeburn  7227:             my @extras=();
                   7228:             if ($validate_phases[$currentphase] eq 'ID') {
                   7229:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7230:             }
                   7231: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7232: 	}
                   7233:     }
                   7234:     if (!$stop) {
1.650     raeburn  7235: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7236:         my $secinfo;
                   7237:         if (keys(%skipbysec) > 0) {
                   7238:             my $seclist = '<ul>';
                   7239:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7240:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7241:             }
                   7242:             $seclist .= '</ul>';
                   7243:             $secinfo = '<p class="LC_info">'.
                   7244:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7245:                            $seclist).
                   7246:                        '</p>';
                   7247:         }
1.542     raeburn  7248: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7249:                   $secinfo.$warning.
1.542     raeburn  7250:                   &mt('Perform verification for each student after storage of submissions?').
                   7251:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7252:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7253:                   ('&nbsp;'x3).'<label>'.
                   7254:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7255:                   '</label></span><br />'.
                   7256:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7257:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7258:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7259:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7260:     } else {
                   7261: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7262: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7263:     }
                   7264:     if ($stop) {
1.334     albertel 7265: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7266: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7267: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7268: 
1.650     raeburn  7269: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
1.334     albertel 7270: 	} else {
1.503     raeburn  7271:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7272: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7273:             } else {
1.539     riegler  7274:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7275:             }
1.492     albertel 7276: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7277: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7278: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7279: 	}
1.157     albertel 7280:     }
1.614     www      7281:     $r->print(" </form><br />");
1.157     albertel 7282:     return '';
                   7283: }
                   7284: 
1.423     albertel 7285: 
                   7286: =pod
                   7287: 
                   7288: =item scantron_remove_file
                   7289: 
1.659     raeburn  7290:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7291:    scantron_original_<filename> is never removed
                   7292: 
                   7293: 
1.423     albertel 7294: =cut
                   7295: 
1.200     albertel 7296: sub scantron_remove_file {
1.192     albertel 7297:     my ($which)=@_;
1.257     albertel 7298:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7299:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7300:     my $file='scantron_';
1.200     albertel 7301:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7302: 	$file.=$which.'_';
1.192     albertel 7303:     } else {
                   7304: 	return 'refused';
                   7305:     }
1.257     albertel 7306:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7307:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7308: }
                   7309: 
1.423     albertel 7310: 
                   7311: =pod
                   7312: 
                   7313: =item scantron_remove_scan_data
                   7314: 
1.659     raeburn  7315:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7316:    data file.  (In the case that both the are doing skipped records we need
                   7317:    to remember the old skipped lines for the time being so that element
                   7318:    persists for a while.)
                   7319: 
1.423     albertel 7320: =cut
                   7321: 
1.200     albertel 7322: sub scantron_remove_scan_data {
1.257     albertel 7323:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7324:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7325:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7326:     my @todelete;
1.257     albertel 7327:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7328:     foreach my $key (@keys) {
                   7329: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7330: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7331: 		$key=~/remember_skipping/) {
                   7332: 		next;
                   7333: 	    }
1.192     albertel 7334: 	    push(@todelete,$key);
                   7335: 	}
                   7336:     }
1.200     albertel 7337:     my $result;
1.192     albertel 7338:     if (@todelete) {
1.491     albertel 7339: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7340: 				       \@todelete,$cdom,$cname);
                   7341:     } else {
                   7342: 	$result = 'ok';
1.192     albertel 7343:     }
                   7344:     return $result;
                   7345: }
                   7346: 
1.423     albertel 7347: 
                   7348: =pod
                   7349: 
                   7350: =item scantron_getfile
                   7351: 
1.659     raeburn  7352:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7353:     the scan_data hash
                   7354:   
                   7355:   Arguments:
                   7356:     None
                   7357: 
                   7358:   Returns:
                   7359:     2 hash references
                   7360: 
                   7361:      - first one has 
                   7362:          orig      -
                   7363:          corrected -
                   7364:          skipped   -  each of which points to an array ref of the specified
                   7365:                       file broken up into individual lines
                   7366:          count     - number of scanlines
                   7367:  
                   7368:      - second is the scan_data hash possible keys are
1.425     albertel 7369:        ($number refers to scanline numbered $number and thus the key affects
                   7370:         only that scanline
                   7371:         $bubline refers to the specific bubble line element and the aspects
                   7372:         refers to that specific bubble line element)
                   7373: 
                   7374:        $number.user - username:domain to use
                   7375:        $number.CODE_ignore_dup 
                   7376:                     - ignore the duplicate CODE error 
                   7377:        $number.useCODE
                   7378:                     - use the CODE in the scanline as is
                   7379:        $number.no_bubble.$bubline
                   7380:                     - it is valid that there is no bubbled in bubble
                   7381:                       at $number $bubline
                   7382:        remember_skipping
                   7383:                     - a frozen hash containing keys of $number and values
                   7384:                       of either 
                   7385:                         1 - we are on a 'do skipped records pass' and plan
                   7386:                             on processing this line
                   7387:                         2 - we are on a 'do skipped records pass' and this
                   7388:                             scanline has been marked to skip yet again
1.424     albertel 7389: 
1.423     albertel 7390: =cut
                   7391: 
1.157     albertel 7392: sub scantron_getfile {
1.200     albertel 7393:     #FIXME really would prefer a scantron directory
1.257     albertel 7394:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7396:     my $lines;
                   7397:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7398: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7399:     my %scanlines;
                   7400:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7401:     my $temp=$scanlines{'orig'};
                   7402:     $scanlines{'count'}=$#$temp;
                   7403: 
                   7404:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7405: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7406:     if ($lines eq '-1') {
                   7407: 	$scanlines{'corrected'}=[];
                   7408:     } else {
                   7409: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7410:     }
                   7411:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7412: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7413:     if ($lines eq '-1') {
                   7414: 	$scanlines{'skipped'}=[];
                   7415:     } else {
                   7416: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7417:     }
1.175     albertel 7418:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7419:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7420:     my %scan_data = @tmp;
                   7421:     return (\%scanlines,\%scan_data);
                   7422: }
                   7423: 
1.423     albertel 7424: =pod
                   7425: 
                   7426: =item lonnet_putfile
                   7427: 
1.424     albertel 7428:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7429: 
                   7430:  Arguments:
                   7431:    $contents - data to store
                   7432:    $filename - filename to store $contents into
                   7433: 
                   7434:  Returns:
                   7435:    result value from &Apache::lonnet::finishuserfileupload
                   7436: 
1.423     albertel 7437: =cut
                   7438: 
1.157     albertel 7439: sub lonnet_putfile {
                   7440:     my ($contents,$filename)=@_;
1.257     albertel 7441:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7442:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7443:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7444:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7445: 
                   7446: }
                   7447: 
1.423     albertel 7448: =pod
                   7449: 
                   7450: =item scantron_putfile
                   7451: 
1.659     raeburn  7452:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7453:     scan_data hash. (Does not modify the original version only the
                   7454:     corrected and skipped versions.
                   7455: 
                   7456:  Arguments:
                   7457:     $scanlines - hash ref that looks like the first return value from
                   7458:                  &scantron_getfile()
                   7459:     $scan_data - hash ref that looks like the second return value from
                   7460:                  &scantron_getfile()
                   7461: 
1.423     albertel 7462: =cut
                   7463: 
1.157     albertel 7464: sub scantron_putfile {
                   7465:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7466:     #FIXME really would prefer a scantron directory
1.257     albertel 7467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7469:     if ($scanlines) {
                   7470: 	my $prefix='scantron_';
1.157     albertel 7471: # no need to update orig, shouldn't change
                   7472: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7473: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7474: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7475: 			$prefix.'corrected_'.
1.257     albertel 7476: 			$env{'form.scantron_selectfile'});
1.200     albertel 7477: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7478: 			$prefix.'skipped_'.
1.257     albertel 7479: 			$env{'form.scantron_selectfile'});
1.200     albertel 7480:     }
1.175     albertel 7481:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7482: }
                   7483: 
1.423     albertel 7484: =pod
                   7485: 
                   7486: =item scantron_get_line
                   7487: 
1.424     albertel 7488:    Returns the correct version of the scanline
                   7489: 
                   7490:  Arguments:
                   7491:     $scanlines - hash ref that looks like the first return value from
                   7492:                  &scantron_getfile()
                   7493:     $scan_data - hash ref that looks like the second return value from
                   7494:                  &scantron_getfile()
                   7495:     $i         - number of the requested line (starts at 0)
                   7496: 
                   7497:  Returns:
                   7498:    A scanline, (either the original or the corrected one if it
                   7499:    exists), or undef if the requested scanline should be
                   7500:    skipped. (Either because it's an skipped scanline, or it's an
                   7501:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7502:    pass.
                   7503: 
1.423     albertel 7504: =cut
                   7505: 
1.157     albertel 7506: sub scantron_get_line {
1.200     albertel 7507:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7508:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7509:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7510:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7511:     return $scanlines->{'orig'}[$i]; 
                   7512: }
                   7513: 
1.423     albertel 7514: =pod
                   7515: 
                   7516: =item scantron_todo_count
                   7517: 
1.424     albertel 7518:     Counts the number of scanlines that need processing.
                   7519: 
                   7520:  Arguments:
                   7521:     $scanlines - hash ref that looks like the first return value from
                   7522:                  &scantron_getfile()
                   7523:     $scan_data - hash ref that looks like the second return value from
                   7524:                  &scantron_getfile()
                   7525: 
                   7526:  Returns:
                   7527:     $count - number of scanlines to process
                   7528: 
1.423     albertel 7529: =cut
                   7530: 
1.200     albertel 7531: sub get_todo_count {
                   7532:     my ($scanlines,$scan_data)=@_;
                   7533:     my $count=0;
                   7534:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7535: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7536: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7537: 	$count++;
                   7538:     }
                   7539:     return $count;
                   7540: }
                   7541: 
1.423     albertel 7542: =pod
                   7543: 
                   7544: =item scantron_put_line
                   7545: 
1.659     raeburn  7546:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7547:     data file.
                   7548: 
                   7549:  Arguments:
                   7550:     $scanlines - hash ref that looks like the first return value from
                   7551:                  &scantron_getfile()
                   7552:     $scan_data - hash ref that looks like the second return value from
                   7553:                  &scantron_getfile()
                   7554:     $i         - line number to update
                   7555:     $newline   - contents of the updated scanline
                   7556:     $skip      - if true make the line for skipping and update the
                   7557:                  'skipped' file
                   7558: 
1.423     albertel 7559: =cut
                   7560: 
1.157     albertel 7561: sub scantron_put_line {
1.200     albertel 7562:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7563:     if ($skip) {
                   7564: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7565: 	&start_skipping($scan_data,$i);
1.157     albertel 7566: 	return;
                   7567:     }
                   7568:     $scanlines->{'corrected'}[$i]=$newline;
                   7569: }
                   7570: 
1.423     albertel 7571: =pod
                   7572: 
                   7573: =item scantron_clear_skip
                   7574: 
1.424     albertel 7575:    Remove a line from the 'skipped' file
                   7576: 
                   7577:  Arguments:
                   7578:     $scanlines - hash ref that looks like the first return value from
                   7579:                  &scantron_getfile()
                   7580:     $scan_data - hash ref that looks like the second return value from
                   7581:                  &scantron_getfile()
                   7582:     $i         - line number to update
                   7583: 
1.423     albertel 7584: =cut
                   7585: 
1.376     albertel 7586: sub scantron_clear_skip {
                   7587:     my ($scanlines,$scan_data,$i)=@_;
                   7588:     if (exists($scanlines->{'skipped'}[$i])) {
                   7589: 	undef($scanlines->{'skipped'}[$i]);
                   7590: 	return 1;
                   7591:     }
                   7592:     return 0;
                   7593: }
                   7594: 
1.423     albertel 7595: =pod
                   7596: 
                   7597: =item scantron_filter_not_exam
                   7598: 
1.424     albertel 7599:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7600:    filter out resources that are not marked as 'exam' mode
                   7601: 
1.423     albertel 7602: =cut
                   7603: 
1.334     albertel 7604: sub scantron_filter_not_exam {
                   7605:     my ($curres)=@_;
                   7606:     
                   7607:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7608: 	# if the user has asked to not have either hidden
                   7609: 	# or 'randomout' controlled resources to be graded
                   7610: 	# don't include them
                   7611: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7612: 	    && $curres->randomout) {
                   7613: 	    return 0;
                   7614: 	}
                   7615: 	return 1;
                   7616:     }
                   7617:     return 0;
                   7618: }
                   7619: 
1.423     albertel 7620: =pod
                   7621: 
                   7622: =item scantron_validate_sequence
                   7623: 
1.424     albertel 7624:     Validates the selected sequence, checking for resource that are
                   7625:     not set to exam mode.
                   7626: 
1.423     albertel 7627: =cut
                   7628: 
1.334     albertel 7629: sub scantron_validate_sequence {
                   7630:     my ($r,$currentphase) = @_;
                   7631: 
                   7632:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7633:     unless (ref($navmap)) {
                   7634:         $r->print(&navmap_errormsg());
                   7635:         return (1,$currentphase);
                   7636:     }
1.334     albertel 7637:     my (undef,undef,$sequence)=
                   7638: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7639: 
                   7640:     my $map=$navmap->getResourceByUrl($sequence);
                   7641: 
                   7642:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7643:                                     value="ignore" />');
                   7644:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7645: 	my @resources=
                   7646: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7647: 	if (@resources) {
1.675     bisitz   7648: 	    $r->print(
                   7649:                 '<p class="LC_warning">'
                   7650:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7651:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7652:                    .' work correctly.')
                   7653:                .'</p>'
                   7654:             );
1.334     albertel 7655: 	    return (1,$currentphase);
                   7656: 	}
                   7657:     }
                   7658: 
                   7659:     return (0,$currentphase+1);
                   7660: }
                   7661: 
1.423     albertel 7662: 
                   7663: 
1.157     albertel 7664: sub scantron_validate_ID {
1.770     raeburn  7665:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7666:     
                   7667:     #get student info
                   7668:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7669:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7670:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7671: 
                   7672:     #get scantron line setup
1.754     raeburn  7673:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7674:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7675: 
                   7676:     my $nav_error;
1.649     raeburn  7677:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7678:     if ($nav_error) {
                   7679:         $r->print(&navmap_errormsg());
                   7680:         return(1,$currentphase);
                   7681:     }
1.157     albertel 7682: 
                   7683:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7684:     my $unsavedskips = 0;
1.157     albertel 7685:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7686: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7687: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7688: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7689: 						 $scan_data);
                   7690: 	my $id=$$scan_record{'scantron.ID'};
                   7691: 	my $found;
                   7692: 	foreach my $checkid (keys(%idmap)) {
                   7693: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7694: 	}
                   7695: 	if ($found) {
                   7696: 	    my $username=$idmap{$found};
1.770     raeburn  7697:             if ($checksec) {
                   7698:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7699:                     my $stusec = $classlist->{$username}->[$secidx];
                   7700:                     if ($stusec ne $checksec) {
                   7701:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7702:                             my $skip=1;
                   7703:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7704:                             if (ref($skipbysec) eq 'HASH') {
                   7705:                                 if ($stusec eq '') {
                   7706:                                     $skipbysec->{'none'} ++;
                   7707:                                 } else {
                   7708:                                     $skipbysec->{$stusec} ++;
                   7709:                                 }
                   7710:                             }
                   7711:                             $unsavedskips ++;
                   7712:                             next;
                   7713:                         }
                   7714:                     }
                   7715:                 }
                   7716:             }
1.157     albertel 7717: 	    if ($found{'ids'}{$found}) {
                   7718: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7719: 					 $line,'duplicateID',$found);
1.770     raeburn  7720:                 if ($unsavedskips) {
                   7721:                     &scantron_putfile($scanlines,$scan_data);
                   7722:                     $unsavedskips = 0;
                   7723:                 }
1.194     albertel 7724: 		return(1,$currentphase);
1.157     albertel 7725: 	    } elsif ($found{'usernames'}{$username}) {
                   7726: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7727: 					 $line,'duplicateID',$username);
1.770     raeburn  7728:                 if ($unsavedskips) {
                   7729:                     &scantron_putfile($scanlines,$scan_data);
                   7730:                     $unsavedskips = 0;
                   7731:                 }
1.194     albertel 7732: 		return(1,$currentphase);
1.157     albertel 7733: 	    }
1.186     albertel 7734: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7735: 	    $found{'ids'}{$found}++;
                   7736: 	    $found{'usernames'}{$username}++;
                   7737: 	} else {
                   7738: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7739: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7740:                 if (($checksec && $username ne '')) {
                   7741:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7742:                         my $stusec = $classlist->{$username}->[$secidx];
                   7743:                         if ($stusec ne $checksec) {
                   7744:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7745:                                 my $skip=1;
                   7746:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7747:                                 if (ref($skipbysec) eq 'HASH') {
                   7748:                                     if ($stusec eq '') {
                   7749:                                         $skipbysec->{'none'} ++;
                   7750:                                     } else {
                   7751:                                         $skipbysec->{$stusec} ++;
                   7752:                                     }
                   7753:                                 }
                   7754:                                 $unsavedskips ++;
                   7755:                                 next;
                   7756:                             }
                   7757:                         }
                   7758:                     }
                   7759: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7760: 		    &scantron_get_correction($r,$i,$scan_record,
                   7761: 					     \%scantron_config,
                   7762: 					     $line,'duplicateID',$username);
1.770     raeburn  7763:                     if ($unsavedskips) {
                   7764:                         &scantron_putfile($scanlines,$scan_data);
                   7765:                         $unsavedskips = 0;
                   7766:                     }
1.194     albertel 7767: 		    return(1,$currentphase);
1.157     albertel 7768: 		} elsif (!defined($username)) {
                   7769: 		    &scantron_get_correction($r,$i,$scan_record,
                   7770: 					     \%scantron_config,
                   7771: 					     $line,'incorrectID');
1.770     raeburn  7772:                     if ($unsavedskips) {
                   7773:                         &scantron_putfile($scanlines,$scan_data);
                   7774:                         $unsavedskips = 0;
                   7775:                     }
1.194     albertel 7776: 		    return(1,$currentphase);
1.157     albertel 7777: 		}
                   7778: 		$found{'usernames'}{$username}++;
                   7779: 	    } else {
                   7780: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7781: 					 $line,'incorrectID');
1.770     raeburn  7782:                 if ($unsavedskips) {
                   7783:                     &scantron_putfile($scanlines,$scan_data);
                   7784:                     $unsavedskips = 0;
                   7785:                 }
1.194     albertel 7786: 		return(1,$currentphase);
1.157     albertel 7787: 	    }
                   7788: 	}
                   7789:     }
1.770     raeburn  7790:     if ($unsavedskips) {
                   7791:         &scantron_putfile($scanlines,$scan_data);
                   7792:         $unsavedskips = 0;
                   7793:     }
1.157     albertel 7794:     return (0,$currentphase+1);
                   7795: }
                   7796: 
1.770     raeburn  7797: sub scantron_get_sections {
                   7798:     my %bysec;
                   7799:     if ($env{'form.scantron_format'} ne '') {
                   7800:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   7801:         my ($scanlines,$scan_data)=&scantron_getfile();
                   7802:         my $classlist=&Apache::loncoursedata::get_classlist();
                   7803:         my %idmap=&username_to_idmap($classlist);
                   7804:         foreach my $key (keys(%idmap)) {
                   7805:             my $lckey = lc($key);
                   7806:             $idmap{$lckey} = $idmap{$key};
                   7807:         }
                   7808:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   7809:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7810:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7811:             if ($line=~/^[\s\cz]*$/) { next; }
                   7812:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7813:                                                      $scan_data);
                   7814:             my $id=lc($$scan_record{'scantron.ID'});
                   7815:             if (exists($idmap{$id})) {
                   7816:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   7817:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   7818:                     if ($stusec eq '') {
                   7819:                         $bysec{'none'} ++;
                   7820:                     } else {
                   7821:                         $bysec{$stusec} ++;
                   7822:                     }
                   7823:                 }
                   7824:             }
                   7825:         }
                   7826:     }
                   7827:     return %bysec;
                   7828: }
1.423     albertel 7829: 
1.157     albertel 7830: sub scantron_get_correction {
1.691     raeburn  7831:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7832:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7833: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7834: #to show both the current line and the previous one and allow skipping
                   7835: #the previous one or the current one
                   7836: 
1.333     albertel 7837:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7838:         $r->print(
                   7839:             '<p class="LC_warning">'
                   7840:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7841:                 "<b>$error</b>",
                   7842:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7843:            ."</p> \n");
1.157     albertel 7844:     } else {
1.658     bisitz   7845:         $r->print(
                   7846:             '<p class="LC_warning">'
                   7847:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7848:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7849:            ."</p> \n");
                   7850:     }
                   7851:     my $message =
                   7852:         '<p>'
                   7853:        .&mt('The ID on the form is [_1]',
                   7854:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7855:        .'<br />'
1.665     raeburn  7856:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7857:             $$scan_record{'scantron.LastName'},
                   7858:             $$scan_record{'scantron.FirstName'})
                   7859:        .'</p>';
1.242     albertel 7860: 
1.157     albertel 7861:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7862:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7863:                            # Array populated for doublebubble or
                   7864:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7865:                            # to validate radio button checking   
                   7866: 
1.157     albertel 7867:     if ($error =~ /ID$/) {
1.186     albertel 7868: 	if ($error eq 'incorrectID') {
1.658     bisitz   7869:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7870: 		      "</p>\n");
1.157     albertel 7871: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7872:             $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 7873: 	}
1.242     albertel 7874: 	$r->print($message);
1.492     albertel 7875: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7876: 	$r->print("\n<ul><li> ");
                   7877: 	#FIXME it would be nice if this sent back the user ID and
                   7878: 	#could do partial userID matches
                   7879: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7880: 				       'scantron_username','scantron_domain'));
                   7881: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7882: 	$r->print("\n:\n".
1.257     albertel 7883: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7884: 
                   7885: 	$r->print('</li>');
1.186     albertel 7886:     } elsif ($error =~ /CODE$/) {
                   7887: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7888: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7889: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7890: 	    $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 7891: 	}
1.658     bisitz   7892: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7893: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7894:                  ."</p>\n");
1.242     albertel 7895: 	$r->print($message);
1.658     bisitz   7896: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7897: 	$r->print("\n<br /> ");
1.194     albertel 7898: 	my $i=0;
1.273     albertel 7899: 	if ($error eq 'incorrectCODE' 
                   7900: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7901: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7902: 	    if ($closest > 0) {
                   7903: 		foreach my $testcode (@{$closest}) {
                   7904: 		    my $checked='';
1.569     bisitz   7905: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7906: 		    $r->print("
                   7907:    <label>
1.569     bisitz   7908:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7909:        ".&mt("Use the similar CODE [_1] instead.",
                   7910: 	    "<b><tt>".$testcode."</tt></b>")."
                   7911:     </label>
                   7912:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7913: 		    $r->print("\n<br />");
                   7914: 		    $i++;
                   7915: 		}
1.194     albertel 7916: 	    }
                   7917: 	}
1.273     albertel 7918: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7919: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7920: 	    $r->print("
                   7921:     <label>
1.569     bisitz   7922:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7923:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7924: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7925:     </label>");
1.273     albertel 7926: 	    $r->print("\n<br />");
                   7927: 	}
1.194     albertel 7928: 
1.597     wenzelju 7929: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7930: function change_radio(field) {
1.190     albertel 7931:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7932:     var i;
                   7933:     for (i=0;i<slct.length;i++) {
                   7934:         if (slct[i].value==field) { slct[i].checked=true; }
                   7935:     }
                   7936: }
                   7937: ENDSCRIPT
1.187     albertel 7938: 	my $href="/adm/pickcode?".
1.359     www      7939: 	   "form=".&escape("scantronupload").
                   7940: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7941: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7942: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7943: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7944: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7945: 	    $r->print("
                   7946:     <label>
                   7947:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7948:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7949: 	     "<a target='_blank' href='$href'>","</a>")."
                   7950:     </label> 
1.558     bisitz   7951:     ".&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 7952: 	    $r->print("\n<br />");
                   7953: 	}
1.492     albertel 7954: 	$r->print("
                   7955:     <label>
                   7956:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7957:        ".&mt("Use [_1] as the CODE.",
                   7958: 	     "</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 7959: 	$r->print("\n<br /><br />");
1.157     albertel 7960:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7961: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7962: 
                   7963: 	# The form field scantron_questions is acutally a list of line numbers.
                   7964: 	# represented by this form so:
                   7965: 
1.691     raeburn  7966: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7967:                                                 $respnumlookup,$startline);
1.497     foxr     7968: 
1.157     albertel 7969: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7970: 		  $line_list.'" />');
1.242     albertel 7971: 	$r->print($message);
1.492     albertel 7972: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7973: 	foreach my $question (@{$arg}) {
1.503     raeburn  7974: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7975:                                                    $scan_record, $error,
                   7976:                                                    $randomorder,$randompick,
                   7977:                                                    $respnumlookup,$startline);
1.524     raeburn  7978:             push(@lines_to_correct,@linenums);
1.157     albertel 7979: 	}
1.503     raeburn  7980:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7981:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7982: 	$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 7983: 	$r->print($message);
1.492     albertel 7984: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7985: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7986: 
1.503     raeburn  7987: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7988: 	# a list of question numbers. Therefore:
                   7989: 	#
1.691     raeburn  7990: 
                   7991: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7992:                                                 $respnumlookup,$startline);
1.497     foxr     7993: 
1.157     albertel 7994: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7995: 		  $line_list.'" />');
1.157     albertel 7996: 	foreach my $question (@{$arg}) {
1.503     raeburn  7997: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7998:                                                    $scan_record, $error,
                   7999:                                                    $randomorder,$randompick,
                   8000:                                                    $respnumlookup,$startline);
1.524     raeburn  8001:             push(@lines_to_correct,@linenums);
1.157     albertel 8002: 	}
1.503     raeburn  8003:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8004:     } else {
                   8005: 	$r->print("\n<ul>");
                   8006:     }
                   8007:     $r->print("\n</li></ul>");
1.497     foxr     8008: }
                   8009: 
1.503     raeburn  8010: sub verify_bubbles_checked {
                   8011:     my (@ansnums) = @_;
                   8012:     my $ansnumstr = join('","',@ansnums);
                   8013:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8014:     &js_escape(\$warning);
1.767     raeburn  8015:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8016: function verify_bubble_radio(form) {
                   8017:     var ansnumArray = new Array ("$ansnumstr");
                   8018:     var need_bubble_count = 0;
                   8019:     for (var i=0; i<ansnumArray.length; i++) {
                   8020:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8021:             var bubble_picked = 0; 
                   8022:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8023:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8024:                     bubble_picked = 1;
                   8025:                 }
                   8026:             }
                   8027:             if (bubble_picked == 0) {
                   8028:                 need_bubble_count ++;
                   8029:             }
                   8030:         }
                   8031:     }
                   8032:     if (need_bubble_count) {
                   8033:         alert("$warning");
                   8034:         return;
                   8035:     }
                   8036:     form.submit(); 
                   8037: }
                   8038: ENDSCRIPT
                   8039:     return $output;
                   8040: }
                   8041: 
1.497     foxr     8042: =pod
                   8043: 
                   8044: =item  questions_to_line_list
1.157     albertel 8045: 
1.497     foxr     8046: Converts a list of questions into a string of comma separated
                   8047: line numbers in the answer sheet used by the questions.  This is
                   8048: used to fill in the scantron_questions form field.
                   8049: 
                   8050:   Arguments:
                   8051:      questions    - Reference to an array of questions.
1.691     raeburn  8052:      randomorder  - True if randomorder in use.
                   8053:      randompick   - True if randompick in use.
                   8054:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8055:                      for current line to question number used for same question
                   8056:                      in "Master Seqence" (as seen by Course Coordinator).
                   8057:      startline    - Reference to hash where key is question number (0 is first)
                   8058:                     and key is number of first bubble line for current student
                   8059:                     or code-based randompick and/or randomorder.
1.693     raeburn  8060: 
1.497     foxr     8061: =cut
                   8062: 
                   8063: 
                   8064: sub questions_to_line_list {
1.691     raeburn  8065:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8066:     my @lines;
                   8067: 
1.503     raeburn  8068:     foreach my $item (@{$questions}) {
                   8069:         my $question = $item;
                   8070:         my ($first,$count,$last);
                   8071:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8072:             $question = $1;
                   8073:             my $subquestion = $2;
1.691     raeburn  8074:             my $responsenum = $question-1;
                   8075:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8076:                 $responsenum = $respnumlookup->{$question-1};
                   8077:                 if (ref($startline) eq 'HASH') {
                   8078:                     $first = $startline->{$question-1} + 1;
                   8079:                 }
                   8080:             } else {
                   8081:                 $first = $first_bubble_line{$responsenum} + 1;
                   8082:             }
                   8083:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8084:             my $subcount = 1;
                   8085:             while ($subcount<$subquestion) {
                   8086:                 $first += $subans[$subcount-1];
                   8087:                 $subcount ++;
                   8088:             }
                   8089:             $count = $subans[$subquestion-1];
                   8090:         } else {
1.691     raeburn  8091:             my $responsenum = $question-1;
                   8092:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8093:                 $responsenum = $respnumlookup->{$question-1};
                   8094:                 if (ref($startline) eq 'HASH') {
                   8095:                     $first = $startline->{$question-1} + 1;
                   8096:                 }
                   8097:             } else {
                   8098:                 $first = $first_bubble_line{$responsenum} + 1;
                   8099:             }
                   8100: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8101:         }
1.506     raeburn  8102:         $last = $first+$count-1;
1.503     raeburn  8103:         push(@lines, ($first..$last));
1.497     foxr     8104:     }
                   8105:     return join(',', @lines);
                   8106: }
                   8107: 
                   8108: =pod 
                   8109: 
                   8110: =item prompt_for_corrections
                   8111: 
                   8112: Prompts for a potentially multiline correction to the
                   8113: user's bubbling (factors out common code from scantron_get_correction
                   8114: for multi and missing bubble cases).
                   8115: 
                   8116:  Arguments:
                   8117:    $r           - Apache request object.
                   8118:    $question    - The question number to prompt for.
                   8119:    $scan_config - The scantron file configuration hash.
                   8120:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8121:    $error       - Type of error
1.691     raeburn  8122:    $randomorder - True if randomorder in use.
                   8123:    $randompick  - True if randompick in use.
                   8124:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8125:                     for current line to question number used for same question
                   8126:                     in "Master Seqence" (as seen by Course Coordinator).
                   8127:    $startline   - Reference to hash where key is question number (0 is first)
                   8128:                   and value is number of first bubble line for current student
                   8129:                   or code-based randompick and/or randomorder.
                   8130: 
1.497     foxr     8131: 
                   8132:  Implicit inputs:
                   8133:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8134:                                   Numbered from 0 (but question numbers are from
                   8135:                                   1.
                   8136:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8137:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8138:                                   type problems render as separate sub-questions, 
1.503     raeburn  8139:                                   in exam mode. This hash contains a 
                   8140:                                   comma-separated list of the lines per 
                   8141:                                   sub-question.
1.510     raeburn  8142:    %responsetype_per_response   - essayresponse, formularesponse,
                   8143:                                   stringresponse, imageresponse, reactionresponse,
                   8144:                                   and organicresponse type problem parts can have
1.503     raeburn  8145:                                   multiple lines per response if the weight
                   8146:                                   assigned exceeds 10.  In this case, only
                   8147:                                   one bubble per line is permitted, but more 
                   8148:                                   than one line might contain bubbles, e.g.
                   8149:                                   bubbling of: line 1 - J, line 2 - J, 
                   8150:                                   line 3 - B would assign 22 points.  
1.497     foxr     8151: 
                   8152: =cut
                   8153: 
                   8154: sub prompt_for_corrections {
1.691     raeburn  8155:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8156:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8157:     my ($current_line,$lines);
                   8158:     my @linenums;
                   8159:     my $questionnum = $question;
1.691     raeburn  8160:     my ($first,$responsenum);
1.503     raeburn  8161:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8162:         $question = $1;
                   8163:         my $subquestion = $2;
1.691     raeburn  8164:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8165:             $responsenum = $respnumlookup->{$question-1};
                   8166:             if (ref($startline) eq 'HASH') {
                   8167:                 $first = $startline->{$question-1};
                   8168:             }
                   8169:         } else {
                   8170:             $responsenum = $question-1;
1.714     raeburn  8171:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8172:         }
                   8173:         $current_line = $first + 1 ;
                   8174:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8175:         my $subcount = 1;
                   8176:         while ($subcount<$subquestion) {
                   8177:             $current_line += $subans[$subcount-1];
                   8178:             $subcount ++;
                   8179:         }
                   8180:         $lines = $subans[$subquestion-1];
                   8181:     } else {
1.691     raeburn  8182:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8183:             $responsenum = $respnumlookup->{$question-1};
                   8184:             if (ref($startline) eq 'HASH') { 
                   8185:                 $first = $startline->{$question-1};
                   8186:             }
                   8187:         } else {
                   8188:             $responsenum = $question-1;
                   8189:             $first = $first_bubble_line{$responsenum};
                   8190:         }
                   8191:         $current_line = $first + 1;
                   8192:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8193:     }
1.497     foxr     8194:     if ($lines > 1) {
1.503     raeburn  8195:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8196:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8197:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8198:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8199:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8200:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8201:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8202:             $r->print(
                   8203:                 &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)
                   8204:                .'<br /><br />'
                   8205:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8206:                .'<br />'
                   8207:                .&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.')
                   8208:                .'<br />'
                   8209:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8210:                .'<br /><br />'
                   8211:             );
1.503     raeburn  8212:         } else {
                   8213:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8214:         }
1.497     foxr     8215:     }
                   8216:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8217:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8218: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8219: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8220:         push(@linenums,$current_line);
1.497     foxr     8221: 	$current_line++;
                   8222:     }
                   8223:     if ($lines > 1) {
                   8224: 	$r->print("<hr /><br />");
                   8225:     }
1.503     raeburn  8226:     return @linenums;
1.157     albertel 8227: }
1.423     albertel 8228: 
                   8229: =pod
                   8230: 
                   8231: =item scantron_bubble_selector
                   8232:   
                   8233:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8234:    possibly showing the existing the selected bubbles if known
1.423     albertel 8235: 
                   8236:  Arguments:
                   8237:     $r           - Apache request object
1.754     raeburn  8238:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8239:     $line        - Number of the line being displayed.
1.503     raeburn  8240:     $questionnum - Question number (may include subquestion)
                   8241:     $error       - Type of error.
1.497     foxr     8242:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8243: 
                   8244: =cut
                   8245: 
1.157     albertel 8246: sub scantron_bubble_selector {
1.503     raeburn  8247:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8248:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8249: 
                   8250:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8251:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8252:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8253:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8254:             $max=$$scan_config{'BubblesPerRow'};
                   8255:             if (($scmode eq 'number') && ($max > 10)) {
                   8256:                 $max = 10;
                   8257:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8258:                 $max = 26;
                   8259:             }
                   8260:         } else {
                   8261:             $max = 10;
                   8262:         }
                   8263:     }
1.274     albertel 8264: 
1.157     albertel 8265:     my @alphabet=('A'..'Z');
1.503     raeburn  8266:     $r->print(&Apache::loncommon::start_data_table().
                   8267:               &Apache::loncommon::start_data_table_row());
                   8268:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8269:     for (my $i=0;$i<$max+1;$i++) {
                   8270: 	$r->print("\n".'<td align="center">');
                   8271: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8272: 	else { $r->print('&nbsp;'); }
                   8273: 	$r->print('</td>');
                   8274:     }
1.503     raeburn  8275:     $r->print(&Apache::loncommon::end_data_table_row().
                   8276:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8277:     for (my $i=0;$i<$max;$i++) {
                   8278: 	$r->print("\n".
                   8279: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8280: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8281:     }
1.503     raeburn  8282:     my $nobub_checked = ' ';
                   8283:     if ($error eq 'missingbubble') {
                   8284:         $nobub_checked = ' checked = "checked" ';
                   8285:     }
                   8286:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8287: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8288:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8289:               $line.'" value="'.$questionnum.'" /></td>');
                   8290:     $r->print(&Apache::loncommon::end_data_table_row().
                   8291:               &Apache::loncommon::end_data_table());
1.157     albertel 8292: }
                   8293: 
1.423     albertel 8294: =pod
                   8295: 
                   8296: =item num_matches
                   8297: 
1.424     albertel 8298:    Counts the number of characters that are the same between the two arguments.
                   8299: 
                   8300:  Arguments:
                   8301:    $orig - CODE from the scanline
                   8302:    $code - CODE to match against
                   8303: 
                   8304:  Returns:
                   8305:    $count - integer count of the number of same characters between the
                   8306:             two arguments
                   8307: 
1.423     albertel 8308: =cut
                   8309: 
1.194     albertel 8310: sub num_matches {
                   8311:     my ($orig,$code) = @_;
                   8312:     my @code=split(//,$code);
                   8313:     my @orig=split(//,$orig);
                   8314:     my $same=0;
                   8315:     for (my $i=0;$i<scalar(@code);$i++) {
                   8316: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8317:     }
                   8318:     return $same;
                   8319: }
                   8320: 
1.423     albertel 8321: =pod
                   8322: 
                   8323: =item scantron_get_closely_matching_CODEs
                   8324: 
1.424     albertel 8325:    Cycles through all CODEs and finds the set that has the greatest
                   8326:    number of same characters as the provided CODE
                   8327: 
                   8328:  Arguments:
                   8329:    $allcodes - hash ref returned by &get_codes()
                   8330:    $CODE     - CODE from the current scanline
                   8331: 
                   8332:  Returns:
                   8333:    2 element list
                   8334:     - first elements is number of how closely matching the best fit is 
                   8335:       (5 means best set has 5 matching characters)
                   8336:     - second element is an arrary ref containing the set of valid CODEs
                   8337:       that best fit the passed in CODE
                   8338: 
1.423     albertel 8339: =cut
                   8340: 
1.194     albertel 8341: sub scantron_get_closely_matching_CODEs {
                   8342:     my ($allcodes,$CODE)=@_;
                   8343:     my @CODEs;
                   8344:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8345: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8346:     }
                   8347: 
                   8348:     return ($#CODEs,$CODEs[-1]);
                   8349: }
                   8350: 
1.423     albertel 8351: =pod
                   8352: 
                   8353: =item get_codes
                   8354: 
1.424     albertel 8355:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8356:    set of remembered CODEs.
                   8357: 
                   8358:  Arguments:
                   8359:   $old_name - name of the set of remembered CODEs
                   8360:   $cdom     - domain of the course
                   8361:   $cnum     - internal course name
                   8362: 
                   8363:  Returns:
                   8364:   %allcodes - keys are the valid CODEs, values are all 1
                   8365: 
1.423     albertel 8366: =cut
                   8367: 
1.194     albertel 8368: sub get_codes {
1.280     foxr     8369:     my ($old_name, $cdom, $cnum) = @_;
                   8370:     if (!$old_name) {
                   8371: 	$old_name=$env{'form.scantron_CODElist'};
                   8372:     }
                   8373:     if (!$cdom) {
                   8374: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8375:     }
                   8376:     if (!$cnum) {
                   8377: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8378:     }
1.278     albertel 8379:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8380: 				    $cdom,$cnum);
                   8381:     my %allcodes;
                   8382:     if ($result{"type\0$old_name"} eq 'number') {
                   8383: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8384:     } else {
                   8385: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8386:     }
1.194     albertel 8387:     return %allcodes;
                   8388: }
                   8389: 
1.423     albertel 8390: =pod
                   8391: 
                   8392: =item scantron_validate_CODE
                   8393: 
1.424     albertel 8394:    Validates all scanlines in the selected file to not have any
                   8395:    invalid or underspecified CODEs and that none of the codes are
                   8396:    duplicated if this was requested.
                   8397: 
1.423     albertel 8398: =cut
                   8399: 
1.157     albertel 8400: sub scantron_validate_CODE {
                   8401:     my ($r,$currentphase) = @_;
1.754     raeburn  8402:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8403:     if ($scantron_config{'CODElocation'} &&
                   8404: 	$scantron_config{'CODEstart'} &&
                   8405: 	$scantron_config{'CODElength'}) {
1.257     albertel 8406: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8407: 	    &FIXME_blow_up()
                   8408: 	}
                   8409:     } else {
                   8410: 	return (0,$currentphase+1);
                   8411:     }
                   8412:     
                   8413:     my %usedCODEs;
                   8414: 
1.194     albertel 8415:     my %allcodes=&get_codes();
1.186     albertel 8416: 
1.582     raeburn  8417:     my $nav_error;
1.649     raeburn  8418:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8419:     if ($nav_error) {
                   8420:         $r->print(&navmap_errormsg());
                   8421:         return(1,$currentphase);
                   8422:     }
1.447     foxr     8423: 
1.186     albertel 8424:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8425:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8426: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8427: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8428: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8429: 						 $scan_data);
                   8430: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8431: 	my $error=0;
1.224     albertel 8432: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8433: 	    &scantron_get_correction($r,$i,$scan_record,
                   8434: 				     \%scantron_config,
                   8435: 				     $line,'incorrectCODE',\%allcodes);
                   8436: 	    return(1,$currentphase);
                   8437: 	}
1.221     albertel 8438: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8439: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8440: 	    &scantron_get_correction($r,$i,$scan_record,
                   8441: 				     \%scantron_config,
1.194     albertel 8442: 				     $line,'incorrectCODE',\%allcodes);
                   8443: 	    return(1,$currentphase);
1.186     albertel 8444: 	}
1.214     albertel 8445: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8446: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8447: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8448: 	    &scantron_get_correction($r,$i,$scan_record,
                   8449: 				     \%scantron_config,
1.194     albertel 8450: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8451: 	    return(1,$currentphase);
1.186     albertel 8452: 	}
1.524     raeburn  8453: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8454:     }
1.157     albertel 8455:     return (0,$currentphase+1);
                   8456: }
                   8457: 
1.423     albertel 8458: =pod
                   8459: 
                   8460: =item scantron_validate_doublebubble
                   8461: 
1.424     albertel 8462:    Validates all scanlines in the selected file to not have any
                   8463:    bubble lines with multiple bubbles marked.
                   8464: 
1.423     albertel 8465: =cut
                   8466: 
1.157     albertel 8467: sub scantron_validate_doublebubble {
                   8468:     my ($r,$currentphase) = @_;
                   8469:     #get student info
                   8470:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8471:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8472:     my (undef,undef,$sequence)=
                   8473:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8474: 
                   8475:     #get scantron line setup
1.754     raeburn  8476:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8477:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8478: 
                   8479:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8480:     unless (ref($navmap)) {
                   8481:         $r->print(&navmap_errormsg());
                   8482:         return(1,$currentphase);
                   8483:     }
                   8484:     my $map=$navmap->getResourceByUrl($sequence);
                   8485:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8486:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8487:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8488:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8489: 
1.583     raeburn  8490:     my $nav_error;
1.691     raeburn  8491:     if (ref($map)) {
                   8492:         $randomorder = $map->randomorder();
                   8493:         $randompick = $map->randompick();
                   8494:         if ($randomorder || $randompick) {
                   8495:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8496:             if ($nav_error) {
                   8497:                 $r->print(&navmap_errormsg());
                   8498:                 return(1,$currentphase);
                   8499:             }
                   8500:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8501:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8502:         }
                   8503:     } else {
                   8504:         $r->print(&navmap_errormsg());
                   8505:         return(1,$currentphase);
                   8506:     }
                   8507: 
1.649     raeburn  8508:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8509:     if ($nav_error) {
                   8510:         $r->print(&navmap_errormsg());
                   8511:         return(1,$currentphase);
                   8512:     }
1.447     foxr     8513: 
1.157     albertel 8514:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8515: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8516: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8517: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8518: 						 $scan_data,undef,\%idmap,$randomorder,
                   8519:                                                  $randompick,$sequence,\@master_seq,
                   8520:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8521:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8522: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8523: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8524: 				 'doublebubble',
1.691     raeburn  8525: 				 $$scan_record{'scantron.doubleerror'},
                   8526:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8527:     	return (1,$currentphase);
                   8528:     }
                   8529:     return (0,$currentphase+1);
                   8530: }
                   8531: 
1.423     albertel 8532: 
1.503     raeburn  8533: sub scantron_get_maxbubble {
1.649     raeburn  8534:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8535:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8536: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8537: 	&restore_bubble_lines();
1.257     albertel 8538: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8539:     }
1.330     albertel 8540: 
1.447     foxr     8541:     my (undef, undef, $sequence) =
1.257     albertel 8542: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8543: 
1.447     foxr     8544:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8545:     unless (ref($navmap)) {
                   8546:         if (ref($nav_error)) {
                   8547:             $$nav_error = 1;
                   8548:         }
1.591     raeburn  8549:         return;
1.582     raeburn  8550:     }
1.191     albertel 8551:     my $map=$navmap->getResourceByUrl($sequence);
                   8552:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8553:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8554: 
                   8555:     &Apache::lonxml::clear_problem_counter();
                   8556: 
1.557     raeburn  8557:     my $uname       = $env{'user.name'};
                   8558:     my $udom        = $env{'user.domain'};
1.435     foxr     8559:     my $cid         = $env{'request.course.id'};
                   8560:     my $total_lines = 0;
                   8561:     %bubble_lines_per_response = ();
1.447     foxr     8562:     %first_bubble_line         = ();
1.503     raeburn  8563:     %subdivided_bubble_lines   = ();
                   8564:     %responsetype_per_response = ();
1.691     raeburn  8565:     %masterseq_id_responsenum  = ();
1.554     raeburn  8566: 
1.447     foxr     8567:     my $response_number = 0;
                   8568:     my $bubble_line     = 0;
1.191     albertel 8569:     foreach my $resource (@resources) {
1.691     raeburn  8570:         my $resid = $resource->id(); 
1.672     raeburn  8571:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8572:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8573:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8574: 	    foreach my $part_id (@{$parts}) {
                   8575:                 my $lines;
                   8576: 
                   8577: 	        # TODO - make this a persistent hash not an array.
                   8578: 
                   8579:                 # optionresponse, matchresponse and rankresponse type items 
                   8580:                 # render as separate sub-questions in exam mode.
                   8581:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8582:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8583:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8584:                     my ($numbub,$numshown);
                   8585:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8586:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8587:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8588:                         }
                   8589:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8590:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8591:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8592:                         }
                   8593:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8594:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8595:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8596:                         }
                   8597:                     }
                   8598:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8599:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8600:                     }
1.649     raeburn  8601:                     my $bubbles_per_row =
                   8602:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8603:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8604:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8605:                         $inner_bubble_lines++;
                   8606:                     }
                   8607:                     for (my $i=0; $i<$numshown; $i++) {
                   8608:                         $subdivided_bubble_lines{$response_number} .= 
                   8609:                             $inner_bubble_lines.',';
                   8610:                     }
                   8611:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8612:                     $lines = $numshown * $inner_bubble_lines;
                   8613:                 } else {
                   8614:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8615:                 }
1.542     raeburn  8616: 
                   8617:                 $first_bubble_line{$response_number} = $bubble_line;
                   8618: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8619:                 $responsetype_per_response{$response_number} = 
                   8620:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8621:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8622: 	        $response_number++;
                   8623: 
                   8624: 	        $bubble_line +=  $lines;
                   8625: 	        $total_lines +=  $lines;
                   8626: 	    }
                   8627:         }
                   8628:     }
1.552     raeburn  8629:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8630: 
                   8631:     &save_bubble_lines();
                   8632:     $env{'form.scantron_maxbubble'} =
                   8633: 	$total_lines;
                   8634:     return $env{'form.scantron_maxbubble'};
                   8635: }
1.523     raeburn  8636: 
1.649     raeburn  8637: sub bubblesheet_bubbles_per_row {
                   8638:     my ($scantron_config) = @_;
                   8639:     my $bubbles_per_row;
                   8640:     if (ref($scantron_config) eq 'HASH') {
                   8641:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8642:     }
                   8643:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8644:         $bubbles_per_row = 10;
                   8645:     }
                   8646:     return $bubbles_per_row;
                   8647: }
                   8648: 
1.157     albertel 8649: sub scantron_validate_missingbubbles {
                   8650:     my ($r,$currentphase) = @_;
                   8651:     #get student info
                   8652:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8653:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8654:     my (undef,undef,$sequence)=
                   8655:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8656: 
                   8657:     #get scantron line setup
1.754     raeburn  8658:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8659:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8660: 
                   8661:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8662:     unless (ref($navmap)) {
                   8663:         $r->print(&navmap_errormsg());
                   8664:         return(1,$currentphase);
                   8665:     }
                   8666: 
                   8667:     my $map=$navmap->getResourceByUrl($sequence);
                   8668:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8669:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8670:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8671:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8672: 
1.582     raeburn  8673:     my $nav_error;
1.691     raeburn  8674:     if (ref($map)) {
                   8675:         $randomorder = $map->randomorder();
                   8676:         $randompick = $map->randompick();
                   8677:         if ($randomorder || $randompick) {
                   8678:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8679:             if ($nav_error) {
                   8680:                 $r->print(&navmap_errormsg());
                   8681:                 return(1,$currentphase);
                   8682:             }
                   8683:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8684:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8685:         }
                   8686:     } else {
                   8687:         $r->print(&navmap_errormsg());
                   8688:         return(1,$currentphase);
                   8689:     }
                   8690: 
                   8691: 
1.649     raeburn  8692:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8693:     if ($nav_error) {
1.691     raeburn  8694:         $r->print(&navmap_errormsg());
1.693     raeburn  8695:         return(1,$currentphase);
1.582     raeburn  8696:     }
1.691     raeburn  8697: 
1.157     albertel 8698:     if (!$max_bubble) { $max_bubble=2**31; }
                   8699:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8700: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8701: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8702: 	my $scan_record =
                   8703:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8704: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8705:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8706:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8707: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8708: 	my @to_correct;
1.470     foxr     8709: 	
                   8710: 	# Probably here's where the error is...
                   8711: 
1.157     albertel 8712: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8713:             my $lastbubble;
                   8714:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8715:                my $question = $1;
                   8716:                my $subquestion = $2;
1.691     raeburn  8717:                my ($first,$responsenum);
                   8718:                if ($randomorder || $randompick) {
                   8719:                    $responsenum = $respnumlookup{$question-1};
                   8720:                    $first = $startline{$question-1};
                   8721:                } else {
                   8722:                    $responsenum = $question-1; 
                   8723:                    $first = $first_bubble_line{$responsenum};
                   8724:                }
                   8725:                if (!defined($first)) { next; }
                   8726:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8727:                my $subcount = 1;
                   8728:                while ($subcount<$subquestion) {
                   8729:                    $first += $subans[$subcount-1];
                   8730:                    $subcount ++;
                   8731:                }
                   8732:                my $count = $subans[$subquestion-1];
                   8733:                $lastbubble = $first + $count;
                   8734:             } else {
1.691     raeburn  8735:                my ($first,$responsenum);
                   8736:                if ($randomorder || $randompick) {
                   8737:                    $responsenum = $respnumlookup{$missing-1};
                   8738:                    $first = $startline{$missing-1};
                   8739:                } else {
                   8740:                    $responsenum = $missing-1;
                   8741:                    $first = $first_bubble_line{$responsenum};
                   8742:                }
                   8743:                if (!defined($first)) { next; }
                   8744:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8745:             }
                   8746:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8747: 	    push(@to_correct,$missing);
                   8748: 	}
                   8749: 	if (@to_correct) {
                   8750: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8751: 				     $line,'missingbubble',\@to_correct,
                   8752:                                      $randomorder,$randompick,\%respnumlookup,
                   8753:                                      \%startline);
1.157     albertel 8754: 	    return (1,$currentphase);
                   8755: 	}
                   8756: 
                   8757:     }
                   8758:     return (0,$currentphase+1);
                   8759: }
                   8760: 
1.663     raeburn  8761: sub hand_bubble_option {
                   8762:     my (undef, undef, $sequence) =
                   8763:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8764:     return if ($sequence eq '');
                   8765:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8766:     unless (ref($navmap)) {
                   8767:         return;
                   8768:     }
                   8769:     my $needs_hand_bubbles;
                   8770:     my $map=$navmap->getResourceByUrl($sequence);
                   8771:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8772:     foreach my $res (@resources) {
                   8773:         if (ref($res)) {
                   8774:             if ($res->is_problem()) {
                   8775:                 my $partlist = $res->parts();
                   8776:                 foreach my $part (@{ $partlist }) {
                   8777:                     my @types = $res->responseType($part);
                   8778:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8779:                         $needs_hand_bubbles = 1;
                   8780:                         last;
                   8781:                     }
                   8782:                 }
                   8783:             }
                   8784:         }
                   8785:     }
                   8786:     if ($needs_hand_bubbles) {
1.754     raeburn  8787:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8788:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8789:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8790:                &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 />').
                   8791:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
1.722     raeburn  8792:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8793:     }
                   8794:     return;
                   8795: }
1.423     albertel 8796: 
1.82      albertel 8797: sub scantron_process_students {
1.608     www      8798:     my ($r,$symb) = @_;
1.513     foxr     8799: 
1.257     albertel 8800:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8801:     if (!$symb) {
                   8802: 	return '';
                   8803:     }
1.324     albertel 8804:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8805: 
1.754     raeburn  8806:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8807:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8808:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8809:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8810:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8811:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8812:     unless (ref($navmap)) {
                   8813:         $r->print(&navmap_errormsg());
                   8814:         return '';
1.691     raeburn  8815:     }
1.83      albertel 8816:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8817:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8818:         %grader_randomlists_by_symb);
1.677     raeburn  8819:     if (ref($map)) {
                   8820:         $randomorder = $map->randomorder();
1.689     raeburn  8821:         $randompick = $map->randompick();
1.691     raeburn  8822:     } else {
                   8823:         $r->print(&navmap_errormsg());
                   8824:         return '';
1.677     raeburn  8825:     }
1.691     raeburn  8826:     my $nav_error;
1.83      albertel 8827:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8828:     if ($randomorder || $randompick) {
                   8829:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8830:         if ($nav_error) {
                   8831:             $r->print(&navmap_errormsg());
                   8832:             return '';
                   8833:         }
                   8834:     }
1.557     raeburn  8835:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8836:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8837: 
1.554     raeburn  8838:     my ($uname,$udom);
1.82      albertel 8839:     my $result= <<SCANTRONFORM;
1.81      albertel 8840: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8841:   <input type="hidden" name="command" value="scantron_configphase" />
                   8842:   $default_form_data
                   8843: SCANTRONFORM
1.82      albertel 8844:     $r->print($result);
                   8845: 
1.770     raeburn  8846:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 8847:     my @delayqueue;
1.542     raeburn  8848:     my (%completedstudents,%scandata);
1.770     raeburn  8849: 
1.520     www      8850:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8851:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8852:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8853:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8854:     $r->print('<br />');
1.140     albertel 8855:     my $start=&Time::HiRes::time();
1.158     albertel 8856:     my $i=-1;
1.542     raeburn  8857:     my $started;
1.447     foxr     8858: 
1.649     raeburn  8859:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8860:     if ($nav_error) {
                   8861:         $r->print(&navmap_errormsg());
                   8862:         return '';
                   8863:     }
                   8864: 
1.513     foxr     8865:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8866:     # the user and return.
                   8867: 
                   8868:     if ($ssi_error) {
                   8869: 	$r->print("</form>");
                   8870: 	&ssi_print_error($r);
1.520     www      8871:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8872: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8873:     }
1.447     foxr     8874: 
1.755     raeburn  8875:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8876:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8877:     my %orderedforcode;
1.542     raeburn  8878: 
1.157     albertel 8879:     while ($i<$scanlines->{'count'}) {
                   8880:  	($uname,$udom)=('','');
                   8881:  	$i++;
1.200     albertel 8882:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8883:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8884: 	if ($started) {
1.667     www      8885: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8886: 	}
                   8887: 	$started=1;
1.691     raeburn  8888:         my %respnumlookup = ();
                   8889:         my %startline = ();
                   8890:         my $total;
1.157     albertel 8891:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8892:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8893:                                                  $randompick,$sequence,\@master_seq,
                   8894:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8895:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8896:                                                  \$total);
1.157     albertel 8897:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8898:  					      \%idmap,$i)) {
                   8899:   	    &scantron_add_delay(\@delayqueue,$line,
                   8900:  				'Unable to find a student that matches',1);
                   8901:  	    next;
                   8902:   	}
                   8903:  	if (exists $completedstudents{$uname}) {
                   8904:  	    &scantron_add_delay(\@delayqueue,$line,
                   8905:  				'Student '.$uname.' has multiple sheets',2);
                   8906:  	    next;
                   8907:  	}
1.677     raeburn  8908:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  8909:         if (($checksec ne '') && ($checksec ne $usec)) {
                   8910:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   8911:                 &scantron_add_delay(\@delayqueue,$line,
                   8912:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   8913:                 next;
                   8914:             }
                   8915:         }
1.677     raeburn  8916:         my $user = $uname.':'.$usec;
1.157     albertel 8917:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8918: 
1.677     raeburn  8919:         my $scancode;
                   8920:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8921:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8922:             $scancode = $scan_record->{'scantron.CODE'};
                   8923:         } else {
                   8924:             $scancode = '';
                   8925:         }
                   8926: 
                   8927:         my @mapresources = @resources;
1.689     raeburn  8928:         if ($randomorder || $randompick) {
1.678     raeburn  8929:             @mapresources = 
1.691     raeburn  8930:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8931:                              \%orderedforcode);
1.677     raeburn  8932:         }
1.586     raeburn  8933:         my (%partids_by_symb,$res_error);
1.677     raeburn  8934:         foreach my $resource (@mapresources) {
1.586     raeburn  8935:             my $ressymb;
                   8936:             if (ref($resource)) {
                   8937:                 $ressymb = $resource->symb();
                   8938:             } else {
                   8939:                 $res_error = 1;
                   8940:                 last;
                   8941:             }
1.557     raeburn  8942:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8943:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8944:                 my $currcode;
                   8945:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8946:                     $currcode = $scancode;
                   8947:                 }
1.557     raeburn  8948:                 my ($analysis,$parts) =
1.672     raeburn  8949:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8950:                                               $uname,$udom,undef,$bubbles_per_row,
                   8951:                                               $currcode);
1.557     raeburn  8952:                 $partids_by_symb{$ressymb} = $parts;
                   8953:             } else {
                   8954:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8955:             }
1.554     raeburn  8956:         }
                   8957: 
1.586     raeburn  8958:         if ($res_error) {
                   8959:             &scantron_add_delay(\@delayqueue,$line,
                   8960:                                 'An error occurred while grading student '.$uname,2);
                   8961:             next;
                   8962:         }
                   8963: 
1.330     albertel 8964: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8965:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8966: 
                   8967: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8968: 	    &scantron_putfile($scanlines,$scan_data);
                   8969: 	}
1.161     albertel 8970: 	
1.542     raeburn  8971:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8972:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8973:                                    $bubbles_per_row,$randomorder,$randompick,
                   8974:                                    \%respnumlookup,\%startline) 
                   8975:             eq 'ssi_error') {
1.542     raeburn  8976:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8977:             $r->print("</form>");
                   8978:             &ssi_print_error($r);
                   8979:             &Apache::lonnet::remove_lock($lock);
                   8980:             return '';      # Why return ''?  Beats me.
                   8981:         }
1.513     foxr     8982: 
1.692     raeburn  8983:         if (($scancode) && ($randomorder || $randompick)) {
                   8984:             my $parmresult =
                   8985:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8986:                                                        '0_examcode',2,$scancode,
                   8987:                                                        'string_examcode',$uname,
                   8988:                                                        $udom);
                   8989:         }
1.140     albertel 8990: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8991:         if ($env{'form.verifyrecord'}) {
                   8992:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8993:             if ($randompick) {
                   8994:                 if ($total) {
                   8995:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8996:                 }
                   8997:             }
                   8998: 
1.542     raeburn  8999:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9000:             chomp($studentdata);
                   9001:             $studentdata =~ s/\r$//;
                   9002:             my $studentrecord = '';
                   9003:             my $counter = -1;
1.677     raeburn  9004:             foreach my $resource (@mapresources) {
1.554     raeburn  9005:                 my $ressymb = $resource->symb();
1.542     raeburn  9006:                 ($counter,my $recording) =
                   9007:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9008:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9009:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9010:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9011:                 $studentrecord .= $recording;
                   9012:             }
                   9013:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9014:                 &Apache::lonxml::clear_problem_counter();
                   9015:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9016:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9017:                                            $bubbles_per_row,$randomorder,$randompick,
                   9018:                                            \%respnumlookup,\%startline) 
                   9019:                     eq 'ssi_error') {
1.554     raeburn  9020:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9021:                     $r->print("</form>");
                   9022:                     &ssi_print_error($r);
                   9023:                     &Apache::lonnet::remove_lock($lock);
                   9024:                     delete($completedstudents{$uname});
                   9025:                     return '';
                   9026:                 }
1.542     raeburn  9027:                 $counter = -1;
                   9028:                 $studentrecord = '';
1.677     raeburn  9029:                 foreach my $resource (@mapresources) {
1.554     raeburn  9030:                     my $ressymb = $resource->symb();
1.542     raeburn  9031:                     ($counter,my $recording) =
                   9032:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9033:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9034:                                                  \%scantron_config,\%lettdig,$numletts,
                   9035:                                                  $randomorder,$randompick,\%respnumlookup,
                   9036:                                                  \%startline);
1.542     raeburn  9037:                     $studentrecord .= $recording;
                   9038:                 }
                   9039:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9040:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9041:                     if ($scancode eq '') {
1.658     bisitz   9042:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9043:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9044:                     } else {
1.658     bisitz   9045:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9046:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9047:                     }
                   9048:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9049:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9050:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9051:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9052:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9053:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9054:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9055:                               &Apache::loncommon::end_data_table_row().
                   9056:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9057:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9058:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9059:                               &Apache::loncommon::end_data_table_row().
                   9060:                               &Apache::loncommon::end_data_table().'</p>');
                   9061:                 } else {
                   9062:                     $r->print('<br /><span class="LC_warning">'.
                   9063:                              &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 />'.
                   9064:                              &mt("As a consequence, this user's submission history records two tries.").
                   9065:                                  '</span><br />');
                   9066:                 }
                   9067:             }
                   9068:         }
1.543     raeburn  9069:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9070:     } continue {
1.330     albertel 9071: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9072: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9073:     }
1.140     albertel 9074:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9075:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9076: #    my $lasttime = &Time::HiRes::time()-$start;
                   9077: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9078: 
1.200     albertel 9079:     $r->print("</form>");
1.157     albertel 9080:     return '';
1.75      albertel 9081: }
1.157     albertel 9082: 
1.557     raeburn  9083: sub graders_resources_pass {
1.649     raeburn  9084:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9085:         $bubbles_per_row) = @_;
1.557     raeburn  9086:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9087:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9088:         foreach my $resource (@{$resources}) {
                   9089:             my $ressymb = $resource->symb();
                   9090:             my ($analysis,$parts) =
                   9091:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9092:                                           $env{'user.name'},$env{'user.domain'},
                   9093:                                           1,$bubbles_per_row);
1.557     raeburn  9094:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9095:             if (ref($analysis) eq 'HASH') {
                   9096:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9097:                     $grader_randomlists_by_symb->{$ressymb} =
                   9098:                         $analysis->{'parts_withrandomlist'};
                   9099:                 }
                   9100:             }
                   9101:         }
                   9102:     }
                   9103:     return;
                   9104: }
                   9105: 
1.678     raeburn  9106: =pod
                   9107: 
                   9108: =item users_order
                   9109: 
                   9110:   Returns array of resources in current map, ordered based on either CODE,
                   9111:   if this is a CODEd exam, or based on student's identity if this is a 
                   9112:   "NAMEd" exam.
                   9113: 
1.691     raeburn  9114:   Should be used when randomorder and/or randompick applied when the 
                   9115:   corresponding exam was printed, prior to students completing bubblesheets 
                   9116:   for the version of the exam the student received.
1.678     raeburn  9117: 
                   9118: =cut
                   9119: 
                   9120: sub users_order  {
1.691     raeburn  9121:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9122:     my @mapresources;
1.691     raeburn  9123:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9124:         return @mapresources;
1.691     raeburn  9125:     }
                   9126:     if ($scancode) {
                   9127:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9128:             @mapresources = @{$orderedforcode->{$scancode}};
                   9129:         } else {
                   9130:             $env{'form.CODE'} = $scancode;
                   9131:             my $actual_seq =
                   9132:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9133:                                                                $master_seq,
                   9134:                                                                $user,$scancode,1);
                   9135:             if (ref($actual_seq) eq 'ARRAY') {
                   9136:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9137:                 if (ref($orderedforcode) eq 'HASH') {
                   9138:                     if (@mapresources > 0) { 
                   9139:                         $orderedforcode->{$scancode} = \@mapresources;
                   9140:                     }
                   9141:                 }
                   9142:             }
                   9143:             delete($env{'form.CODE'});
1.678     raeburn  9144:         }
                   9145:     } else {
                   9146:         my $actual_seq =
                   9147:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9148:                                                            $master_seq,
1.688     raeburn  9149:                                                            $user,undef,1);
1.678     raeburn  9150:         if (ref($actual_seq) eq 'ARRAY') {
                   9151:             @mapresources = 
                   9152:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9153:         }
1.691     raeburn  9154:     }
                   9155:     return @mapresources;
1.678     raeburn  9156: }
                   9157: 
1.542     raeburn  9158: sub grade_student_bubbles {
1.691     raeburn  9159:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9160:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9161:     my $uselookup = 0;
                   9162:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9163:         (ref($startline) eq 'HASH')) {
                   9164:         $uselookup = 1;
                   9165:     }
                   9166: 
1.554     raeburn  9167:     if (ref($resources) eq 'ARRAY') {
                   9168:         my $count = 0;
                   9169:         foreach my $resource (@{$resources}) {
                   9170:             my $ressymb = $resource->symb();
                   9171:             my %form = ('submitted'      => 'scantron',
                   9172:                         'grade_target'   => 'grade',
                   9173:                         'grade_username' => $uname,
                   9174:                         'grade_domain'   => $udom,
                   9175:                         'grade_courseid' => $env{'request.course.id'},
                   9176:                         'grade_symb'     => $ressymb,
                   9177:                         'CODE'           => $scancode
                   9178:                        );
1.649     raeburn  9179:             if ($bubbles_per_row ne '') {
                   9180:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9181:             }
1.663     raeburn  9182:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9183:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9184:             }
1.554     raeburn  9185:             if (ref($parts) eq 'HASH') {
                   9186:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9187:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9188:                         if ($uselookup) {
                   9189:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9190:                         } else {
                   9191:                             $form{'scantron_questnum_start.'.$part} =
                   9192:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9193:                         }
1.554     raeburn  9194:                         $count++;
                   9195:                     }
                   9196:                 }
                   9197:             }
                   9198:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9199:             return 'ssi_error' if ($ssi_error);
                   9200:             last if (&Apache::loncommon::connection_aborted($r));
                   9201:         }
1.542     raeburn  9202:     }
                   9203:     return;
                   9204: }
                   9205: 
1.157     albertel 9206: sub scantron_upload_scantron_data {
1.767     raeburn  9207:     my ($r,$symb) = @_;
1.565     raeburn  9208:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9209:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9210:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9211:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9212:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9213: 							  'domainid',
1.565     raeburn  9214: 							  'coursename',$dom);
                   9215:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9216:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9217:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9218:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9219:     &js_escape(\$nofile_alert);
1.579     raeburn  9220:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
1.736     damieng  9221:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9222:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9223:     function checkUpload(formname) {
                   9224: 	if (formname.upfile.value == "") {
1.579     raeburn  9225: 	    alert("'.$nofile_alert.'");
1.157     albertel 9226: 	    return false;
                   9227: 	}
1.565     raeburn  9228:         if (formname.courseid.value == "") {
1.579     raeburn  9229:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9230:             return false;
                   9231:         }
1.157     albertel 9232: 	formname.submit();
                   9233:     }
1.565     raeburn  9234: 
                   9235:     function ToSyllabus() {
                   9236:         var cdom = '."'$dom'".';
                   9237:         var cnum = document.rules.courseid.value;
                   9238:         if (cdom == "" || cdom == null) {
                   9239:             return;
                   9240:         }
                   9241:         if (cnum == "" || cnum == null) {
                   9242:            return;
                   9243:         }
                   9244:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9245:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9246:         return;
                   9247:     }
                   9248: 
1.754     raeburn  9249:     '.$formatjs.'
1.597     wenzelju 9250: '));
                   9251:     $r->print('
1.648     bisitz   9252: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9253: 
1.492     albertel 9254: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9255: '.$default_form_data.
                   9256:   &Apache::lonhtmlcommon::start_pick_box().
                   9257:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9258:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9259:   &Apache::lonhtmlcommon::row_closure().
                   9260:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9261:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9262:   &Apache::lonhtmlcommon::row_closure().
                   9263:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9264:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9265:   &Apache::lonhtmlcommon::row_closure());
                   9266:     if ($formatoptions) {
                   9267:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9268:                   &Apache::lonhtmlcommon::row_closure());
                   9269:     }
                   9270:     $r->print(
1.565     raeburn  9271:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9272:   '<input type="file" name="upfile" size="50" />'.
                   9273:   &Apache::lonhtmlcommon::row_closure(1).
                   9274:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9275: 
1.492     albertel 9276: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9277: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9278: </form>
1.492     albertel 9279: ');
1.157     albertel 9280:     return '';
                   9281: }
                   9282: 
1.754     raeburn  9283: sub scantron_upload_dataformat {
                   9284:     my ($dom) = @_;
                   9285:     my ($formatoptions,$formattitle,$formatjs);
                   9286:     $formatjs = <<'END';
                   9287: function toggleScantab(form) {
                   9288:    return;
                   9289: }
                   9290: END
                   9291:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9292:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9293:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9294:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9295:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9296:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9297:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9298:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9299:                             my ($onclick,$formatextra,$singleline);
                   9300:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9301:                             my $count = 0;
                   9302:                             foreach my $line (@lines) {
                   9303:                                 next if ($line =~ /^#/);
                   9304:                                 $singleline = $line;
                   9305:                                 $count ++;
                   9306:                             }
                   9307:                             if ($count > 1) {
                   9308:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9309:                                                '<span class="LC_nobreak">'.
                   9310:                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9311:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9312:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9313:                                 $formatjs = <<"END";
1.754     raeburn  9314: function toggleScantab(form) {
                   9315:     var divid = 'bubbletype';
                   9316:     if (document.getElementById(divid)) {
                   9317:         var radioname = 'fileformat';
                   9318:         var num = form.elements[radioname].length;
                   9319:         if (num) {
                   9320:             for (var i=0; i<num; i++) {
                   9321:                 if (form.elements[radioname][i].checked) {
                   9322:                     var chosen = form.elements[radioname][i].value;
                   9323:                     if (chosen == 'dat') {
                   9324:                         document.getElementById(divid).style.display = 'none';
                   9325:                     } else if (chosen == 'csv') {
1.757     raeburn  9326:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9327:                     }
                   9328:                 }
                   9329:             }
                   9330:         }
                   9331:     }
                   9332:     return;
                   9333: }
                   9334: 
                   9335: END
1.756     raeburn  9336:                             } elsif ($count == 1) {
                   9337:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9338:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9339:                             }
                   9340:                             $formattitle = &mt('File format');
                   9341:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9342:                                              &mt('Plain Text (no delimiters)').
                   9343:                                              '</label>'.('&nbsp;'x2).
                   9344:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9345:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9346:                         }
                   9347:                     }
                   9348:                 }
                   9349:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9350:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9351:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9352:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9353:                         $formatoptions = &scantron_scantab();
                   9354:                     }
1.754     raeburn  9355:                 }
                   9356:             }
                   9357:         }
                   9358:     }
                   9359:     return ($formatoptions,$formattitle,$formatjs);
                   9360: }
1.423     albertel 9361: 
1.157     albertel 9362: sub scantron_upload_scantron_data_save {
1.767     raeburn  9363:     my ($r,$symb) = @_;
1.182     albertel 9364:     my $doanotherupload=
                   9365: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9366: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9367: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9368: 	'</form>'."\n";
1.257     albertel 9369:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9370: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9371: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9372:         !&Apache::lonnet::allowed('usc',
                   9373:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9374: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9375: 	unless ($symb) {
1.182     albertel 9376: 	    $r->print($doanotherupload);
                   9377: 	}
1.162     albertel 9378: 	return '';
                   9379:     }
1.257     albertel 9380:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9381:     my $uploadedfile;
1.710     bisitz   9382:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9383:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9384:         $r->print(
                   9385:             &Apache::lonhtmlcommon::confirm_success(
                   9386:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9387:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9388:     } else {
1.754     raeburn  9389:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9390:         my $parser;
                   9391:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9392:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9393:                 my $is_csv;
                   9394:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9395:                 if (@possibles > 1) {
                   9396:                     if ($env{'form.fileformat'} eq 'csv') {
                   9397:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9398:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9399:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9400:                                     $is_csv = 1;
                   9401:                                 }
1.754     raeburn  9402:                             }
                   9403:                         }
                   9404:                     }
                   9405:                 } elsif (@possibles == 1) {
                   9406:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9407:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9408:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9409:                                 $is_csv = 1;
                   9410:                             }
1.754     raeburn  9411:                         }
                   9412:                     }
                   9413:                 }
                   9414:                 if ($is_csv) {
                   9415:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9416:                 }
                   9417:             }
                   9418:         }
                   9419:         my $result =
                   9420:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9421:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9422:         if ($result =~ m{^/uploaded/}) {
                   9423:             $r->print(
                   9424:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9425:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9426:                         (length($env{'form.upfile'})-1),
                   9427:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9428:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9429:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9430:                 my $logname = $uploadedfile;
                   9431:                 $logname =~ s/^scantron_orig_//;
                   9432:                 if ($logname ne '') {
                   9433:                     my $now = time;
                   9434:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9435:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9436:                 }
                   9437:             }
1.567     raeburn  9438:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9439:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9440:         } else {
                   9441:             $r->print(
                   9442:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9443:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9444:                           $result,
1.568     raeburn  9445: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9446: 	}
                   9447:     }
1.174     albertel 9448:     if ($symb) {
1.612     www      9449: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9450:     } else {
1.182     albertel 9451: 	$r->print($doanotherupload);
1.174     albertel 9452:     }
1.157     albertel 9453:     return '';
                   9454: }
                   9455: 
1.567     raeburn  9456: sub validate_uploaded_scantron_file {
1.770     raeburn  9457:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9458: 
1.567     raeburn  9459:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9460:     my @lines;
                   9461:     if ($scanlines ne '-1') {
                   9462:         @lines=split("\n",$scanlines,-1);
                   9463:     }
1.770     raeburn  9464:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9465:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9466:     if ($context eq 'download') {
                   9467:         $priv = 'mgr';
                   9468:     } else {
                   9469:         $priv = 'usc';
                   9470:     }
                   9471:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9472:             (($env{'request.course.id'}) &&
                   9473:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9474:         if ($env{'request.course.sec'} ne '') {
                   9475:             unless (&Apache::lonnet::allowed($priv,
                   9476:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9477:                 unless ($context eq 'download') {
                   9478:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9479:                 }
                   9480:                 return $output;
                   9481:             }
                   9482:             ($checksec,@possibles)=&gradable_sections();
                   9483:         }
                   9484:     }
1.567     raeburn  9485:     if (@lines) {
                   9486:         my (%counts,$max_match_format);
1.710     bisitz   9487:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9488:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9489:         my %idmap = &username_to_idmap($classlist);
                   9490:         foreach my $key (keys(%idmap)) {
                   9491:             my $lckey = lc($key);
                   9492:             $idmap{$lckey} = $idmap{$key};
                   9493:         }
                   9494:         my %unique_formats;
1.754     raeburn  9495:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9496:         foreach my $line (@formatlines) {
                   9497:             chomp($line);
                   9498:             my @config = split(/:/,$line);
                   9499:             my $idstart = $config[5];
                   9500:             my $idlength = $config[6];
                   9501:             if (($idstart ne '') && ($idlength > 0)) {
                   9502:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9503:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9504:                 } else {
                   9505:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9506:                 }
                   9507:             }
                   9508:         }
                   9509:         foreach my $key (keys(%unique_formats)) {
                   9510:             my ($idstart,$idlength) = split(':',$key);
                   9511:             %{$counts{$key}} = (
                   9512:                                'found'   => 0,
                   9513:                                'total'   => 0,
1.770     raeburn  9514:                                'totalanysec' => 0,
                   9515:                                'othersec' => 0,
1.567     raeburn  9516:                               );
                   9517:             foreach my $line (@lines) {
                   9518:                 next if ($line =~ /^#/);
                   9519:                 next if ($line =~ /^[\s\cz]*$/);
                   9520:                 my $id = substr($line,$idstart-1,$idlength);
                   9521:                 $id = lc($id);
                   9522:                 if (exists($idmap{$id})) {
1.770     raeburn  9523:                     if ($checksec ne '') {
                   9524:                         $counts{$key}{'totalanysec'} ++;
                   9525:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9526:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9527:                             if ($stusec ne $checksec) {
                   9528:                                 if (@possibles) {
                   9529:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9530:                                         $counts{$key}{'othersec'} ++;
                   9531:                                         next;
                   9532:                                     }
                   9533:                                 } else {
                   9534:                                     $counts{$key}{'othersec'} ++;
                   9535:                                     next;
                   9536:                                 }
                   9537:                             }
                   9538:                         }
                   9539:                     }
1.567     raeburn  9540:                     $counts{$key}{'found'} ++;
                   9541:                 }
                   9542:                 $counts{$key}{'total'} ++;
                   9543:             }
                   9544:             if ($counts{$key}{'total'}) {
                   9545:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9546:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9547:                     $max_match_pct = $percent_match;
                   9548:                     $max_match_format = $key;
1.710     bisitz   9549:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9550:                     $max_match_count = $counts{$key}{'total'};
                   9551:                 }
                   9552:             }
                   9553:         }
1.770     raeburn  9554:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9555:             my $format_descs;
                   9556:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9557:             for (my $i=0; $i<$numwithformat; $i++) {
                   9558:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9559:                 if ($i<$numwithformat-2) {
                   9560:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9561:                 } elsif ($i==$numwithformat-2) {
                   9562:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9563:                 } elsif ($i==$numwithformat-1) {
                   9564:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9565:                 }
                   9566:             }
                   9567:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9568:             $output .= '<br />';
                   9569:             if ($found_match_count == $max_match_count) {
                   9570:                 # 100% matching entries
                   9571:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9572:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9573:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9574:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9575:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9576:                     ' in the file (for the format defined for [_3]).',
                   9577:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9578:             } else {
                   9579:                 # Not all entries matching? -> Show warning and additional info
                   9580:                 $output .=
                   9581:                     &Apache::lonhtmlcommon::confirm_success(
                   9582:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9583:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9584:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9585:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9586:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9587:                         ' in the file (for the format defined for [_3]).',
                   9588:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9589:                     '<p class="LC_info">'.
                   9590:                     &mt('A low percentage of matches results from one of the following:').
                   9591:                     '</p><ul>'.
                   9592:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9593:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9594:                                '<i>'.$cdom.'</i>').'</li>'.
                   9595:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9596:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9597:                     '</ul>';
                   9598:             }
1.770     raeburn  9599:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9600:                 if ($counts{$max_match_format}{'othersec'}) {
                   9601:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9602:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9603:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9604:                     &js_escape(\$confirmdel);
                   9605:                     $output .= '<p class="LC_warning">'.
                   9606:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
                   9607:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9608:                                '<br />'.
                   9609:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
                   9610:                                '</p><p>'.
                   9611:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9612:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9613:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9614:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9615:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9616:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9617:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9618:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9619:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9620:                                '</form></p>';
                   9621:                 }
                   9622:             }
1.567     raeburn  9623:         }
1.770     raeburn  9624:         if (($context eq 'download') && ($checksec ne '')) {
                   9625:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9626:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9627:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9628:             }
                   9629:         } 
                   9630:     } elsif ($context ne 'download') {
1.710     bisitz   9631:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9632:     }
                   9633:     return $output;
                   9634: }
                   9635: 
1.770     raeburn  9636: sub gradable_sections {
                   9637:     my $checksec = $env{'request.course.sec'};
                   9638:     my @oksecs;
                   9639:     if ($checksec) {
                   9640:         my %availablesecs = &sections_grade_privs();
                   9641:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9642:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9643:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9644:                     push(@oksecs,$sec);
                   9645:                 }
                   9646:             }
                   9647:             if (grep(/^all$/,@oksecs)) {
                   9648:                 undef($checksec);
                   9649:             }
                   9650:         }
                   9651:     }
                   9652:     return($checksec,@oksecs);
                   9653: }
                   9654: 
                   9655: sub sections_grade_privs {
                   9656:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9657:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9658:     my %availablesecs = (
                   9659:                           mgr => [],
                   9660:                           vgr => [],
                   9661:                           usc => [],
                   9662:                         );
                   9663:     my $ccrole = 'cc';
                   9664:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9665:         $ccrole = 'co';
                   9666:     }
                   9667:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9668:                                                      'userroles',['active'],
                   9669:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9670:     my $crsid = $cnum.':'.$cdom;
                   9671:     foreach my $item (keys(%crsroleshash)) {
                   9672:         next unless ($item =~ /^$crsid\:/);
                   9673:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9674:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9675:         if ($sec ne '') {
                   9676:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9677:         }
                   9678:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9679:             foreach my $priv ('mgr','vgr','usc') { 
                   9680:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9681:                     if ($sec eq '') {
                   9682:                         $availablesecs{$priv} = ['all'];
                   9683:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9684:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9685:                             push(@{$availablesecs{$priv}},$sec);
                   9686:                         }
                   9687:                     }
                   9688:                 }
                   9689:             }
                   9690:         } elsif ($role =~ m{^cr/}) {
                   9691:             foreach my $priv ('mgr','vgr','usc') {
                   9692:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9693:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9694:                         if ($sec eq '') {
                   9695:                             $availablesecs{$priv} = ['all'];
                   9696:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9697:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9698:                                 push(@{$availablesecs{$priv}},$sec);
                   9699:                             }
                   9700:                         }
                   9701:                     }
                   9702:                 }
                   9703:             }
                   9704:         }
                   9705:     }
                   9706:     return %availablesecs;
                   9707: }
                   9708: 
                   9709: sub scantron_upload_delete {
                   9710:     my ($r,$symb) = @_;
                   9711:     my $filename = $env{'form.uploadedfile'};
                   9712:     if ($filename =~ /^scantron_orig_/) {
                   9713:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9714:             &Apache::lonnet::allowed('usc',
                   9715:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9716:             &Apache::lonnet::allowed('usc',
                   9717:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9718:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9719:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9720:             if ($retrieval eq '-1') {
                   9721:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9722:                           &mt('File requested for deletion not found.'));
                   9723:             } else {
                   9724:                 $filename =~ s/^scantron_orig_//;
                   9725:                 if ($filename ne '') {
                   9726:                     my ($is_valid,$numleft);
                   9727:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9728:                     if (keys(%info)) {
                   9729:                         if (ref($info{$filename}) eq 'HASH') {
                   9730:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9731:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9732:                                     $is_valid = 1;
                   9733:                                     delete($info{$filename}{$timestamp}); 
                   9734:                                 }
                   9735:                             }
                   9736:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9737:                         }
                   9738:                     }
                   9739:                     if ($is_valid) {
                   9740:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9741:                         if ($result eq 'ok') {
                   9742:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9743:                             if ($numleft) {
                   9744:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9745:                             } else {
                   9746:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9747:                             }
                   9748:                         } else {
                   9749:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9750:                                       &mt('Result was [_1]',$result));
                   9751:                         }
                   9752:                     } else {
                   9753:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9754:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9755:                     }
                   9756:                 } else {
                   9757:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9758:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9759:                 }
                   9760:             }
                   9761:         } else {
                   9762:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9763:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9764:         }
                   9765:     } else {
                   9766:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9767:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9768:     }
                   9769:     return;
                   9770: }
                   9771: 
1.202     albertel 9772: sub valid_file {
                   9773:     my ($requested_file)=@_;
                   9774:     foreach my $filename (sort(&scantron_filenames())) {
                   9775: 	if ($requested_file eq $filename) { return 1; }
                   9776:     }
                   9777:     return 0;
                   9778: }
                   9779: 
                   9780: sub scantron_download_scantron_data {
1.767     raeburn  9781:     my ($r,$symb) = @_;
1.608     www      9782:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9783:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9784:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9785:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9786:     if (! &valid_file($file)) {
1.492     albertel 9787: 	$r->print('
1.202     albertel 9788: 	<p>
1.686     bisitz   9789: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9790:         </p>
1.492     albertel 9791: ');
1.202     albertel 9792: 	return;
                   9793:     }
1.770     raeburn  9794:     my (%uploader,$is_owner,%counts,$percent);
                   9795:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   9796:     if (ref($uploader{$file}) eq 'HASH') {
                   9797:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   9798:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9799:                 $is_owner = 1;
                   9800:                 last;
                   9801:             }
                   9802:         }
                   9803:     }
                   9804:     unless ($is_owner) {
                   9805:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   9806:         if ($counts{'totalanysec'}) {
                   9807:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   9808:             if ($percent_othersec >= 10) {
                   9809:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   9810:                 $r->print('<p class="LC_warning">'.
                   9811:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
                   9812:                           '</p>');
                   9813:                 return;
                   9814:             }
                   9815:         }
                   9816:     }
1.202     albertel 9817:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9818:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9819:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9820:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9821:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9822:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9823:     $r->print('
1.202     albertel 9824:     <p>
1.723     raeburn  9825: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9826: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9827:     </p>
                   9828:     <p>
1.492     albertel 9829: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9830: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9831:     </p>
                   9832:     <p>
1.492     albertel 9833: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9834: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9835:     </p>
1.492     albertel 9836: ');
1.202     albertel 9837:     return '';
                   9838: }
1.157     albertel 9839: 
1.523     raeburn  9840: sub checkscantron_results {
1.608     www      9841:     my ($r,$symb) = @_;
1.523     raeburn  9842:     if (!$symb) {return '';}
                   9843:     my $cid = $env{'request.course.id'};
1.755     raeburn  9844:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9845:     my $numletts = scalar(keys(%lettdig));
                   9846:     my $cnum = $env{'course.'.$cid.'.num'};
                   9847:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9848:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9849:     my %record;
                   9850:     my %scantron_config =
1.754     raeburn  9851:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9852:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  9853:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  9854:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9855:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9856:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9857:     unless (ref($navmap)) {
                   9858:         $r->print(&navmap_errormsg());
                   9859:         return '';
                   9860:     }
1.523     raeburn  9861:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9862:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9863:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9864:     if (ref($map)) { 
                   9865:         $randomorder=$map->randomorder();
1.689     raeburn  9866:         $randompick=$map->randompick();
1.677     raeburn  9867:     }
1.557     raeburn  9868:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9869:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9870:     if ($nav_error) {
                   9871:         $r->print(&navmap_errormsg());
                   9872:         return '';
1.678     raeburn  9873:     }
1.673     raeburn  9874:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9875:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9876:     my ($uname,$udom);
1.523     raeburn  9877:     my (%scandata,%lastname,%bylast);
                   9878:     $r->print('
                   9879: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9880: 
                   9881:     my @delayqueue;
                   9882:     my %completedstudents;
                   9883: 
1.691     raeburn  9884:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9885:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9886:     my ($username,$domain,$started);
1.649     raeburn  9887:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9888:     if ($nav_error) {
                   9889:         $r->print(&navmap_errormsg());
                   9890:         return '';
                   9891:     }
1.523     raeburn  9892: 
1.667     www      9893:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9894:     my $start=&Time::HiRes::time();
                   9895:     my $i=-1;
                   9896: 
                   9897:     while ($i<$scanlines->{'count'}) {
                   9898:         ($username,$domain,$uname)=('','','');
                   9899:         $i++;
                   9900:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9901:         if ($line=~/^[\s\cz]*$/) { next; }
                   9902:         if ($started) {
1.667     www      9903:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9904:         }
                   9905:         $started=1;
                   9906:         my $scan_record=
                   9907:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9908:                                                      $scan_data);
1.693     raeburn  9909:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9910:                                               \%idmap,$i)) {
1.523     raeburn  9911:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9912:                                 'Unable to find a student that matches',1);
                   9913:             next;
                   9914:         }
                   9915:         if (exists $completedstudents{$uname}) {
                   9916:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9917:                                 'Student '.$uname.' has multiple sheets',2);
                   9918:             next;
                   9919:         }
                   9920:         my $pid = $scan_record->{'scantron.ID'};
                   9921:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9922:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9923:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9924:         my $user = $uname.':'.$usec;
1.523     raeburn  9925:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9926: 
1.678     raeburn  9927:         my $scancode;
1.677     raeburn  9928:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9929:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9930:             $scancode = $scan_record->{'scantron.CODE'};
                   9931:         } else {
                   9932:             $scancode = '';
                   9933:         }
                   9934: 
                   9935:         my @mapresources = @resources;
1.691     raeburn  9936:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9937:         my %respnumlookup=();
                   9938:         my %startline=();
1.689     raeburn  9939:         if ($randomorder || $randompick) {
1.678     raeburn  9940:             @mapresources =
1.691     raeburn  9941:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9942:                              \%orderedforcode);
                   9943:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9944:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9945:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9946:                                              \%respnumlookup,\%startline);
                   9947:             if ($randompick && $total) {
                   9948:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9949:             }
1.677     raeburn  9950:         }
1.691     raeburn  9951:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9952:         chomp($scandata{$pid});
                   9953:         $scandata{$pid} =~ s/\r$//;
                   9954: 
1.523     raeburn  9955:         my $counter = -1;
1.677     raeburn  9956:         foreach my $resource (@mapresources) {
1.557     raeburn  9957:             my $parts;
1.554     raeburn  9958:             my $ressymb = $resource->symb();
1.557     raeburn  9959:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9960:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9961:                 my $currcode;
                   9962:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9963:                     $currcode = $scancode;
                   9964:                 }
1.557     raeburn  9965:                 (my $analysis,$parts) =
1.672     raeburn  9966:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9967:                                               $username,$domain,undef,
1.741     raeburn  9968:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9969:             } else {
                   9970:                 $parts = $grader_partids_by_symb{$ressymb};
                   9971:             }
1.542     raeburn  9972:             ($counter,my $recording) =
                   9973:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9974:                                          $scandata{$pid},$parts,
1.691     raeburn  9975:                                          \%scantron_config,\%lettdig,$numletts,
                   9976:                                          $randomorder,$randompick,
                   9977:                                          \%respnumlookup,\%startline);
1.542     raeburn  9978:             $record{$pid} .= $recording;
1.523     raeburn  9979:         }
                   9980:     }
                   9981:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9982:     $r->print('<br />');
                   9983:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9984:     $passed = 0;
                   9985:     $failed = 0;
                   9986:     $numstudents = 0;
                   9987:     foreach my $last (sort(keys(%bylast))) {
                   9988:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9989:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9990:                 my $showscandata = $scandata{$pid};
                   9991:                 my $showrecord = $record{$pid};
                   9992:                 $showscandata =~ s/\s/&nbsp;/g;
                   9993:                 $showrecord =~ s/\s/&nbsp;/g;
                   9994:                 if ($scandata{$pid} eq $record{$pid}) {
                   9995:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9996:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9997: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9998: '</tr>'."\n".
                   9999: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10000: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10001:                     $passed ++;
                   10002:                 } else {
                   10003:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10004:                     $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  10005: '</tr>'."\n".
                   10006: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10007: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10008: '</tr>'."\n";
                   10009:                     $failed ++;
                   10010:                 }
                   10011:                 $numstudents ++;
                   10012:             }
                   10013:         }
                   10014:     }
1.648     bisitz   10015:     $r->print(
                   10016:         '<p>'
                   10017:        .&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).',
                   10018:             '<b>',
                   10019:             $numstudents,
                   10020:             '</b>',
                   10021:             $env{'form.scantron_maxbubble'})
                   10022:        .'</p>'
                   10023:     );
1.682     raeburn  10024:     $r->print('<p>'
1.683     raeburn  10025:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10026:              .'<br />'
                   10027:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10028:              .'</p>'
                   10029:     );
1.523     raeburn  10030:     if ($passed) {
1.572     www      10031:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10032:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10033:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10034:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10035:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10036:                  $okstudents."\n".
                   10037:                  &Apache::loncommon::end_data_table().'<br />');
                   10038:     }
                   10039:     if ($failed) {
1.572     www      10040:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10041:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10042:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10043:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10044:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10045:                  $badstudents."\n".
                   10046:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10047:                  &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  10048:     }
1.614     www      10049:     $r->print('</form><br />');
1.523     raeburn  10050:     return;
                   10051: }
                   10052: 
1.542     raeburn  10053: sub verify_scantron_grading {
1.554     raeburn  10054:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10055:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10056:         $respnumlookup,$startline) = @_;
1.542     raeburn  10057:     my ($record,%expected,%startpos);
                   10058:     return ($counter,$record) if (!ref($resource));
                   10059:     return ($counter,$record) if (!$resource->is_problem());
                   10060:     my $symb = $resource->symb();
1.554     raeburn  10061:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10062:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10063:         $counter ++;
                   10064:         $expected{$part_id} = 0;
1.691     raeburn  10065:         my $respnum = $counter;
                   10066:         if ($randomorder || $randompick) {
                   10067:             $respnum = $respnumlookup->{$counter};
                   10068:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10069:         } else {
                   10070:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10071:         }
                   10072:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10073:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10074:             foreach my $item (@sub_lines) {
                   10075:                 $expected{$part_id} += $item;
                   10076:             }
                   10077:         } else {
1.691     raeburn  10078:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10079:         }
                   10080:     }
                   10081:     if ($symb) {
                   10082:         my %recorded;
                   10083:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10084:         if ($returnhash{'version'}) {
                   10085:             my %lasthash=();
                   10086:             my $version;
                   10087:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10088:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10089:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10090:                 }
                   10091:             }
                   10092:             foreach my $key (keys(%lasthash)) {
                   10093:                 if ($key =~ /\.scantron$/) {
                   10094:                     my $value = &unescape($lasthash{$key});
                   10095:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10096:                     if ($value eq '') {
                   10097:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10098:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10099:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10100:                             }
                   10101:                         }
                   10102:                     } else {
                   10103:                         my @tocheck;
                   10104:                         my @items = split(//,$value);
                   10105:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10106:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10107:                             if (@items < $expected{$part_id}) {
                   10108:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10109:                                 my @singles = split(//,$fragment);
                   10110:                                 foreach my $pos (@singles) {
                   10111:                                     if ($pos eq ' ') {
                   10112:                                         push(@tocheck,$pos);
                   10113:                                     } else {
                   10114:                                         my $next = shift(@items);
                   10115:                                         push(@tocheck,$next);
                   10116:                                     }
                   10117:                                 }
                   10118:                             } else {
                   10119:                                 @tocheck = @items;
                   10120:                             }
                   10121:                             foreach my $letter (@tocheck) {
                   10122:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10123:                                     if ($letter !~ /^[A-J]$/) {
                   10124:                                         $letter = $scantron_config->{'Qoff'};
                   10125:                                     }
                   10126:                                     $recorded{$part_id} .= $letter;
                   10127:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10128:                                     my $digit;
                   10129:                                     if ($letter !~ /^[A-J]$/) {
                   10130:                                         $digit = $scantron_config->{'Qoff'};
                   10131:                                     } else {
                   10132:                                         $digit = $lettdig->{$letter};
                   10133:                                     }
                   10134:                                     $recorded{$part_id} .= $digit;
                   10135:                                 }
                   10136:                             }
                   10137:                         } else {
                   10138:                             @tocheck = @items;
                   10139:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10140:                                 my $curr_sub = shift(@tocheck);
                   10141:                                 my $digit;
                   10142:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10143:                                     $digit = $lettdig->{$curr_sub}-1;
                   10144:                                 }
                   10145:                                 if ($curr_sub eq 'J') {
                   10146:                                     $digit += scalar($numletts);
                   10147:                                 }
                   10148:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10149:                                     if ($j == $digit) {
                   10150:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10151:                                     } else {
                   10152:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10153:                                     }
                   10154:                                 }
                   10155:                             }
                   10156:                         }
                   10157:                     }
                   10158:                 }
                   10159:             }
                   10160:         }
1.554     raeburn  10161:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10162:             if ($recorded{$part_id} eq '') {
                   10163:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10164:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10165:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10166:                     }
                   10167:                 }
                   10168:             }
                   10169:             $record .= $recorded{$part_id};
                   10170:         }
                   10171:     }
                   10172:     return ($counter,$record);
                   10173: }
                   10174: 
1.75      albertel 10175: #-------- end of section for handling grading scantron forms -------
                   10176: #
                   10177: #-------------------------------------------------------------------
                   10178: 
1.72      ng       10179: #-------------------------- Menu interface -------------------------
                   10180: #
1.614     www      10181: #--- Href with symb and command ---
                   10182: 
                   10183: sub href_symb_cmd {
                   10184:     my ($symb,$cmd)=@_;
1.669     raeburn  10185:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10186: }
                   10187: 
1.443     banghart 10188: sub grading_menu {
1.608     www      10189:     my ($request,$symb) = @_;
1.443     banghart 10190:     if (!$symb) {return '';}
                   10191: 
                   10192:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10193:                   'command'=>'individual');
1.538     schulted 10194:     
1.598     www      10195:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10196: 
                   10197:     $fields{'command'}='ungraded';
                   10198:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10199: 
                   10200:     $fields{'command'}='table';
                   10201:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10202: 
                   10203:     $fields{'command'}='all_for_one';
                   10204:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10205: 
1.621     www      10206:     $fields{'command'}='downloadfilesselect';
                   10207:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10208: 
1.443     banghart 10209:     $fields{'command'} = 'csvform';
1.538     schulted 10210:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10211:     
1.443     banghart 10212:     $fields{'command'} = 'processclicker';
1.538     schulted 10213:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10214:     
1.443     banghart 10215:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10216:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10217: 
                   10218:     $fields{'command'} = 'initialverifyreceipt';
                   10219:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10220:     
1.598     www      10221:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10222:             items =>[
1.598     www      10223:                         {	linktext => 'Select individual students to grade',
                   10224:                     		url => $url1a,
1.538     schulted 10225:                     		permission => 'F',
1.636     wenzelju 10226:                     		icon => 'grade_students.png',
1.598     www      10227:                     		linktitle => 'Grade current resource for a selection of students.'
                   10228:                         }, 
1.764     raeburn  10229:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10230:                                 url => $url1b,
                   10231:                                 permission => 'F',
1.636     wenzelju 10232:                                 icon => 'ungrade_sub.png',
1.598     www      10233:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10234:                         },
1.598     www      10235: 
                   10236:                         {       linktext => 'Grading table',
                   10237:                                 url => $url1c,
                   10238:                                 permission => 'F',
1.636     wenzelju 10239:                                 icon => 'grading_table.png',
1.598     www      10240:                                 linktitle => 'Grade current resource for all students.'
                   10241:                         },
1.615     www      10242:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10243:                                 url => $url1d,
                   10244:                                 permission => 'F',
1.636     wenzelju 10245:                                 icon => 'grade_PageFolder.png',
1.598     www      10246:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10247:                         },
                   10248:                         {       linktext => 'Download submissions',
                   10249:                                 url => $url1e,
                   10250:                                 permission => 'F',
1.636     wenzelju 10251:                                 icon => 'download_sub.png',
1.621     www      10252:                                 linktitle => 'Download all students submissions.'
1.598     www      10253:                         }]},
                   10254:                          { categorytitle=>'Automated Grading',
                   10255:                items =>[
                   10256: 
1.538     schulted 10257:                 	    {	linktext => 'Upload Scores',
                   10258:                     		url => $url2,
                   10259:                     		permission => 'F',
                   10260:                     		icon => 'uploadscores.png',
                   10261:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10262:                 	    },
                   10263:                 	    {	linktext => 'Process Clicker',
                   10264:                     		url => $url3,
                   10265:                     		permission => 'F',
                   10266:                     		icon => 'addClickerInfoFile.png',
                   10267:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10268:                 	    },
1.587     raeburn  10269:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10270:                     		url => $url4,
                   10271:                     		permission => 'F',
1.636     wenzelju 10272:                     		icon => 'bubblesheet.png',
1.648     bisitz   10273:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10274:                 	    },
1.616     www      10275:                             {   linktext => 'Verify Receipt Number',
1.602     www      10276:                                 url => $url5,
                   10277:                                 permission => 'F',
1.636     wenzelju 10278:                                 icon => 'receipt_number.png',
1.602     www      10279:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10280:                             }
                   10281: 
1.538     schulted 10282:                     ]
                   10283:             });
                   10284: 
1.443     banghart 10285:     # Create the menu
                   10286:     my $Str;
1.445     banghart 10287:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10288:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10289:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10290: 
1.602     www      10291:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10292:     return $Str;    
                   10293: }
                   10294: 
1.598     www      10295: sub ungraded {
                   10296:     my ($request)=@_;
                   10297:     &submit_options($request);
                   10298: }
                   10299: 
1.599     www      10300: sub submit_options_sequence {
1.608     www      10301:     my ($request,$symb) = @_;
1.599     www      10302:     if (!$symb) {return '';}
1.600     www      10303:     &commonJSfunctions($request);
                   10304:     my $result;
1.599     www      10305: 
1.600     www      10306:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10307:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10308:     $result.=&selectfield(0).
1.601     www      10309:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10310:             <div>
                   10311:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10312:             </div>
                   10313:         </div>
                   10314:   </form>';
                   10315:     return $result;
                   10316: }
                   10317: 
                   10318: sub submit_options_table {
1.608     www      10319:     my ($request,$symb) = @_;
1.600     www      10320:     if (!$symb) {return '';}
1.599     www      10321:     &commonJSfunctions($request);
1.746     raeburn  10322:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10323:     my $result;
                   10324: 
                   10325:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10326:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10327: 
1.745     raeburn  10328:     $result.=&selectfield(1,$is_tool).
1.601     www      10329:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10330:             <div>
                   10331:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10332:             </div>
                   10333:         </div>
                   10334:   </form>';
                   10335:     return $result;
                   10336: }
1.443     banghart 10337: 
1.621     www      10338: sub submit_options_download {
                   10339:     my ($request,$symb) = @_;
                   10340:     if (!$symb) {return '';}
                   10341: 
1.746     raeburn  10342:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10343:     &commonJSfunctions($request);
                   10344: 
                   10345:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10346:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10347:     $result.='
                   10348: <h2>
1.750     raeburn  10349:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10350: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10351:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10352:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10353:             </div>
                   10354:           </div>
1.600     www      10355: 
                   10356: 
1.621     www      10357:   </form>';
                   10358:     return $result;
                   10359: }
                   10360: 
1.443     banghart 10361: #--- Displays the submissions first page -------
                   10362: sub submit_options {
1.608     www      10363:     my ($request,$symb) = @_;
1.72      ng       10364:     if (!$symb) {return '';}
                   10365: 
1.746     raeburn  10366:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10367:     &commonJSfunctions($request);
1.473     albertel 10368:     my $result;
1.533     bisitz   10369: 
1.72      ng       10370:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10371: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10372:     $result.=&selectfield(1,$is_tool).'
1.601     www      10373:                 <input type="hidden" name="command" value="submission" /> 
                   10374: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10375:             </div>
                   10376:           </div>
                   10377:   </form>';
                   10378:     return $result;
                   10379: }
1.533     bisitz   10380: 
1.601     www      10381: sub selectfield {
1.745     raeburn  10382:    my ($full,$is_tool)=@_;
                   10383:    my %options;
                   10384:    if ($is_tool) {
                   10385:        %options =
                   10386:            (&transtatus_options,
                   10387:             'select_form_order' => ['yes','incorrect','all']);
                   10388:    } else {
                   10389:        %options = 
                   10390:            (&substatus_options,
                   10391:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10392:    }
1.601     www      10393:    my $result='<div class="LC_columnSection">
1.537     harmsja  10394:   
1.533     bisitz   10395:     <fieldset>
                   10396:       <legend>
                   10397:        '.&mt('Sections').'
                   10398:       </legend>
1.601     www      10399:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10400:     </fieldset>
1.537     harmsja  10401:   
1.533     bisitz   10402:     <fieldset>
                   10403:       <legend>
                   10404:         '.&mt('Groups').'
                   10405:       </legend>
                   10406:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10407:     </fieldset>
1.537     harmsja  10408:   
1.533     bisitz   10409:     <fieldset>
                   10410:       <legend>
                   10411:         '.&mt('Access Status').'
                   10412:       </legend>
1.601     www      10413:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10414:     </fieldset>';
                   10415:     if ($full) {
1.745     raeburn  10416:         my $heading = &mt('Submission Status');
                   10417:         if ($is_tool) {
                   10418:             $heading = &mt('Transaction Status');
                   10419:         }
                   10420:         $result.='
1.533     bisitz   10421:     <fieldset>
                   10422:       <legend>
1.745     raeburn  10423:         '.$heading.'
1.601     www      10424:       </legend>'.
1.635     raeburn  10425:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10426:    '</fieldset>';
                   10427:     }
                   10428:     $result.='</div><br />';
1.44      ng       10429:     return $result;
1.2       albertel 10430: }
                   10431: 
1.738     raeburn  10432: sub substatus_options {
                   10433:     return &Apache::lonlocal::texthash(
                   10434:                                       'yes'       => 'with submissions',
                   10435:                                       'queued'    => 'in grading queue',
                   10436:                                       'graded'    => 'with ungraded submissions',
                   10437:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10438:                                       'all'       => 'with any status',
                   10439:                                       );
1.738     raeburn  10440: }
                   10441: 
1.745     raeburn  10442: sub transtatus_options {
                   10443:     return &Apache::lonlocal::texthash(
                   10444:                                        'yes'       => 'with score transactions',
                   10445:                                        'incorrect' => 'with less than full credit',
                   10446:                                        'all'       => 'with any status',
                   10447:                                       );
                   10448: }
                   10449: 
1.285     albertel 10450: sub reset_perm {
                   10451:     undef(%perm);
                   10452: }
                   10453: 
                   10454: sub init_perm {
                   10455:     &reset_perm();
1.770     raeburn  10456:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10457: 
                   10458: 	my $scope = $env{'request.course.id'};
                   10459: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10460: 
                   10461: 	    $scope .= '/'.$env{'request.course.sec'};
                   10462: 	    if ( $perm{$test_perm}=
                   10463: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10464: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10465: 	    } else {
                   10466: 		delete($perm{$test_perm});
                   10467: 	    }
1.285     albertel 10468: 	}
                   10469:     }
                   10470: }
                   10471: 
1.674     raeburn  10472: sub init_old_essays {
                   10473:     my ($symb,$apath,$adom,$aname) = @_;
                   10474:     if ($symb ne '') {
                   10475:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10476:         if (keys(%essays) > 0) {
                   10477:             $old_essays{$symb} = \%essays;
                   10478:         }
                   10479:     }
                   10480:     return;
                   10481: }
                   10482: 
                   10483: sub reset_old_essays {
                   10484:     undef(%old_essays);
                   10485: }
                   10486: 
1.400     www      10487: sub gather_clicker_ids {
1.408     albertel 10488:     my %clicker_ids;
1.400     www      10489: 
                   10490:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10491: 
                   10492:     # Set up a couple variables.
1.407     albertel 10493:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10494:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10495:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10496: 
1.407     albertel 10497:     foreach my $student (keys(%$classlist)) {
1.438     www      10498:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10499:         my $username = $classlist->{$student}->[$username_idx];
                   10500:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10501:         my $clickers =
1.408     albertel 10502: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10503:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10504:             $id=~s/^[\#0]+//;
1.421     www      10505:             $id=~s/[\-\:]//g;
1.407     albertel 10506:             if (exists($clicker_ids{$id})) {
1.408     albertel 10507: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10508:             } else {
1.408     albertel 10509: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10510:             }
                   10511:         }
                   10512:     }
1.407     albertel 10513:     return %clicker_ids;
1.400     www      10514: }
                   10515: 
1.402     www      10516: sub gather_adv_clicker_ids {
1.408     albertel 10517:     my %clicker_ids;
1.402     www      10518:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10519:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10520:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10521:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10522:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10523:             my ($puname,$pudom)=split(/\:/,$person);
                   10524:             my $clickers =
1.408     albertel 10525: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10526:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10527: 		$id=~s/^[\#0]+//;
1.421     www      10528:                 $id=~s/[\-\:]//g;
1.408     albertel 10529: 		if (exists($clicker_ids{$id})) {
                   10530: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10531: 		} else {
                   10532: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10533: 		}
1.405     www      10534:             }
1.402     www      10535:         }
                   10536:     }
1.407     albertel 10537:     return %clicker_ids;
1.402     www      10538: }
                   10539: 
1.413     www      10540: sub clicker_grading_parameters {
                   10541:     return ('gradingmechanism' => 'scalar',
                   10542:             'upfiletype' => 'scalar',
                   10543:             'specificid' => 'scalar',
                   10544:             'pcorrect' => 'scalar',
                   10545:             'pincorrect' => 'scalar');
                   10546: }
                   10547: 
1.400     www      10548: sub process_clicker {
1.608     www      10549:     my ($r,$symb)=@_;
1.400     www      10550:     if (!$symb) {return '';}
                   10551:     my $result=&checkforfile_js();
1.632     www      10552:     $result.=&Apache::loncommon::start_data_table().
                   10553:              &Apache::loncommon::start_data_table_header_row().
                   10554:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10555:              &Apache::loncommon::end_data_table_header_row().
                   10556:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10557: # Attempt to restore parameters from last session, set defaults if not present
                   10558:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10559:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10560:                                                  \%Saveable_Parameters);
                   10561:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10562:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10563:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10564:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10565: 
                   10566:     my %checked;
1.521     www      10567:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10568:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10569:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10570:        }
                   10571:     }
                   10572: 
1.632     www      10573:     my $upload=&mt("Evaluate File");
1.400     www      10574:     my $type=&mt("Type");
1.402     www      10575:     my $attendance=&mt("Award points just for participation");
                   10576:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10577:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10578:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10579:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10580:     my $pcorrect=&mt("Percentage points for correct solution");
                   10581:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10582:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10583: 						   {'iclicker' => 'i>clicker',
1.666     www      10584:                                                     'interwrite' => 'interwrite PRS',
                   10585:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10586:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10587:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10588: function sanitycheck() {
                   10589: // Accept only integer percentages
                   10590:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10591:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10592: // Find out grading choice
                   10593:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10594:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10595:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10596:       }
                   10597:    }
                   10598: // By default, new choice equals user selection
                   10599:    newgradingchoice=gradingchoice;
                   10600: // Not good to give more points for false answers than correct ones
                   10601:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10602:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10603:    }
                   10604: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10605:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10606:       document.forms.gradesupload.pcorrect.value=100;
                   10607:       document.forms.gradesupload.pincorrect.value=100;
                   10608:    }
                   10609: // If the values are different, cannot be attendance only
                   10610:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10611:        (gradingchoice=='attendance')) {
                   10612:        newgradingchoice='personnel';
                   10613:    }
                   10614: // Change grading choice to new one
                   10615:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10616:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10617:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10618:       } else {
                   10619:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10620:       }
                   10621:    }
                   10622: // Remember the old state
                   10623:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10624: }
1.597     wenzelju 10625: ENDUPFORM
                   10626:     $result.= <<ENDUPFORM;
1.400     www      10627: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10628: <input type="hidden" name="symb" value="$symb" />
                   10629: <input type="hidden" name="command" value="processclickerfile" />
                   10630: <input type="file" name="upfile" size="50" />
                   10631: <br /><label>$type: $selectform</label>
1.632     www      10632: ENDUPFORM
                   10633:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10634:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10635:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10636: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10637: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10638: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10639: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10640: <br />&nbsp;&nbsp;&nbsp;
                   10641: <input type="text" name="givenanswer" size="50" />
1.413     www      10642: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10643: ENDGRADINGFORM
1.766     raeburn  10644:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10645:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10646:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10647: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10648: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10649: </form>
1.632     www      10650: ENDPERCFORM
                   10651:     $result.='</td>'.
                   10652:              &Apache::loncommon::end_data_table_row().
                   10653:              &Apache::loncommon::end_data_table();
1.400     www      10654:     return $result;
                   10655: }
                   10656: 
                   10657: sub process_clicker_file {
1.766     raeburn  10658:     my ($r,$symb) = @_;
1.400     www      10659:     if (!$symb) {return '';}
1.413     www      10660: 
                   10661:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10662:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10663:                                               \%Saveable_Parameters);
1.598     www      10664:     my $result='';
1.404     www      10665:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10666: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10667: 	return $result;
1.404     www      10668:     }
1.522     www      10669:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10670:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10671:         return $result;
1.521     www      10672:     }
1.522     www      10673:     my $foundgiven=0;
1.521     www      10674:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10675:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10676:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10677:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10678:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10679:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10680:         $foundgiven=$#answers+1;
1.521     www      10681:     }
1.407     albertel 10682:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10683:     my %correct_ids;
1.404     www      10684:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10685: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10686:     }
                   10687:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10688: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10689: 	   $correct_id=~tr/a-z/A-Z/;
                   10690: 	   $correct_id=~s/\s//gs;
                   10691: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10692:            $correct_id=~s/[\-\:]//g;
1.414     www      10693:            if ($correct_id) {
                   10694: 	      $correct_ids{$correct_id}='specified';
                   10695:            }
                   10696:         }
1.400     www      10697:     }
1.404     www      10698:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10699: 	$result.=&mt('Score based on attendance only');
1.521     www      10700:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10701:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10702:     } else {
1.408     albertel 10703: 	my $number=0;
1.411     www      10704: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10705: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10706: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10707: 	    if ($correct_ids{$id} eq 'specified') {
                   10708: 		$result.=&mt('specified');
                   10709: 	    } else {
                   10710: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10711: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10712: 	    }
                   10713: 	    $number++;
                   10714: 	}
1.411     www      10715:         $result.="</p>\n";
1.710     bisitz   10716:         if ($number==0) {
                   10717:             $result .=
                   10718:                  &Apache::lonhtmlcommon::confirm_success(
                   10719:                      &mt('No IDs found to determine correct answer'),1);
                   10720:             return $result;
                   10721:         }
1.404     www      10722:     }
1.405     www      10723:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10724:         $result .=
                   10725:             &Apache::lonhtmlcommon::confirm_success(
                   10726:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10727:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10728:         return $result;
1.405     www      10729:     }
1.760     raeburn  10730:     my $mimetype;
                   10731:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10732:         my $mm = new File::MMagic;
                   10733:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10734:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10735:             $result.= '<p>'.
                   10736:                 &Apache::lonhtmlcommon::confirm_success(
                   10737:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10738:             return $result;
                   10739:         }
                   10740:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10741:         $result .= '<p>'.
                   10742:             &Apache::lonhtmlcommon::confirm_success(
                   10743:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10744:         return $result;
                   10745:     }
1.410     www      10746: 
                   10747: # Were able to get all the info needed, now analyze the file
                   10748: 
1.411     www      10749:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10750:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10751:     $result.=&Apache::loncommon::start_data_table().
                   10752:              &Apache::loncommon::start_data_table_header_row().
                   10753:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10754:              &Apache::loncommon::end_data_table_header_row().
                   10755:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10756: <td>
1.410     www      10757: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10758: <input type="hidden" name="symb" value="$symb" />
                   10759: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10760: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10761: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10762: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10763: ENDHEADER
1.522     www      10764:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10765:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10766:     } 
1.408     albertel 10767:     my %responses;
                   10768:     my @questiontitles;
1.405     www      10769:     my $errormsg='';
                   10770:     my $number=0;
                   10771:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  10772:         if ($mimetype eq 'text/plain') {
                   10773:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10774:         } elsif ($mimetype eq 'text/html') {
                   10775:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10776:         }
                   10777:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10778:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  10779:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      10780:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10781:     }
1.411     www      10782:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10783:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10784:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10785:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10786:              '<br />';
1.522     www      10787:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10788:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10789:        return $result;
1.522     www      10790:     } 
1.414     www      10791: # Remember Question Titles
                   10792: # FIXME: Possibly need delimiter other than ":"
                   10793:     for (my $i=0;$i<$number;$i++) {
                   10794:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10795:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10796:     }
1.411     www      10797:     my $correct_count=0;
                   10798:     my $student_count=0;
                   10799:     my $unknown_count=0;
1.414     www      10800: # Match answers with usernames
                   10801: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10802:     foreach my $id (keys(%responses)) {
1.410     www      10803:        if ($correct_ids{$id}) {
1.414     www      10804:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10805:           $correct_count++;
1.410     www      10806:        } elsif ($clicker_ids{$id}) {
1.437     www      10807:           if ($clicker_ids{$id}=~/\,/) {
                   10808: # More than one user with the same clicker!
1.632     www      10809:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10810:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10811:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10812:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10813:                            "<select name='multi".$id."'>";
                   10814:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10815:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10816:              }
                   10817:              $result.='</select>';
                   10818:              $unknown_count++;
                   10819:           } else {
                   10820: # Good: found one and only one user with the right clicker
                   10821:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10822:              $student_count++;
                   10823:           }
1.410     www      10824:        } else {
1.632     www      10825:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10826:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10827:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10828:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10829:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10830:                    "\n".&mt("Domain").": ".
                   10831:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  10832:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10833:           $unknown_count++;
1.410     www      10834:        }
1.405     www      10835:     }
1.412     www      10836:     $result.='<hr />'.
                   10837:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10838:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10839:        if ($correct_count==0) {
1.696     bisitz   10840:           $errormsg.="Found no correct answers for grading!";
1.412     www      10841:        } elsif ($correct_count>1) {
1.414     www      10842:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10843:        }
                   10844:     }
1.428     www      10845:     if ($number<1) {
                   10846:        $errormsg.="Found no questions.";
                   10847:     }
1.412     www      10848:     if ($errormsg) {
                   10849:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10850:     } else {
                   10851:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10852:     }
1.632     www      10853:     $result.='</form></td>'.
                   10854:              &Apache::loncommon::end_data_table_row().
                   10855:              &Apache::loncommon::end_data_table();
1.614     www      10856:     return $result;
1.400     www      10857: }
                   10858: 
1.405     www      10859: sub iclicker_eval {
1.406     www      10860:     my ($questiontitles,$responses)=@_;
1.405     www      10861:     my $number=0;
                   10862:     my $errormsg='';
                   10863:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10864:         my %components=&Apache::loncommon::record_sep($line);
                   10865:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10866: 	if ($entries[0] eq 'Question') {
                   10867: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10868: 		$$questiontitles[$number]=$entries[$i];
                   10869: 		$number++;
                   10870: 	    }
                   10871: 	}
                   10872: 	if ($entries[0]=~/^\#/) {
                   10873: 	    my $id=$entries[0];
                   10874: 	    my @idresponses;
                   10875: 	    $id=~s/^[\#0]+//;
                   10876: 	    for (my $i=0;$i<$number;$i++) {
                   10877: 		my $idx=3+$i*6;
1.644     www      10878:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10879: 		push(@idresponses,$entries[$idx]);
                   10880: 	    }
                   10881: 	    $$responses{$id}=join(',',@idresponses);
                   10882: 	}
1.405     www      10883:     }
                   10884:     return ($errormsg,$number);
                   10885: }
                   10886: 
1.760     raeburn  10887: sub iclickerxml_eval {
                   10888:     my ($questiontitles,$responses)=@_;
                   10889:     my $number=0;
                   10890:     my $errormsg='';
                   10891:     my @state;
                   10892:     my %respbyid;
                   10893:     my $p = HTML::Parser->new
                   10894:     (
                   10895:         xml_mode => 1,
                   10896:         start_h =>
                   10897:             [sub {
                   10898:                  my ($tagname,$attr) = @_;
                   10899:                  push(@state,$tagname);
                   10900:                  if ("@state" eq "ssn p") {
                   10901:                      my $title = $attr->{qn};
                   10902:                      $title =~ s/(^\s+|\s+$)//g;
                   10903:                      $questiontitles->[$number]=$title;
                   10904:                  } elsif ("@state" eq "ssn p v") {
                   10905:                      my $id = $attr->{id};
                   10906:                      my $entry = $attr->{ans};
                   10907:                      $id=~s/^[\#0]+//;
                   10908:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10909:                      $respbyid{$id}[$number] = $entry;
                   10910:                  }
                   10911:             }, "tagname, attr"],
                   10912:          end_h =>
                   10913:                [sub {
                   10914:                    my ($tagname) = @_;
                   10915:                    if ("@state" eq "ssn p") {
                   10916:                        $number++;
                   10917:                    }
                   10918:                    pop(@state);
                   10919:                 }, "tagname"],
                   10920:     );
                   10921: 
                   10922:     $p->parse($env{'form.upfile'});
                   10923:     $p->eof;
                   10924:     foreach my $id (keys(%respbyid)) {
                   10925:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10926:     }
                   10927:     return ($errormsg,$number);
                   10928: }
                   10929: 
1.419     www      10930: sub interwrite_eval {
                   10931:     my ($questiontitles,$responses)=@_;
                   10932:     my $number=0;
                   10933:     my $errormsg='';
1.420     www      10934:     my $skipline=1;
                   10935:     my $questionnumber=0;
                   10936:     my %idresponses=();
1.419     www      10937:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10938:         my %components=&Apache::loncommon::record_sep($line);
                   10939:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10940:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10941:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10942:         next if $skipline;
                   10943:         if ($entries[0]!=$questionnumber) {
                   10944:            $questionnumber=$entries[0];
                   10945:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10946:            $number++;
1.419     www      10947:         }
1.420     www      10948:         my $id=$entries[4];
                   10949:         $id=~s/^[\#0]+//;
1.421     www      10950:         $id=~s/^v\d*\://i;
                   10951:         $id=~s/[\-\:]//g;
1.420     www      10952:         $idresponses{$id}[$number]=$entries[6];
                   10953:     }
1.524     raeburn  10954:     foreach my $id (keys(%idresponses)) {
1.420     www      10955:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10956:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10957:     }
                   10958:     return ($errormsg,$number);
                   10959: }
                   10960: 
1.666     www      10961: sub turning_eval {
                   10962:     my ($questiontitles,$responses)=@_;
                   10963:     my $number=0;
                   10964:     my $errormsg='';
                   10965:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10966:         my %components=&Apache::loncommon::record_sep($line);
                   10967:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10968:         if ($#entries>$number) { $number=$#entries; }
                   10969:         my $id=$entries[0];
                   10970:         my @idresponses;
                   10971:         $id=~s/^[\#0]+//;
                   10972:         unless ($id) { next; }
                   10973:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10974:             $entries[$idx]=~s/\,/\;/g;
                   10975:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10976:             push(@idresponses,$entries[$idx]);
                   10977:         }
                   10978:         $$responses{$id}=join(',',@idresponses);
                   10979:     }
                   10980:     for (my $i=1; $i<=$number; $i++) {
                   10981:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10982:     }
                   10983:     return ($errormsg,$number);
                   10984: }
                   10985: 
                   10986: 
1.414     www      10987: sub assign_clicker_grades {
1.766     raeburn  10988:     my ($r,$symb) = @_;
1.414     www      10989:     if (!$symb) {return '';}
1.416     www      10990: # See which part we are saving to
1.582     raeburn  10991:     my $res_error;
                   10992:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10993:     if ($res_error) {
                   10994:         return &navmap_errormsg();
                   10995:     }
1.416     www      10996: # FIXME: This should probably look for the first handgradeable part
                   10997:     my $part=$$partlist[0];
                   10998: # Start screen output
1.766     raeburn  10999:     my $result = &Apache::loncommon::start_data_table().
                   11000:                  &Apache::loncommon::start_data_table_header_row().
                   11001:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11002:                  &Apache::loncommon::end_data_table_header_row().
                   11003:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11004: # Get correct result
                   11005: # FIXME: Possibly need delimiter other than ":"
                   11006:     my @correct=();
1.415     www      11007:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11008:     my $number=$env{'form.number'};
                   11009:     if ($gradingmechanism ne 'attendance') {
1.414     www      11010:        foreach my $key (keys(%env)) {
                   11011:           if ($key=~/^form\.correct\:/) {
                   11012:              my @input=split(/\,/,$env{$key});
                   11013:              for (my $i=0;$i<=$#input;$i++) {
                   11014:                  if (($correct[$i]) && ($input[$i]) &&
                   11015:                      ($correct[$i] ne $input[$i])) {
                   11016:                     $result.='<br /><span class="LC_warning">'.
                   11017:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11018:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11019:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11020:                     $correct[$i]=$input[$i];
                   11021:                  }
                   11022:              }
                   11023:           }
                   11024:        }
1.415     www      11025:        for (my $i=0;$i<$number;$i++) {
1.644     www      11026:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11027:              $result.='<br /><span class="LC_error">'.
                   11028:                       &mt('No correct result given for question "[_1]"!',
                   11029:                           $env{'form.question:'.$i}).'</span>';
                   11030:           }
                   11031:        }
1.644     www      11032:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11033:     }
                   11034: # Start grading
1.415     www      11035:     my $pcorrect=$env{'form.pcorrect'};
                   11036:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11037:     my $storecount=0;
1.632     www      11038:     my %users=();
1.415     www      11039:     foreach my $key (keys(%env)) {
1.420     www      11040:        my $user='';
1.415     www      11041:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11042:           $user=$1;
                   11043:        }
                   11044:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11045:           my $id=$1;
                   11046:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11047:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11048:           } elsif ($env{'form.multi'.$id}) {
                   11049:              $user=$env{'form.multi'.$id};
1.420     www      11050:           }
                   11051:        }
1.632     www      11052:        if ($user) {
                   11053:           if ($users{$user}) {
                   11054:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11055:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11056:                       '</span><br />';
                   11057:           }
                   11058:           $users{$user}=1; 
1.415     www      11059:           my @answer=split(/\,/,$env{$key});
                   11060:           my $sum=0;
1.522     www      11061:           my $realnumber=$number;
1.415     www      11062:           for (my $i=0;$i<$number;$i++) {
1.576     www      11063:              if  ($correct[$i] eq '-') {
                   11064:                 $realnumber--;
1.766     raeburn  11065:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11066:                 if ($gradingmechanism eq 'attendance') {
                   11067:                    $sum+=$pcorrect;
1.576     www      11068:                 } elsif ($correct[$i] eq '*') {
1.522     www      11069:                    $sum+=$pcorrect;
1.415     www      11070:                 } else {
1.644     www      11071: # We actually grade if correct or not
                   11072:                    my $increment=$pincorrect;
                   11073: # Special case: numerical answer "0"
                   11074:                    if ($correct[$i] eq '0') {
                   11075:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11076:                          $increment=$pcorrect;
                   11077:                       }
                   11078: # General numerical answer, both evaluate to something non-zero
                   11079:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11080:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11081:                          $increment=$pcorrect;
                   11082:                       }
                   11083: # Must be just alphanumeric
                   11084:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11085:                       $increment=$pcorrect;
1.415     www      11086:                    }
1.644     www      11087:                    $sum+=$increment;
1.415     www      11088:                 }
                   11089:              }
                   11090:           }
1.522     www      11091:           my $ave=$sum/(100*$realnumber);
1.416     www      11092: # Store
                   11093:           my ($username,$domain)=split(/\:/,$user);
                   11094:           my %grades=();
                   11095:           $grades{"resource.$part.solved"}='correct_by_override';
                   11096:           $grades{"resource.$part.awarded"}=$ave;
                   11097:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11098:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11099:                                                  $env{'request.course.id'},
                   11100:                                                  $domain,$username);
                   11101:           if ($returncode ne 'ok') {
                   11102:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11103:           } else {
                   11104:              $storecount++;
                   11105:           }
1.415     www      11106:        }
                   11107:     }
                   11108: # We are done
1.549     hauer    11109:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11110:              '</td>'.
                   11111:              &Apache::loncommon::end_data_table_row().
                   11112:              &Apache::loncommon::end_data_table();
1.614     www      11113:     return $result;
1.414     www      11114: }
                   11115: 
1.582     raeburn  11116: sub navmap_errormsg {
                   11117:     return '<div class="LC_error">'.
                   11118:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11119:            &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  11120:            '</div>';
                   11121: }
1.607     droeschl 11122: 
1.609     www      11123: sub startpage {
1.754     raeburn  11124:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
                   11125:     my %args;
                   11126:     if ($onload) {
                   11127:          my %loaditems = (
                   11128:                         'onload' => $onload,
                   11129:                       );
                   11130:          $args{'add_entries'} = \%loaditems;
                   11131:     }
1.671     raeburn  11132:     if ($nomenu) {
1.754     raeburn  11133:         $args{'only_body'} = 1; 
1.759     raeburn  11134:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
1.671     raeburn  11135:     } else {
                   11136:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11137:         $args{'bread_crumbs'} = $crumbs;
                   11138:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
1.765     raeburn  11139:         if ($env{'request.course.id'}) {
                   11140:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11141:         }
1.671     raeburn  11142:     }
1.613     www      11143:     unless ($nodisplayflag) {
1.759     raeburn  11144:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      11145:     }
1.607     droeschl 11146: }
1.582     raeburn  11147: 
1.622     www      11148: sub select_problem {
                   11149:     my ($r)=@_;
1.632     www      11150:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11151:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11152:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11153:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11154: }
                   11155: 
1.1       albertel 11156: sub handler {
1.41      ng       11157:     my $request=$_[0];
1.434     albertel 11158:     &reset_caches();
1.646     raeburn  11159:     if ($request->header_only) {
                   11160:         &Apache::loncommon::content_type($request,'text/html');
                   11161:         $request->send_http_header;
                   11162:         return OK;
                   11163:     }
                   11164:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11165: 
1.664     raeburn  11166: # see what command we need to execute
                   11167: 
                   11168:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11169:     my $command=$commands[0];
                   11170: 
1.646     raeburn  11171:     &init_perm();
                   11172:     if (!$env{'request.course.id'}) {
1.664     raeburn  11173:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11174:                 ($command =~ /^scantronupload/)) {
                   11175:             # Not in a course.
                   11176:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11177:             return HTTP_NOT_ACCEPTABLE;
                   11178:         }
1.646     raeburn  11179:     } elsif (!%perm) {
                   11180:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11181:         return OK;
1.41      ng       11182:     }
1.646     raeburn  11183:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11184:     $request->send_http_header;
1.646     raeburn  11185: 
1.160     albertel 11186:     if ($#commands > 0) {
                   11187: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11188:     }
1.608     www      11189: 
                   11190: # see what the symb is
                   11191: 
                   11192:     my $symb=$env{'form.symb'};
                   11193:     unless ($symb) {
                   11194:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11195:        $symb=&Apache::lonnet::symbread($url);
                   11196:     }
1.646     raeburn  11197:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11198: 
1.513     foxr     11199:     $ssi_error = 0;
1.637     www      11200:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11201: #
1.637     www      11202: # Not called from a resource, but inside a course
1.601     www      11203: #    
1.622     www      11204:         &startpage($request,undef,[],1,1);
                   11205:         &select_problem($request);
1.41      ng       11206:     } else {
1.104     albertel 11207: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  11208:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   11209:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11210:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11211:                     &choose_task_version_form($symb,$env{'form.student'},
                   11212:                                               $env{'form.userdom'});
                   11213:             }
                   11214:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   11215:             if ($versionform) {
                   11216:                 $request->print($versionform);
                   11217:             }
                   11218:             $request->print('<br clear="all" />');
1.611     www      11219: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  11220:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11221:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11222:                 &choose_task_version_form($symb,$env{'form.student'},
                   11223:                                           $env{'form.userdom'},
                   11224:                                           $env{'form.inhibitmenu'});
                   11225:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   11226:             if ($versionform) {
                   11227:                 $request->print($versionform);
                   11228:             }
                   11229:             $request->print('<br clear="all" />');
                   11230:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11231: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11232:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11233:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11234: 	    &pickStudentPage($request,$symb);
1.103     albertel 11235: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      11236:             &startpage($request,$symb,
                   11237:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11238:                                        {href=>'',text=>'Select student'},
                   11239:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      11240: 	    &displayPage($request,$symb);
1.104     albertel 11241: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11242:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11243:                                        {href=>'',text=>'Select student'},
                   11244:                                        {href=>'',text=>'Grade student'},
                   11245:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11246: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11247: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      11248:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11249:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      11250: 	    &processGroup($request,$symb);
1.104     albertel 11251: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11252:             &startpage($request,$symb);
                   11253: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11254: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11255:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11256: 	    $request->print(&submit_options($request,$symb));
1.598     www      11257:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      11258:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   11259:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11260:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11261:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11262:             $request->print(&submit_options_table($request,$symb));
1.598     www      11263:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11264:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11265:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11266: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11267:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11268: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11269: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11270:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11271:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11272: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11273: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11274:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11275:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11276:                                                                              text=>"Modify grades"},
                   11277:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11278: 	    $request->print(&editgrades($request,$symb));
1.602     www      11279:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11280:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11281:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11282: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11283:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11284:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11285: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11286:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11287:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11288:             $request->print(&process_clicker($request,$symb));
1.400     www      11289:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11290:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11291:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11292:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11293:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11294:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11295:                                        {href=>'', text=>'Process clicker file'},
                   11296:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11297:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11298: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11299:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11300: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11301: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11302:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11303: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11304: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11305:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11306: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11307: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11308: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11309:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11310: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11311: 	    } else {
1.257     albertel 11312: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11313: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11314: 		} else {
1.257     albertel 11315: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11316: 		}
1.627     www      11317:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11318: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11319: 	    }
1.246     albertel 11320: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11321:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11322: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11323: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11324:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11325:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11326: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11327:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11328:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11329:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11330: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11331:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11332: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11333: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11334:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11335: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11336:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11337:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11338:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11339:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11340:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11341:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11342:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11343:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11344:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11345:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11346:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11347:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11348:         } elsif ($command eq 'scantronupload_delete' &&
                   11349:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11350:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11351:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11352:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11353:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11354:             $request->print(&checkscantron_results($request,$symb));
                   11355:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11356:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   11357:             $request->print(&submit_options_download($request,$symb));
                   11358:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11359:             &startpage($request,$symb,
                   11360:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.750     raeburn  11361:     {href=>'', text=>'Download submitted files'}]);
1.621     www      11362:             &submit_download_link($request,$symb);
1.106     albertel 11363: 	} elsif ($command) {
1.620     www      11364:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11365: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11366: 	}
1.2       albertel 11367:     }
1.513     foxr     11368:     if ($ssi_error) {
                   11369: 	&ssi_print_error($request);
                   11370:     }
1.671     raeburn  11371:     if ($env{'form.inhibitmenu'}) {
                   11372:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11373:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11374:         &Apache::lonquickgrades::endGradeScreen($request);
                   11375:     }
1.434     albertel 11376:     &reset_caches();
1.646     raeburn  11377:     return OK;
1.44      ng       11378: }
                   11379: 
1.1       albertel 11380: 1;
                   11381: 
1.13      albertel 11382: __END__;
1.531     jms      11383: 
                   11384: 
                   11385: =head1 NAME
                   11386: 
                   11387: Apache::grades
                   11388: 
                   11389: =head1 SYNOPSIS
                   11390: 
                   11391: Handles the viewing of grades.
                   11392: 
                   11393: This is part of the LearningOnline Network with CAPA project
                   11394: described at http://www.lon-capa.org.
                   11395: 
                   11396: =head1 OVERVIEW
                   11397: 
                   11398: Do an ssi with retries:
1.715     bisitz   11399: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11400: 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
                   11401: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11402: 
                   11403: At least the logic that drives this has been pulled out into loncommon.
                   11404: 
                   11405: 
                   11406: 
                   11407: ssi_with_retries - Does the server side include of a resource.
                   11408:                      if the ssi call returns an error we'll retry it up to
                   11409:                      the number of times requested by the caller.
1.715     bisitz   11410:                      If we still have a problem, no text is appended to the
1.531     jms      11411:                      output and we set some global variables.
                   11412:                      to indicate to the caller an SSI error occurred.  
                   11413:                      All of this is supposed to deal with the issues described
1.715     bisitz   11414:                      in LON-CAPA BZ 5631 see:
1.531     jms      11415:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11416:                      by informing the user that this happened.
                   11417: 
                   11418: Parameters:
                   11419:   resource   - The resource to include.  This is passed directly, without
                   11420:                interpretation to lonnet::ssi.
                   11421:   form       - The form hash parameters that guide the interpretation of the resource
                   11422:                
                   11423:   retries    - Number of retries allowed before giving up completely.
                   11424: Returns:
                   11425:   On success, returns the rendered resource identified by the resource parameter.
                   11426: Side Effects:
                   11427:   The following global variables can be set:
                   11428:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11429:                               It is up to the caller to initialize this to false
                   11430:                               if desired.
                   11431:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11432:                               of the resource that could not be rendered by the ssi
                   11433:                               call.
                   11434:    ssi_error_message   - The error string fetched from the ssi response
                   11435:                               in the event of an error.
                   11436: 
                   11437: 
                   11438: =head1 HANDLER SUBROUTINE
                   11439: 
                   11440: ssi_with_retries()
                   11441: 
                   11442: =head1 SUBROUTINES
                   11443: 
                   11444: =over
                   11445: 
1.671     raeburn  11446: =head1 Routines to display previous version of a Task for a specific student
                   11447: 
                   11448: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11449: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11450: requires a proctor to check-in the student, a new version of the Task will
                   11451: be created when the student is checked in to the new opportunity.
                   11452: 
                   11453: If a particular student has tried two or more versions of a particular task,
                   11454: the submission screen provides a user with vgr privileges (e.g., a Course
                   11455: Coordinator) the ability to display a previous version worked on by the
                   11456: student.  By default, the current version is displayed. If a previous version
                   11457: has been selected for display, submission data are only shown that pertain
                   11458: to that particular version, and the interface to submit grades is not shown.
                   11459: 
                   11460: =over 4
                   11461: 
                   11462: =item show_previous_task_version()
                   11463: 
                   11464: Displays a specified version of a student's Task, as the student sees it.
                   11465: 
                   11466: Inputs: 2
                   11467:         request - request object
                   11468:         symb    - unique symb for current instance of resource
                   11469: 
                   11470: Output: None.
                   11471: 
                   11472: Side Effects: calls &show_problem() to print version of Task, with
                   11473:               version contained in form item: $env{'form.previousversion'}
                   11474: 
                   11475: =item choose_task_version_form()
                   11476: 
                   11477: Displays a web form used to select which version of a student's view of a
                   11478: Task should be displayed.  Either launches a pop-up window, or replaces
                   11479: content in existing pop-up, or replaces page in main window.
                   11480: 
                   11481: Inputs: 4
                   11482:         symb    - unique symb for current instance of resource
                   11483:         uname   - username of student
                   11484:         udom    - domain of student
                   11485:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11486:                   breadcrumbs etc., are displayed
                   11487: 
                   11488: Output: 4
                   11489:         current   - student's current version
                   11490:         displayed - student's version being displayed
                   11491:         result    - scalar containing HTML for web form used to switch to
                   11492:                     a different version (or a link to close window, if pop-up).
                   11493:         js        - javascript for processing selection in versions web form
                   11494: 
                   11495: Side Effects: None.
                   11496: 
                   11497: =item previous_display_javascript()
                   11498: 
                   11499: Inputs: 2
                   11500:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11501:                   breadcrumbs etc., are displayed.
                   11502:         current - student's current version number.
                   11503: 
                   11504: Output: 1
                   11505:         js      - javascript for processing selection in versions web form.
                   11506: 
                   11507: Side Effects: None.
                   11508: 
                   11509: =back
                   11510: 
                   11511: =head1 Routines to process bubblesheet data.
                   11512: 
                   11513: =over 4
                   11514: 
1.531     jms      11515: =item scantron_get_correction() : 
                   11516: 
                   11517:    Builds the interface screen to interact with the operator to fix a
                   11518:    specific error condition in a specific scanline
                   11519: 
                   11520:  Arguments:
                   11521:     $r           - Apache request object
                   11522:     $i           - number of the current scanline
                   11523:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11524:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11525:     $line        - full contents of the current scanline
                   11526:     $error       - error condition, valid values are
                   11527:                    'incorrectCODE', 'duplicateCODE',
                   11528:                    'doublebubble', 'missingbubble',
                   11529:                    'duplicateID', 'incorrectID'
                   11530:     $arg         - extra information needed
                   11531:        For errors:
                   11532:          - duplicateID   - paper number that this studentID was seen before on
                   11533:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11534:                            seen on before
                   11535:          - incorrectCODE - current incorrect CODE 
                   11536:          - doublebubble  - array ref of the bubble lines that have double
                   11537:                            bubble errors
                   11538:          - missingbubble - array ref of the bubble lines that have missing
                   11539:                            bubble errors
                   11540: 
1.691     raeburn  11541:    $randomorder - True if exam folder has randomorder set
                   11542:    $randompick  - True if exam folder has randompick set
                   11543:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11544:                      for current line to question number used for same question
                   11545:                      in "Master Seqence" (as seen by Course Coordinator).
                   11546:    $startline   - Reference to hash where key is question number (0 is first)
                   11547:                   and value is number of first bubble line for current student
                   11548:                   or code-based randompick and/or randomorder.
                   11549: 
                   11550: 
                   11551: 
1.531     jms      11552: =item  scantron_get_maxbubble() : 
                   11553: 
1.582     raeburn  11554:    Arguments:
                   11555:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11556:                       failure to retrieve a navmap object.
                   11557:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11558:        calling routine should trap the error condition and display the warning
                   11559:        found in &navmap_errormsg().
                   11560: 
1.649     raeburn  11561:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11562: 
1.531     jms      11563:    Returns the maximum number of bubble lines that are expected to
                   11564:    occur. Does this by walking the selected sequence rendering the
                   11565:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11566:    for what the current value of the problem counter is.
                   11567: 
                   11568:    Caches the results to $env{'form.scantron_maxbubble'},
                   11569:    $env{'form.scantron.bubble_lines.n'}, 
                   11570:    $env{'form.scantron.first_bubble_line.n'} and
                   11571:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11572:    which are the total number of bubble lines, the number of bubble
1.531     jms      11573:    lines for response n and number of the first bubble line for response n,
                   11574:    and a comma separated list of numbers of bubble lines for sub-questions
                   11575:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11576: 
                   11577: 
                   11578: =item  scantron_validate_missingbubbles() : 
                   11579: 
                   11580:    Validates all scanlines in the selected file to not have any
                   11581:     answers that don't have bubbles that have not been verified
                   11582:     to be bubble free.
                   11583: 
                   11584: =item  scantron_process_students() : 
                   11585: 
1.659     raeburn  11586:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11587: 
                   11588:    The parsed scanline hash is added to %env 
                   11589: 
                   11590:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11591:    foreach resource , with the form data of
                   11592: 
                   11593: 	'submitted'     =>'scantron' 
                   11594: 	'grade_target'  =>'grade',
                   11595: 	'grade_username'=> username of student
                   11596: 	'grade_domain'  => domain of student
                   11597: 	'grade_courseid'=> of course
                   11598: 	'grade_symb'    => symb of resource to grade
                   11599: 
                   11600:     This triggers a grading pass. The problem grading code takes care
                   11601:     of converting the bubbled letter information (now in %env) into a
                   11602:     valid submission.
                   11603: 
                   11604: =item  scantron_upload_scantron_data() :
                   11605: 
1.659     raeburn  11606:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11607: 
                   11608: =item  scantron_upload_scantron_data_save() : 
                   11609: 
                   11610:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11611:    has the correct privileges to do so.
                   11612: 
                   11613: = item scantron_upload_delete() :
                   11614: 
                   11615:    Deletes a previously uploaded bubble information data file, if user
                   11616:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11617: 
                   11618: =item  valid_file() :
                   11619: 
                   11620:    Validates that the requested bubble data file exists in the course.
                   11621: 
                   11622: =item  scantron_download_scantron_data() : 
                   11623: 
                   11624:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11625:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11626:    course.
                   11627: 
                   11628: =item  scantron_validate_ID() : 
                   11629: 
                   11630:    Validates all scanlines in the selected file to not have any
1.556     weissno  11631:    invalid or underspecified student/employee IDs
1.531     jms      11632: 
1.582     raeburn  11633: =item navmap_errormsg() :
                   11634: 
                   11635:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11636:    Should be called whenever the request to instantiate a navmap object fails.
                   11637: 
                   11638: =back
1.582     raeburn  11639: 
1.531     jms      11640: =back
                   11641: 
                   11642: =cut

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